Example #1
0
int compute_tle_from_state_vector( tle_t *tle, const double *state_vect, const int ephem,
                        double *trial_state)
{
   int n_failed_steps = 0, i;
   double state_out[6], best_vect[6], curr_err;
   const double thresh = 1e-12;

   memcpy( trial_state, state_vect, 6 * sizeof( double));
   if( vector_to_tle( tle, state_vect))
      {
      printf( "Immediate failure\n");
      return( -1);
      }
   memcpy( best_vect, state_vect, 6 * sizeof( double));
   compute_new_state_vect( tle, state_out, ephem);
   for( i = 0; i < 6; i++)
      trial_state[i] += state_vect[i] - state_out[i];
   curr_err = total_vector_diff( state_out, state_vect);
   if( verbose)
      show_results( "Initial guess", tle, state_out);
   if( curr_err < thresh)
      printf( "Got it right away\n");
   while( curr_err > thresh && n_failed_steps < 20)
      {
      double new_err = 0.;
      tle_t new_tle = *tle;

      if( vector_to_tle( &new_tle, trial_state))
         {
         memcpy( trial_state, best_vect, 6 * sizeof( double));
         show_results( "Simple failure:", tle, trial_state);
         return( -1);
         }
      compute_new_state_vect( &new_tle, state_out, ephem);
      new_err = total_vector_diff( state_out, state_vect);
      if( new_err > curr_err * .9)
          n_failed_steps++;      /* slow or no convergence */
      if( new_err < curr_err)
         {
         curr_err = new_err;
         *tle = new_tle;
         memcpy( best_vect, trial_state, 6 * sizeof( double));
         if( verbose)
            {
            printf( "New record %f\n", curr_err);
            show_results( NULL, tle, state_out);
            }
         }
      for( i = 0; i < 6; i++)
          trial_state[i] += state_vect[i] - state_out[i];
      }
   memcpy( trial_state, best_vect, 6 * sizeof( double));
   return( curr_err > thresh);
}
Example #2
0
int main() 
{
  char **unique, filename[80], word[80];
  int counts[31], size = 10, i, count = 0;
  FILE *fp;
  unique = malloc(10 * sizeof(char*));
  printf("Filename: ");
  scanf("%s", filename);
  
  if((fp = fopen(filename, "r")) == NULL)
  {
    printf("Unable to read %s.\n", filename);
    return -1;
  }  // if not able to open file
  
  for(i = 0; i <= 30; i++)    
    counts[i] = 0;
  
  while(fscanf(fp, "%s", word) != EOF)
    unique = processWord(unique, counts, &size, &count, word);
  
  show_results(counts, count, size);
  free_unique(unique, count);
  
  return 0;
} // main()
Example #3
0
File: rds.c Project: aclisp/myqperf
/*
 * Measure RDS bandwidth (client side).
 */
void
run_client_rds_bw(void)
{
    char *buf;
    int sockfd;

    par_use(L_ACCESS_RECV);
    par_use(R_ACCESS_RECV);
    set_parameters(8*1024);
    client_send_request();
    sockfd = init();
    buf = qmalloc(Req.msg_size);
    sync_test();
    while (!Finished) {
        int n = sendto(sockfd, buf, Req.msg_size, 0, (SA *)&RAddr, RLen);

        if (Finished)
            break;
        if (n != Req.msg_size) {
            LStat.s.no_errs++;
            continue;
        }
        LStat.s.no_bytes += n;
        LStat.s.no_msgs++;
    }
    stop_test_timer();
    exchange_results();
    free(buf);
    close(sockfd);
    show_results(BANDWIDTH);
}
Example #4
0
 void
 handle_run(ThroughputCommand & an_instance)
 {
    if( an_instance.command == THROUGHPUT_COMMAND_START)
      {
        logres = true;
        reset_results();
        interval_data_length_ = an_instance.data_length;
        demand_ = an_instance.current_publisher_effort;
        ACE_High_Res_Timer::gettimeofday_hr ().to_usec (first_time_);
     }
   if( an_instance.command == THROUGHPUT_COMMAND_COMPLETE)
    {
      logres = false;
      ACE_UINT64 last_time;
      ACE_High_Res_Timer::gettimeofday_hr ().to_usec (last_time);
      interval_time_ =  (last_time  - first_time_);
      ++run_;
      show_results();
      if(an_instance.current_publisher_effort ==
         an_instance.final_publisher_effort)
        {
          shutdown_flag = true;
        }
    }
 }
Example #5
0
void MainWindow::setMode(MainWindow::Mode mode)
{
    bool trigger;
    if(pic_item.scene())
        scene.removeItem(&pic_item);
    switch(mode){
    case MainWindow::GUIMode:{
        trigger = true;
        ui->statusBar->clearMessage();
        QVector<qreal> tmp;
        tmp.resize(5);
        show_results(tmp);
        pic_item.pixmap().mask().clear();
        break;
    }
    case MainWindow::DialogMode:{
        trigger = false;
        ui->statusBar->showMessage(QString("Підготовка навчальної вибірки, зображення %1/%2, об'єм вибірки %3").arg(cur_index+1).arg(result_imageName.size()).arg(sample.size()));
        break;
    }
    default:
        return;
        break;
    }
    ui->toolBox->widget(1)->setEnabled(trigger);
    ui->pushButton_file_path->setEnabled(trigger);
    ui->radioButton_by_features->setEnabled(trigger);
    ui->radioButton_by_images->setEnabled(trigger);

    ui->pushButton_cancel->setEnabled(!trigger);
    ui->pushButton_ok->setEnabled(!trigger);
    ui->pushButton_skip->setEnabled(!trigger);
    ui->pushButton_stop->setEnabled(!trigger);
}
Example #6
0
File: main.cpp Project: CCJY/coliru
int main()
{
   std::istringstream stm( "123 456" ) ;
   int i ;

   stm >> i ;
   show_results( stm ) ;
   // bad: false   fail: false   eof: false   good: true   bool(stm): true   !stm: false

   stm >> i ;
   show_results( stm ) ;
   // bad: false   fail: false   eof: true   good: false   bool(stm): true   !stm: false

   stm >> i ;
   show_results( stm ) ;
   // bad: false   fail: true   eof: true   good: false   bool(stm): false   !stm: true
}
Example #7
0
static void
event_exit(void)
{
    show_results();
    drmgr_unregister_cls_field(event_thread_context_init,
                               event_thread_context_exit,
                               tcls_idx);
    drmgr_exit();
}
Example #8
0
File: isql.c Project: nevali/libsql
static int
exec_queries(History *hist)
{
	HistEvent ev;
	size_t c;
	SQL_STATEMENT *rs;
	unsigned int cols;
	unsigned long long rows;
	
	for(c = 0; c < pquery_count; c++)
	{
		history(hist, &ev, H_ADD, pqueries[c].query);
		if(pqueries[c].query[0] == '\\')
		{
			exec_builtin(sql_conn, hist, pqueries[c].query);
			continue;
		}
		if(!sql_conn)
		{
			printf("[08003] Not connected to database server\n");
			continue;
		}
		rs = sql_query(sql_conn, pqueries[c].query);
		if(!rs)
		{
			printf("[%s] %s\n", sql_sqlstate(sql_conn), sql_error(sql_conn));
			return -1;
		}
		cols = sql_stmt_columns(rs);
		if(!cols)
		{
			printf("%qu rows affected.\n", sql_stmt_affected(rs));
			sql_stmt_destroy(rs);
			return 0;
		}
		if(pqueries[c].output_mode == 'G')
		{
			show_results_long(rs);
		}
		else
		{
			show_results(rs);
		}
		rows = sql_stmt_rows(rs);
		if(rows == 1)
		{
			printf("1 row in set.\n");
		}
		else
		{
			printf("%qu rows in set.\n", rows);
		}		
		sql_stmt_destroy(rs);
	}
	return 0;
}
Example #9
0
/* -----------------------------------------------------------------------------------*/
void ProcessMT_Main(){
	struct get_my_error_type g_m_e;

	printf("Main Process starts ...\n ");

	g_m_e = checkgetmyid(NO_ERROR);

	show_results(g_m_e);

}
Example #10
0
// -------------------------------------------------------------------
void COPLANAR::analyze()
{
    getProperties();

    /* compute coplanar parameters */
    calc();

    /* print results in the subwindow */
    show_results();
}
Example #11
0
/*
 * synthesize - synthesis function
 */
void rectwaveguide::synthesize ()
{
  double lambda_g, k, beta;

  /* Get and assign substrate parameters */
  get_rectwaveguide_sub();

  /* Get and assign component parameters */
  get_rectwaveguide_comp();
      
  /* Get and assign electrical parameters */
  get_rectwaveguide_elec();

  /* Get and assign physical parameters */
  get_rectwaveguide_phys();


  if (isSelected ("b")) {
    /* solve for b */
    b = Z0 * a * sqrt(1.0 - pow((fc(1,0)/f),2.0))/
      (2. * ZF0);
    setProperty ("b", b, UNIT_LENGTH, LENGTH_M);
  } else if (isSelected ("a")) {
    /* solve for a */
    a = sqrt(pow((2.0 * ZF0 * b/Z0), 2.0) + 
		 pow((C0/(2.0 * f)),2.0));
    setProperty ("a", a, UNIT_LENGTH, LENGTH_M);
  }

  k = kval ();
  beta = sqrt(pow(k,2.) - pow(kc(1,0),2.0));
  lambda_g = (2. * M_PI)/beta;
  l = (ang_l * lambda_g)/(2.0 * M_PI);    /* in m */

  setProperty ("L", l, UNIT_LENGTH, LENGTH_M);

  if (kc(1,0) <= k) {
    /*propagating modes */
    beta = sqrt(pow(k,2.) - pow(kc(1,0),2.0));
    lambda_g = (2. * M_PI)/beta;
    atten_cond = alphac () * l;
    atten_dielectric = alphad () * l;
    er_eff = (1.0 - pow((fc(1,0)/f),2.0));
  } else { 
    /*evanascent modes */	
    Z0 = 0;
    ang_l = 0;
    er_eff = 0;
    atten_dielectric = 0.0;
    atten_cond = alphac_cutoff () * l;
  }

  show_results ();
}
Example #12
0
static void
event_exit(void)
{
    show_results();
    if (!drmgr_unregister_cls_field(event_thread_context_init,
                                    event_thread_context_exit,
                                    tcls_idx) ||
        !drmgr_unregister_pre_syscall_event(event_pre_syscall) ||
        !drmgr_unregister_post_syscall_event(event_post_syscall))
        DR_ASSERT(false && "failed to unregister");
    drmgr_exit();
}
Example #13
0
bool download(category cat, const char* name)
{
	int count = DownloadSearch(DL_ANY, cat, name);
	if (count<=0) {
		LOG_ERROR("Couldn't find %s",name);
		return false;
	}
	for (int i=0; i<count; i++) {
		DownloadAdd(i);
	}
	show_results(count);
	return true;
}
Example #14
0
int main(int argc, char ** argv) 
{
    /**** In Defaults.h ****/
    struct global_t global;
    struct const_t constant;
    struct stats_t stats;
    struct display_t dpy;
    /***********************/

    /***************** In Initialize.h *****************/
    init(&global, &constant, &stats, &dpy, &argc, &argv);
    /***************************************************/

    // Each process starts a loop to run the simulation 
    // for the specified number of days
    for(global.current_day = 0; global.current_day <= constant.total_number_of_days; 
        global.current_day++)
    {
        /****** In Infection.h ******/
        find_infected(&global);
        /****************************/

        /**************** In Display.h *****************/
        #if defined(X_DISPLAY) || defined(TEXT_DISPLAY)

        do_display(&global, &constant, &dpy);

        throttle(&constant);

        #endif
        /***********************************************/

        /************** In Core.h *************/
        move(&global, &constant);       

        susceptible(&global, &constant, &stats);

        infected(&global, &constant, &stats);

        update_days_infected(&global, &constant);
        /**************************************/
    }

    /******** In Finialize.h ********/
    show_results(&global, &stats);

    cleanup(&global, &constant, &dpy);
    /********************************/

    exit(EXIT_SUCCESS);
}
void infomap_weighted_test(const igraph_t * g, const igraph_vector_t *weights){
  igraph_vector_t membership;
  igraph_real_t codelength = 1000;
  igraph_vector_init(&membership, 0);

  igraph_community_infomap(/*in */ g, /*e_weight=*/ weights, NULL, /*nb_trials=*/5,
                           /*out*/ &membership, &codelength);
  if(igraph_vcount(g) > 500)
      show_results_lite(&membership, codelength);
  else
      show_results(&membership, codelength);

  igraph_vector_destroy(&membership);
}
Example #16
0
/**
 *  指定した範囲の結果を表示する関数
 */
void show_results_in_range(void)
{
    int offset, n_display;          // 結果のオフセットと表示数
    
    printf("\nHow many results do you want to display?\n");
    printf("Offset > ");
    offset = read_input_as_int();       // offsetを入力
    if (offset < 0) offset = 0;
    
    printf("How many > ");
    n_display = read_input_as_int();    // 表示数を入力
    if (n_display < 0)  n_display = 0;
    
    show_results(offset, n_display);    // 結果の表示
    putchar('\n');
}
/*
 * analysis function
 */
void MICROSTRIP::analyze()
{
    /* Get and assign substrate parameters */
    get_microstrip_sub();

    /* Get and assign component parameters */
    get_microstrip_comp();

    /* Get and assign physical parameters */
    get_microstrip_phys();

    /* compute microstrip parameters */
    calc();

    /* print results in the subwindow */
    show_results();
}
Example #18
0
int read_result (const alarm_stage * asp)
{
  uint8_t data[3];
  int rc;

  rc = iBSPACMi2cRead(asp->tpp, SHT21_ADDRESS, data, sizeof(data));
  if ((0 <= rc) && (0 == sht21_crc(data, rc))) {
    rc = ((data[0] << 8) | data[1]) & ~0x03;
    if (asp->cmd) {
      t_raw = rc;
      rc = send_read(asp);
    } else {
      rh_raw = rc;
      show_results(asp);
    }
  }
  return rc;
}
Example #19
0
/*
 * analyze - analysis function
 */
void rectwaveguide::analyze ()
{
  double lambda_g;
  double k;
  double beta;

  /* Get and assign substrate parameters */
  get_rectwaveguide_sub();

  /* Get and assign component parameters */
  get_rectwaveguide_comp();
      
  /* Get and assign physical parameters */
  get_rectwaveguide_phys();

  k = kval ();
      
  if (kc (1,0) <= k) {
    /* propagating modes */
    beta = sqrt (pow (k, 2.0) - pow (kc (1,0), 2.0));
    lambda_g = 2.0 * M_PI / beta;
    /* Z0 = (k * ZF0) / beta; */
    Z0 = k * ZF0 / beta;

    /* calculate electrical angle */
    lambda_g = 2.0 * M_PI / beta;
    ang_l = 2.0 * M_PI * l / lambda_g;    /* in radians */
    atten_cond = alphac () * l;
    atten_dielectric = alphad () * l;
    er_eff = (1.0 - pow ((fc (1,0) / f), 2.0));
  } else { 
    /* evanascent modes */	
    Z0 = 0;
    ang_l = 0;
    er_eff = 0;
    atten_dielectric = 0.0;
    atten_cond = alphac_cutoff () * l;
  }

  setProperty ("Z0", Z0, UNIT_RES, RES_OHM);
  setProperty ("Ang_l", ang_l, UNIT_ANG, ANG_RAD);

  show_results ();
}
Example #20
0
int main (int argc, char **argv) {

  SPICEDOUBLE_CELL(cnfine,2);
  SPICEDOUBLE_CELL(result,2*MAXWIN);
  furnsh_c("/home/user/BCGIT/ASTRO/standard.tm");
  wninsd_c((SYEAR-2000.)*31556952.,(EYEAR-2000.)*31556952.,&cnfine);

  // all of DE431
  // wninsd_c (-479695089600.+86400*468, 479386728000., &cnfine);

  // 1 second tolerance (serious overkill, but 1e-6 is default, worse!)
  gfstol_c(1.);

  // NOTE: putting MAXSEP below is harmless if cond is LOCMIN or something
  gfuds_c(GFQ,gfdecrx,COND,MAXSEP,0.,86400.,MAXWIN,&cnfine,&result);
  show_results(LABEL,result,GFQ);

  return(0);
}
Example #21
0
File: rds.c Project: aclisp/myqperf
/*
 * Measure RDS latency (client side).
 */
void
run_client_rds_lat(void)
{
    char *buf;
    int sockfd;

    set_parameters(1);
    client_send_request();
    sockfd = init();
    buf = qmalloc(Req.msg_size);
    sync_test();
    while (!Finished) {
        int n = sendto(sockfd, buf, Req.msg_size, 0, (SA *)&RAddr, RLen);

        if (Finished)
            break;
        if (n != Req.msg_size) {
            LStat.s.no_errs++;
            continue;
        }
        LStat.s.no_bytes += n;
        LStat.s.no_msgs++;

        n = read(sockfd, buf, Req.msg_size);
        if (Finished)
            break;
        if (n != Req.msg_size) {
            LStat.r.no_errs++;
            continue;
        }
        LStat.r.no_bytes += n;
        LStat.r.no_msgs++;
    }
    stop_test_timer();
    exchange_results();
    free(buf);
    close(sockfd);
    show_results(LATENCY);
}
Example #22
0
static void
put_results(struct Datum *res)
{
  if (show_count)
    printf("%lu\n",(unsigned long)res->count);
  else if (res->count)
    {
      if (xmldir)
	xmldir_results(xmldir,res->count);
      if ('v' == id_prefix(res->l.l8p[0]->text_id))
	{
	  if (!strcmp(return_index, "cat"))
	    vid_display_proj = vid_proj_xmd;
	  else
	    vid_display_proj = vid_proj_xtf;
	  vid_show_results(res);
	}
      else
	show_results(res);
    }
  else if (xmldir)
    xmldir_results(xmldir,res->count);
}
Example #23
0
/* -----------------------------------------------------------------------------------*/
void Process3(void){
	struct stop_error_type c_s;
	APEX_BYTE data[MAX_LENGTH];
	char sal_code[MAX_CAD];
	PROCESS_ID_TYPE procMainId2;
	RETURN_CODE_TYPE retCode;
	BLACKBOARD_ID_TYPE bbId;

	printf("Process 3 starts ... \n");

	strcpy(data, "OK");

	/* To get the procMainId2 value */
	GET_PROCESS_ID("tProc2", &procMainId2, &retCode);
	CHECK_CODE(": GET_PROCESS_ID Process 2", retCode, sal_code);
    printf("%s\n", sal_code);

	/* To check stop process 2 */
	c_s = check_stop(procMainId2, NO_ERROR);

	GET_BLACKBOARD_ID(BLACKBOARD_NAME_0, &bbId, &retCode);
	CHECK_CODE(": GET_BLACKBOARD_ID_0 by Process3", retCode, sal_code);
	printf("%s\n", sal_code);

	DISPLAY_BLACKBOARD (bbId, data, 3, &retCode);
	CHECK_CODE(": DISPLAY_BLACKBOARD B1 in Process 3", retCode, sal_code);
    printf("%s\n", sal_code);

	START(procMainId2, &retCode);
	CHECK_CODE(": START Process 2", retCode, sal_code);
    printf("%s\n", sal_code);

	show_results(c_s);

    STOP_SELF ();
}
Example #24
0
int main() {
    int num_spins = 1;	     // spins per trial
    int	num_wins;	     // wins per trial
    clock_t start_t, stop_t; // wall clock elapsed time

    start_t = clock();
    srand( time(NULL) );

    printf("\n Starting simulation...\n\n");
    printf(" ---------------------------------------------------\n");
    printf(" | Number of spins | Number of wins | Percent wins |\n");
    printf(" ---------------------------------------------------\n");

    /*
     * begin simulation
     */		
    while (num_spins < MAX) {
	// spin wheel
	num_wins = get_num_wins(num_spins);
	// print results
	show_results(num_spins, num_wins);
	// double spins for next simulation
	num_spins += num_spins;
    }

    /*
     * all done
     */
    stop_t = clock();
    printf(" ---------------------------------------------------\n\n");
    printf(" Elapsed wall clock time: %7.2f\n\n", 
	   (double)(stop_t-start_t) / CLOCKS_PER_SEC);
    printf(" *** Normal Termination ***\n\n");
    
    return 0;
}
Example #25
0
void MainWindow::on_pushButton_file_path_clicked()
{

    QFile file;
    QTextStream stream(&file);
    if(ui->radioButton_by_images->isChecked())
        file.setFileName("sources/image_sample.txt");
    else
        file.setFileName("sources/feature_sample.txt");

    if(!QFile::exists(file.fileName()) || !stream.device()->open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(this, "Помилка", QString("Неможливо відкрити файл \"%1\". Перевірте правильність вводу файла.").arg(file.fileName()));
        return;
    }
//
    result_imageName.clear();
    sample.clear();
    cur_index = 0;
//
    QString str;
    QTextStream s_stream(&str,QIODevice::ReadOnly);
    try{
        if(ui->radioButton_by_images->isChecked()){
            dir_path = stream.readLine();
            stream.readLine();
            stream.readLine();
            for(str = stream.readLine(); str.size(); str = stream.readLine(),s_stream.seek(0))
            {
                QPair<QVector<qreal>, QString> pair;
                pair.first.resize(5);
                s_stream >> pair.first[0];//first column
                for(int i = 0; i < 5; i++){
                    s_stream >> pair.first[i];
                    pair.first[i]=(pair.first[i]-1)/4;
                }
                s_stream >> pair.second;

                result_imageName.append(pair);
                str.clear();

                setMode(MainWindow::DialogMode);
                if(open_rec_img(dir_path + result_imageName[cur_index].second))
                    show_results(result_imageName[cur_index].first);
                else
                    on_pushButton_skip_clicked();
            }
        }else
        {
            stream.readLine();
            stream.readLine();
            for(str = stream.readLine(); str.size(); str = stream.readLine(),s_stream.seek(0))
            {
                QPair<QVector<qreal>, QVector<qreal> > pair;

                pair.second.resize(5);
                for(int i = 0; i < pair.second.size(); i++)
                    s_stream >> pair.second[i];

                QString tmp;
                s_stream >> tmp;

                pair.first.resize(21);
                for(int i = 0; i < pair.first.size(); i++)
                    s_stream >> pair.first[i];

                sample.append(pair);
                str.clear();
            }

            emit train_sample_inputed(sample);
        }
    }
Example #26
0
/* the main program body */
int main(int argc, char *argv[])
{
   ALLEGRO_PATH *font_path;
   int w = 0, h = 0;
   int www = FALSE;
   int i, n;
   int display_flags = ALLEGRO_GENERATE_EXPOSE_EVENTS;

   srand(time(NULL));
   
   al_set_org_name("liballeg.org");
   al_set_app_name("SPEED");

   if (!al_init()) {
      fprintf(stderr, "Could not initialise Allegro.\n");
      return 1;
   }
   al_init_primitives_addon();

   /* parse the commandline */
   for (i=1; i<argc; i++) {
      if (strcmp(argv[i], "-cheat") == 0) {
         cheat = TRUE;
      }
      else if (strcmp(argv[i], "-simple") == 0) {
         low_detail = TRUE;
      }
      else if (strcmp(argv[i], "-nogrid") == 0) {
         no_grid = TRUE;
      }
      else if (strcmp(argv[i], "-nomusic") == 0) {
         no_music = TRUE;
      }
      else if (strcmp(argv[i], "-www") == 0) {
         www = TRUE;
      }
      else if (strcmp(argv[i], "-fullscreen") == 0) {
         /* if no width is specified, assume fullscreen_window */
         display_flags |= w ? ALLEGRO_FULLSCREEN : ALLEGRO_FULLSCREEN_WINDOW;
      }
      else {
         n = atoi(argv[i]);

         if (!n) {
            usage();
            return 1;
         }

         if (!w) {
            w = n;
            if (display_flags & ALLEGRO_FULLSCREEN_WINDOW) {
               /* toggle from fullscreen_window to fullscreen */
               display_flags &= ~ALLEGRO_FULLSCREEN_WINDOW;
               display_flags |= ALLEGRO_FULLSCREEN;
            }
         }
         else if (!h) {
            h = n;
         }
         else {
            usage();
            return 1;
         }
      }
   }

   /* it's a real shame that I had to take this out! */
   if (www) {
      printf(
	 "\n"
	 "Unfortunately the built-in web browser feature had to be removed.\n"
	 "\n"
	 "I did get it more or less working as of Saturday evening (forms and\n"
	 "Java were unsupported, but tables and images were mostly rendering ok),\n"
	 "but the US Department of Justice felt that this was an unacceptable\n"
	 "monopolistic attempt to tie in web browsing functionality to an\n"
	 "unrelated product, so they threatened me with being sniped at from\n"
	 "the top of tall buildings by guys with high powered rifles unless I\n"
	 "agreed to disable this code.\n"
	 "\n"
	 "We apologise for any inconvenience that this may cause you.\n"
      );

      return 1;
   }
   
   if (!w || !h) {
      if (argc == 1 || (display_flags & ALLEGRO_FULLSCREEN_WINDOW)) {
         w = 640;
         h = 480;
      }
      else {
         usage();
         return 1;
      }
   }

   /* set the screen mode */
   al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_SUGGEST);
   al_set_new_display_option(ALLEGRO_SAMPLES, 4, ALLEGRO_SUGGEST);

   al_set_new_display_flags(display_flags);
   screen = al_create_display(w, h);
   if (!screen) {
      fprintf(stderr, "Error setting %dx%d display mode\n", w, h);
      return 1;
   }

   al_init_image_addon();

   /* The Allegro 5 port introduced an external data dependency, sorry.
    * To avoid performance problems on graphics drivers that don't support
    * drawing to textures, we build up transition screens on memory bitmaps.
    * We need a font loaded into a memory bitmap for those, then a font
    * loaded into a video bitmap for the game view. Blech!
    */
   font_path = get_resources_path();
   al_set_path_filename(font_path, "a4_font.tga");

   al_init_font_addon();
   al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
   font = al_load_bitmap_font(al_path_cstr(font_path, '/'));
   if (!font) {
      fprintf(stderr, "Error loading %s\n", al_path_cstr(font_path, '/'));
      return 1;
   }

   al_set_new_bitmap_flags(ALLEGRO_VIDEO_BITMAP);
   font_video = al_load_bitmap_font(al_path_cstr(font_path, '/'));
   if (!font_video) {
      fprintf(stderr, "Error loading %s\n", al_path_cstr(font_path, '/'));
      return 1;
   }
   
   al_destroy_path(font_path);

   /* set up everything else */
   al_install_keyboard();
   al_install_joystick();
   if (al_install_audio()) {
      if (!al_reserve_samples(8))
         al_uninstall_audio();
   }

   init_input();
   init_sound();
   init_hiscore();

   /* the main program body */
   while (title_screen()) {
      if (play_game()) {
	 show_results();
	 score_table();
      }
   }

   /* time to go away now */
   shutdown_hiscore();
   shutdown_sound();

   goodbye();

   shutdown_input();

   al_destroy_font(font);
   al_destroy_font(font_video);

   return 0;
}
Example #27
0
// -------------------------------------------------------------------
void COPLANAR::synthesize()
{
    double Z0_dest, Z0_current, Z0_result, increment, slope, error;
    int    iteration;

    getProperties();

    /* required value of Z0 */
    Z0_dest = Z0;

    /* Newton's method */
    iteration = 0;

    /* compute coplanar parameters */
    calc();
    Z0_current = Z0;

    error = fabs( Z0_dest - Z0_current );

    while( error > MAX_ERROR )
    {
        iteration++;
        if( isSelected( PHYS_WIDTH_PRM ) )
        {
            increment = w / 100.0;
            w += increment;
        }
        else
        {
            increment = s / 100.0;
            s += increment;
        }
        /* compute coplanar parameters */
        calc();
        Z0_result = Z0;
        /* f(w(n)) = Z0 - Z0(w(n)) */
        /* f'(w(n)) = -f'(Z0(w(n))) */
        /* f'(Z0(w(n))) = (Z0(w(n)) - Z0(w(n+delw))/delw */
        /* w(n+1) = w(n) - f(w(n))/f'(w(n)) */
        slope = (Z0_result - Z0_current) / increment;
        slope = (Z0_dest - Z0_current) / slope - increment;
        if( isSelected( PHYS_WIDTH_PRM ) )
            w += slope;
        else
            s += slope;
        if( w <= 0.0 )
            w = increment;
        if( s <= 0.0 )
            s = increment;
        /* find new error */
        /* compute coplanar parameters */
        calc();
        Z0_current = Z0;
        error = fabs( Z0_dest - Z0_current );
        if( iteration > 100 )
            break;
    }

    setProperty( PHYS_WIDTH_PRM, w );
    setProperty( PHYS_S_PRM, s );
    /* calculate physical length */
    ang_l = getProperty( ANG_L_PRM );
    len   = C0 / f / sqrt( er_eff ) * ang_l / 2.0 / M_PI; /* in m */
    setProperty( PHYS_LEN_PRM, len );

    /* compute coplanar parameters */
    calc();

    /* print results in the subwindow */
    show_results();
}
/*
 * synthesis function
 */
void MICROSTRIP::synthesize()
{
    double Z0_dest, Z0_current, Z0_result, increment, slope, error;
    int    iteration;

    /* Get and assign substrate parameters */
    get_microstrip_sub();

    /* Get and assign component parameters */
    get_microstrip_comp();

    /* Get and assign electrical parameters */
    get_microstrip_elec();

    /* Get and assign physical parameters */
    /* at present it is required only for getting strips length */
    get_microstrip_phys();


    /* calculate width and use for initial value in Newton's method */
    w = synth_width();

    /* required value of Z0 */
    Z0_dest = Z0;

    /* Newton's method */
    iteration = 0;

    /* compute microstrip parameters */
    calc();
    Z0_current = Z0;

    error = fabs( Z0_dest - Z0_current );

    while( error > MAX_ERROR )
    {
        iteration++;
        increment = (w / 100.0);
        w += increment;
        /* compute microstrip parameters */
        calc();
        Z0_result = Z0;
        /* f(w(n)) = Z0 - Z0(w(n)) */
        /* f'(w(n)) = -f'(Z0(w(n))) */
        /* f'(Z0(w(n))) = (Z0(w(n)) - Z0(w(n+delw))/delw */
        /* w(n+1) = w(n) - f(w(n))/f'(w(n)) */
        slope = (Z0_result - Z0_current) / increment;
        /* printf("%g\n",slope); */
        w += (Z0_dest - Z0_current) / slope - increment;
        /*      printf("ms->w = %g\n", ms->w); */
        /* find new error */
        /* compute microstrip parameters */
        calc();
        Z0_current = Z0;
        error = fabs( Z0_dest - Z0_current );

        /*      printf("Iteration = %d\n",iteration);
         *   printf("w = %g\t Z0 = %g\n",ms->w, Z0_current); */
        if( iteration > 100 )
            break;
    }

    setProperty( PHYS_WIDTH_PRM, w );
    /* calculate physical length */
    ang_l = getProperty( ANG_L_PRM );
    l     = C0 / f / sqrt( er_eff * mur_eff ) * ang_l / 2.0 / M_PI; /* in m */
    setProperty( PHYS_LEN_PRM, l );

    /* compute microstrip parameters */
    calc();

    /* print results in the subwindow */
    show_results();
}
Example #29
0
static int find_tle_via_simplex_method( tle_t *tle, const double *state_vect,
                     const double *start_vect, const int ephem)
{
   SIMPLEX_POINT simp[7];
   double best_rval_found = 1e+39, best_vect[6];
   int i, j, soln_found = 0, n_iterations = 0;
   int n_consecutive_contractions = 0;
   const int max_iterations = 43000;

   if( verbose)
      show_results( "Setting up:", NULL, start_vect);
   srand( 1);
   if( initialize_simplexes( simp, state_vect, start_vect, ephem))
      return( 0);       /* no solution found */
   while( !soln_found && n_iterations++ < max_iterations)
      {
      double ytry;

      sort_simplexes( simp);
      ytry = try_simplex( simp, -1., tle, state_vect, ephem);
      if( ytry <= simp[6].error)
         {
         if( verbose)
            {
            char buff[200];
            printf( "New record low: %f\n", ytry);

            write_elements_in_tle_format( buff, tle);
            printf( "%s", buff);
            }
         try_simplex( simp, 2., tle, state_vect, ephem);
         if( ytry < 1e-13)
            soln_found = true;
         if( ytry < best_rval_found)
            {
            best_rval_found = ytry;
            memcpy( best_vect, simp[0].state_vect, 6 * sizeof( double));
            }
         n_consecutive_contractions = 0;
         }
      else if( ytry > simp[1].error)
         {
         double ysave = simp[0].error;

         ytry = try_simplex( simp, .5, tle, state_vect, ephem);
         if( ytry > ysave)       /* still no success;  try contracting */
            {                    /* around lowest point: */
//          printf( "Contracting around best point\n");
            for( i = 0; i < 6; i++)
               {
               for( j = 0; j < 6; j++)
                  simp[i].state_vect[j] =
                           (simp[i].state_vect[j] + simp[6].state_vect[j]) / 2.;
               simp[i].error = compute_simplex_point_error( simp[i].state_vect, tle,
                                                               state_vect, ephem);
               }
            n_consecutive_contractions++;
            if( n_consecutive_contractions == 30)
               initialize_simplexes( simp, state_vect, best_vect, ephem);
            }
         else
            n_consecutive_contractions = 0;
         }
      if( n_iterations % 200 == 199)
         initialize_simplexes( simp, state_vect, best_vect, ephem);
      }
   sort_simplexes( simp);
   if( verbose)
      printf( "End err: %f\n", simp[6].error);
   vector_to_tle( tle, best_vect);
// vector_to_tle( tle, simp[6].state_vect);
   return( soln_found);
}
Example #30
0
/* Main program */
int main( const int argc, const char **argv)
{
   const char *tle_filename = ((argc == 1) ? "test.tle" : argv[1]);
   FILE *ifile = fopen( tle_filename, "rb");
   tle_t tle; /* Pointer to two-line elements set for satellite */
   char line1[100], line2[100];
   int ephem = 1;       /* default to SGP4 */
   int i;               /* Index for loops etc */
   int n_failures = 0, n_simple = 0, n_simplex = 0;
   bool failures_only = false;

   for( i = 2; i < argc; i++)
      if( argv[i][0] == '-')
         switch( argv[i][1])
            {
            case 'f':
               failures_only = true;
               break;
            case 'v':
               verbose = 1;
               break;
            case 'd':
               dist_offset = atof( argv[i] + 2);
               break;
            case 's':
               vel_offset = atof( argv[i] + 2);
               break;
            default:
               printf( "Option '%s' unrecognized\n", argv[i]);
               break;
            }
   if( !ifile)
      {
      printf( "Couldn't open input TLE file %s\n", tle_filename);
      exit( -1);
      }
   *line1 = '\0';
   while( fgets( line2, sizeof( line2), ifile))
      {
      int got_data = 0;
      double state_vect[6];

      set_tle_defaults( &tle);
      if( strlen( line2) > 110 && line2[7] == '.' && line2[18] == '.'
                     && line2[0] == '2' && line2[1] == '4')
         {
         got_data = 3;           /* Find_Orb state vector ephemeris */
         tle.epoch = atof( line2);
         sscanf( line2 + 13, "%lf %lf %lf %lf %lf %lf",
                    state_vect + 0, state_vect + 1, state_vect + 2,
                    state_vect + 3, state_vect + 4, state_vect + 5);
         }
      else if( strlen( line1) > 55 && !memcmp( line1 + 50, " (TDB)", 6))
         {                                  /* JPL Horizons vector */
         const double obliq_2000 = 23.4392911 * PI / 180.;

         tle.epoch = atof( line1);          /* get JD epoch from header... */
         strcpy( line1, line2);
         if( fgets( line2, sizeof( line2), ifile))
            got_data = 1;
         sscanf( line1, "%lf %lf %lf",
                    state_vect + 0, state_vect + 1, state_vect + 2);
         sscanf( line2, "%lf %lf %lf",
                    state_vect + 3, state_vect + 4, state_vect + 5);
                      /* Cvt ecliptic to equatorial 2000: */
         rotate_vector( state_vect    , obliq_2000, 0);
         rotate_vector( state_vect + 3, obliq_2000, 0);
         }
      else if( parse_elements( line1, line2, &tle) >= 0)
         got_data = 2;

      if( got_data == 1 || got_data == 3)
         tle.epoch -= 68.00 / 86400.;       /* rough convert TDT to UTC */

      if( got_data)     /* hey! we got a TLE! */
         {
         double sat_params[N_SAT_PARAMS],  trial_state[6];
         int simple_rval;
         bool failed = false;
         tle_t new_tle;

         if( got_data == 1 || got_data == 3)
            {
            ephem = 3;        /* Use SDP4 for JPL Horizons vectors */
            for( i = 0; i < 6 && fabs( state_vect[i]) < 1.; i++)
               ;
            if( i == 6)   /* all small quantities,  must be in AU & AU/day : */
               {
               for( i = 0; i < 6; i++)
                  state_vect[i] *= AU_IN_KM;
               for( i = 3; i < 6; i++)
                  state_vect[i] /= seconds_per_day;
               }
            for( i = 3; i < 6; i++)    /* cvt km/sec to km/min */
               state_vect[i] *= seconds_per_minute;
            if( !failures_only)
               show_results( "Before:", NULL, state_vect);
            }
         else
            {
            int is_deep = select_ephemeris( &tle);

            if( is_deep && (ephem == 1 || ephem == 2))
               ephem += 2;    /* switch to an SDx */
            if( !is_deep && (ephem == 3 || ephem == 4))
               ephem -= 2;    /* switch to an SGx */

            /* Calling of NORAD routines */
            /* Each NORAD routine (SGP, SGP4, SGP8, SDP4, SDP8)   */
            /* will be called in turn with the appropriate TLE set */
            switch( ephem)
               {
               case 0:
                  SGP_init( sat_params, &tle);
                  SGP( 0., &tle, sat_params, state_vect, state_vect + 3);
                  break;
               case 1:
                  SGP4_init( sat_params, &tle);
                  SGP4( 0., &tle, sat_params, state_vect, state_vect + 3);
                  break;
               case 2:
                  SGP8_init( sat_params, &tle);
                  SGP8( 0., &tle, sat_params, state_vect, state_vect + 3);
                  break;
               case 3:
                  SDP4_init( sat_params, &tle);
                  SDP4( 0., &tle, sat_params, state_vect, state_vect + 3);
                  break;
               case 4:
                  SDP8_init( sat_params, &tle);
                  SDP8( 0., &tle, sat_params, state_vect, state_vect + 3);
                  break;
               }
            if( !failures_only)
               show_results( "Before:", &tle, state_vect);
            }

         new_tle = tle;
         simple_rval = compute_tle_from_state_vector( &new_tle, state_vect, ephem, trial_state);
         if( simple_rval)
            {
            n_simplex++;
            find_tle_via_simplex_method( &new_tle, state_vect, trial_state, ephem);
            }
         else
            n_simple++;

         compute_new_state_vect( &new_tle, trial_state, ephem);
         for( i = 0; i < 6; i++)
            {
            trial_state[i] -= state_vect[i];
            if( fabs( trial_state[i]) > 1e-6)
               failed = true;
            }
         if( failed && failures_only)
            show_results( "Before:", &tle, state_vect);
         if( failed || !failures_only)
            show_results( (simple_rval ? "Simplex result:" : "Simplest method:"),
                                &new_tle, trial_state);
         if( failed)
            n_failures++;
         }
      strcpy( line1, line2);
      }
   fclose( ifile);
   printf( "%d solved with simple method; %d with simplex\n", n_simple, n_simplex);
   if( n_failures)
      printf( "%d failures\n", n_failures);
   return(0);
} /* End of main() */