コード例 #1
0
ファイル: main.c プロジェクト: alacrities/EddieBalance
/* Incoming UDP Command Packet handler:
 *
 * DRIVE[value]	=	+ is Forwards, - is Reverse, 0.0 is IDLE
 * TURN[value]	=	+ is Right, - is Left, 0.0 is STRAIGHT
 *
 * SETPIDS = Changes all PIDs for speed and pitch controllers
 * GETPIDS = Returns all PIDs for speed and pitch controllers via UDP
 *
 * PIDP[P,I,D][value] = adjust pitch PIDs
 * SPID[P,I,D][value] = adjust speed PIDs
 *
 * KALQA[value] = adjust Kalman Q Angle
 * KALQB[value] = adjust Kalman Q Bias
 * KALR[value] = adjust Kalman R Measure
 *
 * STOPUDP	= Will stop Eddie from sending UDP to current recipient
 *
 * STREAM[0,1] = Enable/Disable Live Data Stream
 *
 */
void UDP_Command_Handler( char * p_udpin )
{
	/* DRIVE commands */
	if( !memcmp( p_udpin, "DRIVE", 5 ) )
	{
		driveTrim = atof( &p_udpin[5] );
	}
	/* TURN commands */
	else if( !memcmp( p_udpin, "TURN", 4 ) )
	{
		turnTrim = atof( &p_udpin[4] );
	}
	/* Get/Set all PID quick commands*/
	else if ( strncmp( p_udpin, "SETPIDS:", 8 ) == 0 )
	{
		char * pch;
		
		pch = strtok ( &p_udpin[8], "," );
		pidP_P_GAIN=atof(pch);
		
		pch = strtok (NULL, ",");
		pidP_I_GAIN=atof(pch);
		
		pch = strtok (NULL, ",");
		pidP_D_GAIN=atof(pch);
		
		pch = strtok (NULL, ",");
		pidS_P_GAIN=atof(pch);
		
		pch = strtok (NULL, ",");
		pidS_I_GAIN=atof(pch);
		
		pch = strtok (NULL, ",");
		pidS_D_GAIN=atof(pch);		
	}
	else if ( strncmp( p_udpin, "GETPIDS", 7 ) == 0 )
	{
		print( "CURRENTPIDS:%0.3f,%0.3f,%0.3f,%0.3f,%0.3f,%0.3f\r\n", pidP_P_GAIN, pidP_I_GAIN, pidP_D_GAIN, pidS_P_GAIN, pidS_I_GAIN, pidS_D_GAIN );
	}
	/* Individual Pitch PID Controller commands */
	else if ( strncmp( p_udpin, "PPIDP", 5 ) == 0 )
	{
		float newGain = 0;
		newGain = atof( &p_udpin[5] );
		print( "New Pitch PID P Gain Received: Changing %0.3f to %0.3f\r\n", pidP_P_GAIN, newGain );
		pidP_P_GAIN = newGain;
	}
	else if ( strncmp( p_udpin, "PPIDI", 5 ) == 0 )
	{
		float newGain = 0;
		newGain = atof( &p_udpin[5] );
		print( "New Pitch PID I Gain Received: Changing %0.3f to %0.3f\r\n", pidP_I_GAIN, newGain );
		pidP_I_GAIN = newGain;
	}
	else if ( strncmp( p_udpin, "PPIDD", 5 ) == 0 )
	{
		float newGain = 0;
		newGain = atof( &p_udpin[5] );
		print( "New Pitch PID D Gain Received: Changing %0.3f to %0.3f\r\n", pidP_D_GAIN, newGain );
		pidP_D_GAIN = newGain;
	}
	/* Individual Speed PID Controller commands*/
	else if ( strncmp( p_udpin, "SPIDP", 5 ) == 0 )
	{
		float newGain = 0;
		newGain = atof( &p_udpin[5] );
		print( "New Speed PID P Gain Received: Changing %0.3f to %0.3f\r\n", pidS_P_GAIN, newGain );
		pidS_P_GAIN = newGain;
	}
	else if ( strncmp( p_udpin, "SPIDI", 5 ) == 0 )
	{
		float newGain = 0;
		newGain = atof( &p_udpin[5] );
		print( "New Speed PID I Gain Received: Changing %0.3f to %0.3f\r\n", pidS_I_GAIN, newGain );
		pidS_I_GAIN = newGain;
	}
	else if ( strncmp( p_udpin, "SPIDD", 5 ) == 0 )
	{
		float newGain = 0;
		newGain = atof( &p_udpin[5] );
		print( "New Speed PID D Gain Received: Changing %0.3f to %0.3f\r\n", pidS_D_GAIN, newGain );
		pidS_D_GAIN = newGain;
	}
	/* Pitch Kalman filter tuning commands */
	else if ( strncmp( p_udpin, "KALQA", 4 ) == 0 )
	{
		float newGain = 0;
		newGain = atof( &p_udpin[4] );
		print( "Setting Kalman Q Angle to: %0.4f\r\n", newGain );
		setQkalmanangle( newGain );
	}
	else if ( strncmp( p_udpin, "KALQB", 4 ) == 0 )
	{
		float newGain = 0;
		newGain = atof( &p_udpin[4] );
		print( "Setting Kalman Q Bias to: %0.4f\r\n", newGain );
		setQbias( newGain );
	}
	else if ( strncmp( p_udpin, "KALR", 4 ) == 0 )
	{
		float newGain = 0;
		newGain = atof( &p_udpin[4] );
		print( "Setting Kalman R Measure to: %0.4f\r\n", newGain );
		setRmeasure( newGain );
	}
	/* UDP Hangup command */
	else if ( strncmp( p_udpin, "STOPUDP", 7 ) == 0 )
	{
		UDPCloseTX();
	}
	/* Enable/Disable live data stream */
	else if ( strncmp( p_udpin, "STREAM1", 7 ) == 0 )
	{
		StreamData = 1;
	}
	else if ( strncmp( p_udpin, "STREAM0", 7 ) == 0 )
	{
		StreamData = 0;
	}
}
コード例 #2
0
ファイル: RCCE_admin.c プロジェクト: BillTheBest/RCCE
//--------------------------------------------------------------------------------------
// FUNCTION: RCCE_init
//--------------------------------------------------------------------------------------
// initialize the library and sanitize parameter list
//--------------------------------------------------------------------------------------
int RCCE_init(
  int *argc,   // pointer to argc, passed in from main program
  char ***argv // pointer to argv, passed in from main program
  ) {

  int i, ue, dummy_offset, loc, error;
#ifdef SCC
  int x, y, z;
  unsigned int physical_lockaddress;
#endif

#ifdef SHMADD
  unsigned int RCCE_SHM_BUFFER_offset ,result, rd_slot_nbr, wr_slot_nbr;
#endif
  void *nothing = NULL;
  
#ifdef SCC
  // Copperridge specific initialization...
  InitAPI(0);fflush(0);
#endif  

  // save pointer to executable name for later insertion into the argument list
  char *executable_name = (*argv)[0];

  RCCE_NP        = atoi(*(++(*argv)));  
  RC_REFCLOCKGHZ = atof(*(++(*argv)));  

  // put the participating core ids (unsorted) into an array             
  for (ue=0; ue<RCCE_NP; ue++) {
    RC_COREID[ue] = atoi(*(++(*argv)));
  }

#ifndef SCC
  // if using the functional emulator, must make sure to have read all command line 
  // parameters up to now before overwriting (shifted) first one with executable
  // name; even though argv is made firstprivate, that applies only the pointer to 
  // the arguments, not the actual data
  #pragma omp barrier
#endif
  // make sure executable name is as expected                 
  (*argv)[0] = executable_name;

  RC_MY_COREID = MYCOREID();

  // adjust apparent number of command line arguments, so it will appear to main 
  // program that number of UEs, clock frequency, and core ID list were not on
  // command line        
  *argc -= RCCE_NP+2;

  // sort array of participating phyical core IDs to determine their ranks
  RCCE_qsort((char *)RC_COREID, RCCE_NP, sizeof(int), id_compare);

  // determine rank of calling core
  for (ue=0; ue<RCCE_NP; ue++) {
    if (RC_COREID[ue] == RC_MY_COREID) RCCE_IAM = ue;
  }

#ifdef SHMADD
//   printf("Using SHMADD\n");
     RCCE_SHM_BUFFER_offset     = 0x00;
//   RCCE_SHM_BUFFER_offset     = 0x3FFFF80;
//   RCCE_SHM_BUFFER_offset   = 0x4000000;
//   RCCE_SHM_BUFFER_offset   = 0x181000;
   rd_slot_nbr=0x80;
   for(i=0; i<60; i++) {
     result  = readLUT(rd_slot_nbr);
     result -= 1;
     wr_slot_nbr = rd_slot_nbr + 4;
     writeLUT(wr_slot_nbr,result);
     rd_slot_nbr++;
   }
#endif

  // leave in one reassuring debug print
  if (DEBUG){
    printf("My rank is %d, physical core ID is %d\n", RCCE_IAM, RC_MY_COREID);
    fflush(0);
  }

  if (RCCE_IAM<0)
    return(RCCE_error_return(RCCE_debug_comm,RCCE_ERROR_CORE_NOT_IN_HOSTFILE));

#ifdef SCC
  // compute and memory map addresses of test&set registers for all participating cores 
  for (ue=0; ue<RCCE_NP; ue++) { 
    z = Z_PID(RC_COREID[ue]);
    x = X_PID(RC_COREID[ue]);
    y = Y_PID(RC_COREID[ue]);
    physical_lockaddress = CRB_ADDR(x,y) + (z==0 ? LOCK0 : LOCK1);
    virtual_lockaddress[ue] = (t_vcharp) MallocConfigReg(physical_lockaddress);
  }
#endif

  // initialize MPB starting addresses for all participating cores; allow one
  // dummy cache line at front of MPB for fooling write combine buffer in case
  // of single-byte MPB access
  RCCE_fool_write_combine_buffer = RC_COMM_BUFFER_START(RCCE_IAM);

  for (ue=0; ue<RCCE_NP; ue++) 
    RCCE_comm_buffer[ue] = RC_COMM_BUFFER_START(ue) + RCCE_LINE_SIZE;

  // gross MPB size is set equal to maximum
  RCCE_BUFF_SIZE = RCCE_BUFF_SIZE_MAX - RCCE_LINE_SIZE;

#ifdef RC_POWER_MANAGEMENT
#ifndef SCC
  // always store RPC queue data structure at beginning of usable MPB, so allocatable
  // storage needs to skip it. Only need to do this for functional emulator
  for (ue=0; ue<RCCE_NP; ue++) 
    RCCE_comm_buffer[ue] += REGULATOR_LENGTH;
  RCCE_BUFF_SIZE -= REGULATOR_LENGTH;
#endif
#endif

  // initialize RCCE_malloc
  RCCE_malloc_init(RCCE_comm_buffer[RCCE_IAM],RCCE_BUFF_SIZE);
#ifdef SHMADD

  RCCE_shmalloc_init(RC_SHM_BUFFER_START()+RCCE_SHM_BUFFER_offset ,RCCE_SHM_SIZE_MAX);
#ifdef SHMDBG
  printf("\n%d:%s:%d: RCCE_SHM_BUFFER_offset, RCCE_SHM_SIZE_MAX: % x %x\n", RCCE_IAM, 
    __FILE__,__LINE__,RCCE_SHM_BUFFER_offset ,RCCE_SHM_SIZE_MAX);
#endif
#else
  RCCE_shmalloc_init(RC_SHM_BUFFER_START(),RCCE_SHM_SIZE_MAX);
#endif

  // initialize the (global) flag bookkeeping data structure
  for (loc=0; loc<RCCE_FLAGS_PER_LINE; loc++) 
    RCCE_flags.flag[loc] = (char)((unsigned int)0);
  RCCE_flags.line_address = NULL;
  RCCE_flags.members=0;
  RCCE_flags.next=NULL;

  // create global communicator (equivalent of MPI_COMM_WORLD); this will also allocate 
  // the two synchronization flags associated with the global barrier 
  RCCE_comm_split(RCCE_global_color, nothing, &RCCE_COMM_WORLD);

  // if power management is enabled, initialize more stuff; this includes two more 
  // communicators (for voltage and frequency domains), plus two synchronization flags
  // associated with the barrier for each communicator       
#ifdef RC_POWER_MANAGEMENT
  if (error=RCCE_init_RPC(RC_COREID, RCCE_IAM, RCCE_NP)) 
       return(RCCE_error_return(RCCE_debug_RPC,error));
#endif

#ifndef GORY
  // if we use the simplified API, we need to define more flags upfront  
  for (ue=0; ue<RCCE_NP; ue++) {
    if (error=RCCE_flag_alloc(&RCCE_sent_flag[ue]))
      return(RCCE_error_return(RCCE_debug_synch,error));
    if (error=RCCE_flag_alloc(&RCCE_ready_flag[ue]))
      return(RCCE_error_return(RCCE_debug_synch,error));
  }

#endif

  return (RCCE_SUCCESS);
}
コード例 #3
0
ファイル: udpfeed.c プロジェクト: LeeVidor/kannel-mongodb
int main(int argc, char **argv) {
	int opt;
	Octstr *address;
	int udpsock;

	gwlib_init();

	/* Set defaults that can't be set statically */
	hostname = octstr_create("localhost");

	while ((opt = getopt(argc, argv, "hg:p:i:m:")) != EOF) {
		switch(opt) {
		case 'g':
			octstr_destroy(hostname);
			hostname = octstr_create(optarg);
			break;

		case 'p':
			port = atoi(optarg);
			break;

		case 'i':
			interval = atof(optarg);
			break;

		case 'm':
			maxsize = atol(optarg);
			if (maxsize > UDP_MAXIMUM) {
				maxsize = UDP_MAXIMUM;
				warning(0, "-m: truncated to UDP maximum of"
					"%ld bytes.", maxsize);
			}
			break;

		case 'h':
			help();
			exit(0);
			break;

		case '?':
		default:
			error(0, "Unknown option '%c'", opt);
			help();
			exit(1);
			break;
		}
	}

	address = udp_create_address(hostname, port);
	udpsock = udp_client_socket();
	if (udpsock < 0)
		exit(1);

	for ( ; optind < argc; optind++) {
		send_file(udpsock, argv[optind], address);
		if (interval > 0 && optind + 1 < argc)
			gwthread_sleep(interval);
	}

	octstr_destroy(address);
	octstr_destroy(hostname);
	gwlib_shutdown();
    	return 0;
}
コード例 #4
0
ファイル: lsystem.cpp プロジェクト: abred/TreeHugger
string
Lsystem::parse_lsystem(char const* filename, int iteration) {
    //Falls Datei noch nicht geparsed


    if(lsystem_.empty() == true){
        //Datei einlesen
        file_iterator<> first = load(filename);
        file_iterator<> last = first.make_end();

        typedef char char_t;
        typedef file_iterator <char_t> iterator_t;

        string input(first, last);
//        std::cout << "Eingabe:" << "\n" << input << "\n" << std::endl;

        lsystem_grammer lsys;

        //Parsevorgang
        parse_info<iterator_t> pi = parse(first, last, lsys, space_p);
        if (pi.hit) {
            if (pi.full) {
                std::cout << "LSystem: file reading successfully" << std::endl;
                std::cout << "LSystem: " << pi.length << "characters read" << std::endl;
				std::cout << "LSystem: parsing ..." << std::endl;
//                std::cout << "Vektor:" << gl_lsys_file.size() << "\n" << std::endl;

                //Eingabe splitten
                typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
                //Axiom
                //string s1 = get_axiom();
                //boost::char_separator<char> sep1(": ");
                //tokenizer tok(s1, sep1);
                //tokenizer::iterator it = tok.begin();
                //string start = *(++it);
                boost::char_separator<char> sep1(": ");
				string start = get_axiom();
				std::string  ret;

                //Produkion(en)
                vector<string> s2 = get_production();
               // 
                    int last_pos = 0;
                    int left = 1;

                    //Zufallszahlen bis 100
                   // srand(j * time(0));
                    //int prob = rand() % 100 + 1;
                //  std::cout << "ZZ:" << prob << std::endl;
				//  std::cout<<s2.size()<<std::endl;

				std::map<int, string> mapProbToProd;
				
				int zaehler=0;

				for (int i = 0; i < s2.size(); i++) 
				{

					int position;

                    tokenizer tok2(s2[i], sep1);
                    tokenizer::iterator it = tok2.begin();
                    string temp = *(++it);                                                              //Alles nach dem Doppelpunkt

                        boost::char_separator<char> sep2("=");
                        tokenizer tok3(temp, sep2);
                        tokenizer::iterator it2 = tok3.begin();
                        string temp1 = *(it2);                                                              //Alles vor dem Gleichheitszeichen
                        string temp2 = *(++it2);                                                            //Alles nach dem Gleichheitszeichen

                        if (temp2.find(",") == string::npos) 
						{                                              //DOL
                            stochastic_ = false;
                            //Ersetzung
                            boost::replace_all(start, temp1, temp2);
							lsystem_.push_back(start);
							lsystem_.push_back(start);                                                      //DOL mit meherere Produktionen existieren
                        } 
						else if (temp2.find(",") != string::npos) 
						{                                       //stochastische L-Systeme
                            stochastic_ = true;
                            boost::char_separator<char> sep3(",");
                            tokenizer tok4(temp2, sep3);
                            tokenizer::iterator it3 = tok4.begin();
                            string sto = *(it3);                                                            //Alles vor Komma (Wahrscheinlichkeit)
                            string temp3 = *(++it3);                                                        //Alles nach Komma (Regel)

                            int cur_pos = atof(sto.data()) * 100;                                           //aktuelle Wahrscheinlichkeit
                            int right = last_pos + cur_pos; //Bereich rechts
                       
							for(int k = 0; k < cur_pos ; ++k )
							{
								mapProbToProd.insert ( std::pair<int, string>(zaehler,temp3));
								++zaehler;
							}

//                       
                        }
                    }
				for (int j = 1; j <= iteration * 2; j++) 
				{

					std::string result;
				//	result.reserve(14*start.size());

					for(int i = 0 ; i < start.size() ; ++i)
					{
						srand(i*time(0));
						int k = rand() % 100;
						if(start[i]=='F')
							result += mapProbToProd[k];
						else
							result += start[i];
					}

					lsystem_.push_back(result);
					start=result;

				}
				std::cout << "LSystem: parsing finished\n\n";
                //}
                if (stochastic_ == false) {
//                    std::cout << "Ergebnis: " << lsystem_[(s2.size()) * iteration - 1] << std::endl;
                    return lsystem_[(s2.size() * iteration - 1)];
                } else if (stochastic_ == true) {
//                    std::cout << "Ergebnis: " << lsystem_[iteration - 1] << std::endl;
                    return lsystem_[iteration - 1];
                }

            } else {
                std::cout << "LSystem: ERROR parsing data partially" << std::endl;
                std::cout << "LSystem: ERROR " << pi.length << "characters parsed \n\n" << std::endl;
            }
        } else
            std::cout << "LSystem: ERROR parsing failed; stopped at '" << pi.stop << "'\n\n" << std::endl;
    }
    //erneutes Parsen verhindern
    else if(iteration <= lsystem_.size()) 
	{
        if (stochastic_ == false) 
		{
//            std::cout << "Ergebnis: " << lsystem_[(get_production().size()) * iteration - 1] << std::endl;
            return lsystem_[(get_production().size() * iteration - 1)];
        } 
		else if (stochastic_ == true) 
{
//            std::cout << "Ergebnis: " << lsystem_[iteration - 1] << std::endl;
            return lsystem_[iteration - 1];
        }
    }
    //Vektor vergrößern
    else if(iteration > lsystem_.size()){
        erase_old();
        parse_lsystem(filename, iteration);
        if (stochastic_ == false) {
            //            std::cout << "Ergebnis: " << lsystem_[(get_production().size()) * iteration - 1] << std::endl;
            return lsystem_[(get_production().size() * iteration - 1)];
        } else if (stochastic_ == true) {
            //            std::cout << "Ergebnis: " << lsystem_[iteration - 1] << std::endl;
            return lsystem_[iteration - 1];
        }
    }
	return std::string();
}
コード例 #5
0
ファイル: g_items.c プロジェクト: 0culus/ioq3
int Pickup_PersistantPowerup( gentity_t *ent, gentity_t *other ) {
	int		clientNum;
	char	userinfo[MAX_INFO_STRING];
	float	handicap;
	int		max;

	other->client->ps.stats[STAT_PERSISTANT_POWERUP] = ent->item - bg_itemlist;
	other->client->persistantPowerup = ent;

	switch( ent->item->giTag ) {
	case PW_GUARD:
		clientNum = other->client->ps.clientNum;
		trap_GetUserinfo( clientNum, userinfo, sizeof(userinfo) );
		handicap = atof( Info_ValueForKey( userinfo, "handicap" ) );
		if( handicap<=0.0f || handicap>100.0f) {
			handicap = 100.0f;
		}
		max = (int)(2 *  handicap);

		other->health = max;
		other->client->ps.stats[STAT_HEALTH] = max;
		other->client->ps.stats[STAT_MAX_HEALTH] = max;
		other->client->ps.stats[STAT_ARMOR] = max;
		other->client->pers.maxHealth = max;

		break;

	case PW_SCOUT:
		clientNum = other->client->ps.clientNum;
		trap_GetUserinfo( clientNum, userinfo, sizeof(userinfo) );
		handicap = atof( Info_ValueForKey( userinfo, "handicap" ) );
		if( handicap<=0.0f || handicap>100.0f) {
			handicap = 100.0f;
		}
		other->client->pers.maxHealth = handicap;
		other->client->ps.stats[STAT_ARMOR] = 0;
		break;

	case PW_DOUBLER:
		clientNum = other->client->ps.clientNum;
		trap_GetUserinfo( clientNum, userinfo, sizeof(userinfo) );
		handicap = atof( Info_ValueForKey( userinfo, "handicap" ) );
		if( handicap<=0.0f || handicap>100.0f) {
			handicap = 100.0f;
		}
		other->client->pers.maxHealth = handicap;
		break;
	case PW_AMMOREGEN:
		clientNum = other->client->ps.clientNum;
		trap_GetUserinfo( clientNum, userinfo, sizeof(userinfo) );
		handicap = atof( Info_ValueForKey( userinfo, "handicap" ) );
		if( handicap<=0.0f || handicap>100.0f) {
			handicap = 100.0f;
		}
		other->client->pers.maxHealth = handicap;
		memset(other->client->ammoTimes, 0, sizeof(other->client->ammoTimes));
		break;
	default:
		clientNum = other->client->ps.clientNum;
		trap_GetUserinfo( clientNum, userinfo, sizeof(userinfo) );
		handicap = atof( Info_ValueForKey( userinfo, "handicap" ) );
		if( handicap<=0.0f || handicap>100.0f) {
			handicap = 100.0f;
		}
		other->client->pers.maxHealth = handicap;
		break;
	}

	return -1;
}
コード例 #6
0
int
main(int argc,
     char *argv[]) {

  typedef enum {ERROR, HALT, LOG, REGISTER, TEST} Commands;
  const char *COMMANDS[] = {"error", "halt", "log", "register", "test"};
  const char *USAGE = "ctrl_host [-P password] [-t n] [-z] <command> host ...";

  int c;
  Commands command;
  struct host_cookie cookie;
  struct host_desc host;
  HostInfo info;
  struct host_desc nsDesc;
  unsigned short nsPort;
  const char *parameter = NULL;
  const char *password;
  const char *STATII[] = {"dead", "healthy", "sick", "unresponsive"};
  unsigned short sensorPort;
  HostStatii status;
  const char *TYPES[] = {"forecaster", "memory", "name_server", "sensor"};
  double timeOut;
  extern char *optarg;
  extern int optind;

  password = NULL;
  timeOut = PKTTIMEOUT;

  DirectDiagnostics(DIAGINFO, stdout);
  DirectDiagnostics(DIAGLOG, stdout);
  DirectDiagnostics(DIAGWARN, stderr);
  DirectDiagnostics(DIAGERROR, stderr);
  DirectDiagnostics(DIAGFATAL, stderr);

  nsPort = DefaultHostPort(NAME_SERVER_HOST);
  sensorPort = DefaultHostPort(SENSOR_HOST);

  while((c = getopt(argc, argv, SWITCHES)) != EOF) {

    switch(c) {

    case 'P':
      password = optarg;
      break;

    case 't':
      timeOut = atof(optarg);
      break;

    case 'z':
      DirectDiagnostics(DIAGINFO, DIAGSUPPRESS);
      DirectDiagnostics(DIAGLOG, DIAGSUPPRESS);
      DirectDiagnostics(DIAGWARN, DIAGSUPPRESS);
      DirectDiagnostics(DIAGERROR, DIAGSUPPRESS);
      DirectDiagnostics(DIAGFATAL, DIAGSUPPRESS);
      break;

    default:
      fprintf(stderr, "unrecognized switch\n%s\n", USAGE);
      exit(1);
      break;

    }

  }

  if(optind >= argc) {
    fprintf(stderr, "%s\n", USAGE);
    exit(1);
  }

  for(command = ERROR; command <= TEST; command++) {
    if(strncasecmp(COMMANDS[command], argv[optind], strlen(argv[optind])) == 0)
      break;
  }

  if(command > TEST) {
    fprintf(stderr, "unknown command %s\n", argv[optind]);
    exit(1);
  }

  optind++;

  switch(command) {

  case REGISTER:
    if(optind >= argc) {
      fprintf(stderr, "missing parameter for %c command\n", command);
      exit(1);
    }
    parameter = argv[optind++];
    HostDValue(parameter, nsPort, &nsDesc);
    if(!IsANameServer(&nsDesc, timeOut)) {
      fprintf(stderr, "%s is not a name server\n", parameter);
    }
    break;

  default:
    break;

  }

  for(; optind < argc; optind++) {

    HostDValue(argv[optind], sensorPort, &host);
    MakeHostCookie(host.host_name, host.port, &cookie);

    if(!ConnectToHost(&cookie, &cookie.sd)) {
      if(command == TEST) {
        printf("%s dead\n", HostDImage(&host));
      }
      else {
        WARN1("connect %s failed\n", HostDImage(&host));
      }
      continue;
    }

    switch(command) {

    case ERROR:
      if(!DoDiagnosticsCommand(cookie.sd, ALL_ERRORS, timeOut)) {
        WARN1("error toggle failed for host %s\n", HostDImage(&host));
      }
      break;

    case HALT:
      if(!DoHaltHost(cookie.sd, password, timeOut)) {
        WARN1("halt failed for host %s\n", HostDImage(&host));
      }
      break;

    case LOG:
      if(!DoDiagnosticsCommand(cookie.sd, ALL_LOGS, timeOut)) {
        WARN1("log toggle failed for host %s\n", HostDImage(&host));
      }
      break;

    case REGISTER:
      if(!DoRegisterHost(cookie.sd, parameter, password, timeOut)) {
        WARN1("registration change failed for host %s\n", HostDImage(&host));
      }
      break;

    case TEST:
      status = DoTestHost(cookie.sd, &info, timeOut);
      if((status == HEALTHY) || (status == SICK)) {
        printf("%s %s ", TYPES[info.hostType], HostDImage(&host));
        if((strcmp(info.registrationName, HostDImage(&host)) != 0) &&
           (strcmp(info.registrationName, "") != 0)) {
          printf("(%s) ", info.registrationName);
        }
        printf("registered with %s ", info.nameServer);
      }
      else {
        printf("%s ", HostDImage(&host));
      }
      printf("%s\n", STATII[status]);
      break;

    }

    DisconnectHost(&cookie);

  }

  return(0);

}
コード例 #7
0
bool8 ObjReader::LoadObj(char8 *aFilename)
{
   FILE *ifp;
   char8 ch1, ch2, charBuffer[4096], valStr[20][4096];
   uint32 numRead;
   uint32 rawPositionIdx = 0;
   uint32 rawNormalIdx = 0;
   uint32 rawTexCoordIdx = 0;
   uint32 i;

   //first pass to count number of elements in each array
   errno_t result = fopen_s( &ifp, aFilename, "r" );

   if( result != 0 )
   {
       return false;
   }

   while (!feof(ifp))
   {
      fgets(charBuffer, 4096, ifp);
      numRead = sscanf_s(charBuffer, "%c%c%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n", &ch1, &ch2, 
         &valStr[0][0], &valStr[1][0], &valStr[2][0], &valStr[3][0], &valStr[4][0],
         &valStr[5][0], &valStr[6][0], &valStr[7][0], &valStr[8][0], &valStr[9][0],
         &valStr[10][0], &valStr[11][0], &valStr[12][0], &valStr[13][0], &valStr[14][0],
         &valStr[15][0], &valStr[16][0], &valStr[17][0], &valStr[18][0], &valStr[19][0]         
         );

      switch(ch1)
      {
         case 'g':
         break;
         case 'v':
            if(ch2 == ' ')
            {
               mNumRawPosition++;
            }
            else if(ch2 == 'n')
            {
               mNumRawNormal++;
            }
            else if(ch2 == 't')
            {
               mNumRawTexCoord++;
            }
         break;
         case 'f':
            mNumRawIndex += (numRead - 4) * 3;
         break;      
      }
   }

   //second pass to load in raw data
   fseek(ifp, 0, SEEK_SET);

   rawPositionIdx = 0;
   rawNormalIdx = 0;
   rawTexCoordIdx = 0;

   mRawPosition  = new float32 [mNumRawPosition * 3];
   mRawNormal  = new float32 [mNumRawNormal * 3];
   mRawTexCoord  = new float32 [mNumRawTexCoord * 2];
   mIndex  = new uint32 [mNumRawIndex];

   //for now allocate max size, and end of index condensing, reallocate arrays to optimal size
   mPosition = new float32 [mNumRawIndex * 3];
   mNormal = new float32 [mNumRawIndex * 3];
   mTexCoord = new float32 [mNumRawIndex * 2];
   
   mRawIndexTranslation = new uint32 [mNumRawIndex * 3];

   while (!feof(ifp))
   {
      fgets(charBuffer, 4096, ifp);
      //numRead = sscanf(charBuffer, "%c%c%s%s%s%s\n", &ch1, &ch2, &valStr[0][0], &valStr[1][0], &valStr[2][0], &valStr[3][0]);
      numRead = sscanf_s(charBuffer, "%c%c%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n", &ch1, &ch2, 
         &valStr[0][0], &valStr[1][0], &valStr[2][0], &valStr[3][0], &valStr[4][0],
         &valStr[5][0], &valStr[6][0], &valStr[7][0], &valStr[8][0], &valStr[9][0],
         &valStr[10][0], &valStr[11][0], &valStr[12][0], &valStr[13][0], &valStr[14][0],
         &valStr[15][0], &valStr[16][0], &valStr[17][0], &valStr[18][0], &valStr[19][0]         
         );

      
      switch(ch1)
      {
         case 'g':
         break;
         case 'v':
            if(ch2 == ' ')
            {
               mRawPosition [rawPositionIdx * 3 + 0] = (float32) atof(&valStr[0][0]);
               mRawPosition [rawPositionIdx * 3 + 1] = (float32) atof(&valStr[1][0]);
               mRawPosition [rawPositionIdx * 3 + 2] = (float32) atof(&valStr[2][0]);
               rawPositionIdx ++;
            }
            else if(ch2 == 'n')
            {
               mRawNormal [rawNormalIdx * 3 + 0] = (float32) atof(&valStr[0][0]);
               mRawNormal [rawNormalIdx * 3 + 1] = (float32) atof(&valStr[1][0]);
               mRawNormal [rawNormalIdx * 3 + 2] = (float32) atof(&valStr[2][0]);
               rawNormalIdx ++;
            }
            else if(ch2 == 't')
            {
               mRawTexCoord [rawTexCoordIdx * 2 + 0] = (float32) atof(&valStr[0][0]);
               mRawTexCoord [rawTexCoordIdx * 2 + 1] = (float32) atof(&valStr[1][0]);
               rawTexCoordIdx ++;
            }
         break;
         case 'f':
            //pack raw indices into array
            uint32 rawIndices[OR_MAX_FACE_VERTS][3];

            if(numRead < 5)
            {
            //error: face has less than 3 sides
            break;
            }

            for(i = 0; i < (numRead - 2); i++)
            {
               sscanf_s(&valStr[i][0], "%d/%d/%d", &rawIndices[i][0], &rawIndices[i][1], &rawIndices[i][2] ); 
               
               //convert indices to zero base instead of 1 base
               rawIndices[i][0]--;
               rawIndices[i][1]--;
               rawIndices[i][2]--;
            }

            for(i = 0; i < (numRead - 4); i++) //convert face polygon into a triangle fan e.g. (0,1,2) (0,2,3) (0,3,4) etc..
            {  //note that the first index looks funny (0, i+1, i+2) but is correct..
               mIndex [mNumIndex + 0] = LookupCreateIndex(rawIndices[0][0], rawIndices[0][1], rawIndices[0][2]);
               mIndex [mNumIndex + 1] = LookupCreateIndex(rawIndices[1+i][0], rawIndices[1+i][1], rawIndices[1+i][2]);
               mIndex [mNumIndex + 2] = LookupCreateIndex(rawIndices[2+i][0], rawIndices[2+i][1], rawIndices[2+i][2]);              
               mNumIndex += 3;
            }
         break;      
      }
   }

   //delete unnecessary raw data arrays
   delete [] mRawIndexTranslation;
   delete [] mRawPosition;
   delete [] mRawNormal;
   delete [] mRawTexCoord;

   CalculateTangentSpace();

   return TRUE;
}
コード例 #8
0
ファイル: FastTraxWindow.cpp プロジェクト: HaikuArchives/TraX
void FastTraxWindow :: MessageReceived( BMessage * msg )
{
	switch( msg->what )
	{
		case B_ABOUT_REQUESTED:
		{
			BMessenger msgr( be_app ) ;
			if( msgr.IsValid() )
				msgr.SendMessage( msg ) ;
			break ;
		}
		case ( Messages::SetTab | 'N' ) :
		{
			fCurrentView->Hide() ;
			fCurrentView = fNameView ;
			fCurrentView->Show() ;

			fDisabledButton->SetEnabled( true ) ;
			fDisabledButton = fNameButton ;
			fDisabledButton->SetEnabled( false ) ;
			break ;
		}
		case ( Messages::SetTab | 'F' ) :
		{
			fCurrentView->Hide() ;
			fCurrentView = fFileView ;
			fCurrentView->Show() ;

			fDisabledButton->SetEnabled( true ) ;
			fDisabledButton = fFileButton ;
			fDisabledButton->SetEnabled( false ) ;
			break ;
		}
		case ( Messages::SetTab | 'D' ) :
		{
			fCurrentView->Hide() ;
			fCurrentView = fDateView ;
			fCurrentView->Show() ;

			fDisabledButton->SetEnabled( true ) ;
			fDisabledButton = fDateButton ;
			fDisabledButton->SetEnabled( false ) ;
			break ;
		}
		case Messages::LibInUse:
		{
			fFindButton->SetEnabled( false ) ;
			break ;
		}
		case Messages::LibNotInUse:
		{
			fFindButton->SetEnabled( true ) ;
			delete[] fNameStr ;
			delete[] fContainsStr ;

			fNameStr = NULL ;
			fContainsStr = NULL ;
			break ;
		}
		case Messages::StartFind :
		{
			if( !FindLibThread::InitFind( "FastTraX" ) )
			{
				beep() ;
				break ;
			}
			
			findlib_start_predicates() ;
			const char * str ;

			time_t now = time( NULL ) ;
			
			str = fpCreAfter->Text() ;
			if( str[0] )
			{
				time_t t ;
				signed char ok = GetTime( str, now, &t ) ;
				if( ok < 0 )
					break ;
				if( ok > 0 )
					findlib_insert_crtime( COMP_GT, t ) ;
			}
			str = fpCreBefore->Text() ;
			if( str[0] )
			{
				time_t t ;
				signed char ok = GetTime( str, now, &t ) ;
				if( ok < 0 )
					break ;
				if( ok > 0 )
				{
					findlib_insert_crtime( COMP_LT, t ) ;
				}
			}

			str = fpModAfter->Text() ;
			if( str[0] )
			{
				time_t t ;
				signed char ok = GetTime( str, now, &t ) ;
				if( ok < 0 )
					break ;
				if( ok > 0 )
				{
					findlib_insert_mtime( COMP_GT, t ) ;
				}
			}

			str = fpModBefore->Text() ;
			if( str[0] )
			{
				time_t t ;
				signed char ok = GetTime( str, now, &t ) ;
				if( ok < 0 )
					break ;
				if( ok > 0 )
				{
					findlib_insert_mtime( COMP_LT, t ) ;
				}
			}


			fNameStr = strdup( fpName->Text() ) ;
			if( fNameStr[0] )
				findlib_insert_iname( fNameStr ) ;
			
			if( fpSubDirs->Value() == 0 )
				findlib_insert_maxdepth( 1Ul ) ;
	
			fContainsStr = strdup( fpContaining->Text() ) ;
			if( fContainsStr[0] )
			{
				findlib_insert_open_paren() ;
				findlib_insert_type( S_IFREG ) ;
				findlib_insert_and() ;
				findlib_insert_contains_istr( fContainsStr ) ;
				findlib_insert_close_paren() ;
			}

			str = fpSizeLT->Text() ;
			if( str[0] )
			{
				float f = atof(str) ;
				findlib_insert_fsize( COMP_LT, f, 1024 ) ;
			}

			str = fpSizeGT->Text() ;
			if( str[0] )
			{
				float f = atof(str) ;
				findlib_insert_fsize( COMP_GT, f, 1024 ) ;
			}
			
			int32 i = fpKind->GetIndex() ;
			if( i )
				findlib_insert_type( kKindType[i] ) ;

			findlib_end_predicates() ;
			FindLibThread * thread = new FindLibThread ;
			
			entry_ref ref ;
			fpFolder->GetRef( &ref ) ;
			BEntry ent( &ref ) ;
			thread->Path.SetTo( &ent ) ;
			thread->StartThread() ;

			break ;
		}
		case Messages::SettingsRequested:
		{
			fSettingsWindow->Lock() ;
			if( fSettingsWindow->IsHidden() )
				fSettingsWindow->Show();
			fSettingsWindow->Unlock() ;
			fSettingsWindow->Activate( true ) ;
			break ;
		}		
		default:
		{
			inherited::MessageReceived( msg ) ;
		}
	}
}
コード例 #9
0
void Gcode::solve0(int readPos){
  
  //Check if the feedrate is changed
  int checkFrPos=readPos;
  boolean setFr=0;
  String StrFr="";
  while(checkFrPos<code.length()){
    if(code[checkFrPos]=='f'||code[checkFrPos]=='F')
      {
        for(checkFrPos++;code[checkFrPos]!=' '&&checkFrPos<code.length();checkFrPos++)
        {
          StrFr= StrFr+code[checkFrPos];
        }
        setFr=1;       
      }
    checkFrPos++;
  }
  
 //execute movement
  while(readPos<code.length()){
  while(code[readPos]==' '){readPos++;}  //skip spacing
  
  String StrPos="";  //store the destination
  switch(code[readPos]){
    case 'X':
    case 'x':
      //get the destination
      for(readPos++;code[readPos]!=' '&&readPos<code.length();readPos++)
      {
        StrPos= StrPos+code[readPos];
      }
      
      Serial.print("x moves to ");
      Serial.println(atof(StrPos.c_str()));
      if (setFr==1){smX.setFeedrate(atof(StrFr.c_str()));}  //set a new feedrate for motor x
      digitalWrite(controlSwitch, 0);       //grant the access to stepper motor x
      smX.toDestination(atof(StrPos.c_str()));
      digitalWrite(controlSwitch, 1);
      break;
      
    case 'Y':
    case 'y':
      //get the destination
      for(readPos++;code[readPos]!=' '&&readPos<code.length();readPos++)
      {
        StrPos= StrPos+code[readPos];
      }
      
      Serial.print("y moves to ");
      Serial.println(atof(StrPos.c_str()));
      if (setFr==1){ smY.setFeedrate(atof(StrFr.c_str()));} //set a new feedrate for motor y
      smY.toDestination(atof(StrPos.c_str()));
      break;
      
    case 'Z':
    case 'z':
      //get the destination
      for(readPos++;code[readPos]!=' '&&readPos<code.length();readPos++)
      {
        StrPos= StrPos+code[readPos];
      }
      
      Serial.print("z moves to ");
      Serial.println(atof(StrPos.c_str()));
      if (setFr==1){smZ.setFeedrate(atof(StrFr.c_str()));} //set a new feedrate for motor z
      smZ.toDestination(atof(StrPos.c_str()));     
      break;
      
    case 'E':
    case 'e':
      //get the destination
      for(readPos++;code[readPos]!=' '&&readPos<code.length();readPos++)
      {
        StrPos= StrPos+code[readPos];
      }
      
      Serial.print("e moves to ");
      Serial.println(atof(StrPos.c_str()));
      if (setFr==1){smE.setFeedrate(atof(StrFr.c_str()));} //set a new feedrate for motor e
      smE.toDestination(atof(StrPos.c_str()));
      break;
      
    case 'R':
    case 'r':
        if(code[readPos+1]=='1') 
        {
        digitalWrite(ROLLER,1);     //The motor for the spreader(roller) is a DC motor.
        }
        if(code[readPos+1]=='0') 
        {
        digitalWrite(ROLLER,0);     
        }
        
    default:
      readPos++;
      break;
  }
  } 
}
コード例 #10
0
ファイル: contact.c プロジェクト: fenggangwu/vanetcsim
void load_contacts_with_hashtable(FILE *fsource, struct Region *aRegion, struct Hashtable *table, int mode, time_t *startAt, time_t *endAt)
{
	char buf[128], *vName1, *vName2, *tm1,*tm2, *strp, key[128];
	struct Contact *newContact;
	struct Item *aPairItem, *anEgoItem, *aLinkmanItem;
	struct Pair *aPair = NULL;
	struct Ego *anEgo = NULL;
	struct Linkman *aLinkman = NULL;

	time_t sAt, eAt;
	time_t tableStartAt, tableEndAt;
	struct Point aPoint;
	int xNumber, yNumber;
	int needed;
	int first;

	if(table == NULL)
		return;
	first = 1;
	while(fgets(buf, 128, fsource)) {

		vName1 = strtok(buf, ",");
		vName2 = strtok(NULL, ",");
		tm1 = strtok(NULL, ",");
		tm2 = strtok(NULL, ",");
		strp = strtok(NULL, ",");
		aPoint.x = atof(strp);
		strp = strtok(NULL, ",");
		aPoint.y = atof(strp);
		strp = strtok(NULL, ",");
		xNumber = atoi(strp);
		strp = strtok(NULL, ",");
		yNumber = atoi(strp);
		sAt = strtot(tm1);
		eAt = strtot(tm2);

		if(aRegion == NULL && *startAt == 0 && *endAt == 0) {
			needed = 1;
		} else if (aRegion == NULL && *startAt == 0 && *endAt) {
			if (eAt <= *endAt) needed = 1; else needed = 0;
		} else if (aRegion == NULL && *startAt && *endAt == 0) {
			if (sAt >= *startAt) needed = 1; else needed = 0;
		} else if (aRegion == NULL && *startAt && *endAt) {
			if (eAt <= *endAt && sAt >= *startAt) needed = 1; else needed = 0;
		} else if (aRegion && *startAt == 0 && *endAt == 0) {
			if (is_point_in_polygon(&aPoint, aRegion->chosen_polygon))
				needed = 1; else needed = 0;
		} else if (aRegion && *startAt == 0 && *endAt) {
			if (eAt <= *endAt && is_point_in_polygon(&aPoint, aRegion->chosen_polygon))
				needed = 1; else needed = 0;
		} else if (aRegion && *startAt && *endAt == 0) {
			if (is_point_in_polygon(&aPoint, aRegion->chosen_polygon) && sAt >= *startAt)
				needed = 1; else needed = 0;
		} else if (aRegion && *startAt && *endAt) {
			if (is_point_in_polygon(&aPoint, aRegion->chosen_polygon) && sAt >= *startAt && eAt <= *endAt)
				needed = 1; else needed = 0;
		} 
		if( needed ) {	
			newContact = (struct Contact*)malloc(sizeof(struct Contact));
			newContact->gPoint.x = aPoint.x;
			newContact->gPoint.y = aPoint.y;
			newContact->xNumber = xNumber;
			newContact->yNumber = yNumber;
			newContact->startAt = sAt;
			newContact->endAt = eAt;

			if(mode == PAIRWISE_TABLE) {
				sprintf(key, "%s,%s", vName1, vName2);
				aPairItem = hashtable_find(table, key);
				if(aPairItem == NULL) {
					aPair = (struct Pair*)malloc(sizeof(struct Pair));
					pair_init_func(aPair);
					strncpy(aPair->vName1, vName1, strlen(vName1)+1);
					strncpy(aPair->vName2, vName2, strlen(vName2)+1);
					hashtable_add(table, key, aPair);
					aPair->color.integer = rand();
					aPair->startAt = sAt;
					aPair->endAt = eAt;
					if(first) {
						tableStartAt = aPair->startAt;
						tableEndAt = aPair->endAt;
						first = 0;
					}	
				} else {
					aPair = (struct Pair*)aPairItem->datap;
					if(sAt < aPair->startAt) {
						aPair->startAt = sAt;
						if(aPair->startAt < tableStartAt)
							tableStartAt = aPair->startAt;
					}
					if(eAt > aPair->endAt) {
						aPair->endAt = eAt;
						if(aPair->endAt > tableEndAt)
							tableEndAt = aPair->endAt;
					}
				}

				newContact->fromPair = aPair;
				duallist_add_to_tail(&aPair->contents, newContact);
			} else {
				/* Ego vName1 */
				anEgoItem = hashtable_find(table, vName1);
				if(anEgoItem == NULL) {
					anEgo = (struct Ego*)malloc(sizeof(struct Ego));
					ego_init_func(anEgo);
					strncpy(anEgo->vName, vName1, strlen(vName1)+1);
					hashtable_add(table, vName1, anEgo);
					anEgo->startAt = sAt;
					anEgo->endAt = eAt;
					if(first) {
						tableStartAt = anEgo->startAt;
						tableEndAt = anEgo->endAt;
						first = 0;
					}	
				} else {
					anEgo = (struct Ego*)anEgoItem->datap;
					if(sAt < anEgo->startAt) {
						anEgo->startAt = sAt;
						if(anEgo->startAt < tableStartAt)
							tableStartAt = anEgo->startAt;
					}
					if(eAt > anEgo->endAt) {
						anEgo->endAt = eAt;
						if(anEgo->endAt > tableEndAt)
							tableEndAt = anEgo->endAt;
					}
				}

				aLinkmanItem = duallist_find(&anEgo->linkmen, vName2, (int(*)(void*,void*))linkman_has_name);
				if(aLinkmanItem == NULL) {
					aLinkman = (struct Linkman*)malloc(sizeof(struct Linkman));
					linkman_init_func(aLinkman);
					aLinkman->color.integer=rand();
					strncpy(aLinkman->vName, vName2, strlen(vName2)+1);
					duallist_add_to_tail(&anEgo->linkmen, aLinkman);
				} else 
					aLinkman = (struct Linkman*)aLinkmanItem->datap;
				newContact->fromPair = NULL;
				duallist_add_to_tail(&aLinkman->contacts, newContact);

				/* Ego vName2 */
				anEgoItem = hashtable_find(table, vName2);
				if(anEgoItem == NULL) {
					anEgo = (struct Ego*)malloc(sizeof(struct Ego));
					ego_init_func(anEgo);
					strncpy(anEgo->vName, vName2, strlen(vName2)+1);
					hashtable_add(table, vName2, anEgo);
					anEgo->startAt = sAt;
					anEgo->endAt = eAt;
				} else {
					anEgo = (struct Ego*)anEgoItem->datap;
					if(sAt < anEgo->startAt) {
						anEgo->startAt = sAt;
					}
					if(eAt > anEgo->endAt) {
						anEgo->endAt = eAt;
					}
				}

				aLinkmanItem = duallist_find(&anEgo->linkmen, vName1, (int(*)(void*,void*))linkman_has_name);
				if(aLinkmanItem == NULL) {
					aLinkman = (struct Linkman*)malloc(sizeof(struct Linkman));
					linkman_init_func(aLinkman);
					aLinkman->color.integer=rand();
					strncpy(aLinkman->vName, vName1, strlen(vName1)+1);
					duallist_add_to_tail(&anEgo->linkmen, aLinkman);
				} else 
					aLinkman = (struct Linkman*)aLinkmanItem->datap;
				duallist_add_to_tail(&aLinkman->contacts, contact_copy_func(newContact));
			}
		}

	}
	if(table->count) {
		*startAt = tableStartAt;
		*endAt = tableEndAt;
	}
}
コード例 #11
0
ファイル: my_mavlink.c プロジェクト: crashmatt/multigcs
void mavlink_parseParams1 (xmlDocPtr doc, xmlNodePtr cur, char *name) { 
	int n = 0;
	int n2 = 0;
	int n3 = 0;
	int n4 = 0;
	char tmp_str3[1024];
	for (n = 0; n < MAVLINK_PARAMETER_MAX; n++) {
		if (strcmp(MavLinkVars[n].name, name) == 0) {
			break;
		}
	}
	if (n == MAVLINK_PARAMETER_MAX) {
		return;
	}
	cur = cur->xmlChildrenNode;
	while (cur != NULL) {
		if ((!xmlStrcasecmp(cur->name, (const xmlChar *)"Range"))) {
			float min = 0.0;
			float max = 0.0;
			xmlChar *key;
			key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
			if (key != NULL) {
				sscanf((char *)key, "%f %f", &min, &max);
				MavLinkVars[n].min = min;
				MavLinkVars[n].max = max;
				xmlFree(key);
			}
		} else if ((!xmlStrcasecmp(cur->name, (const xmlChar *)"Description"))) {
			xmlChar *key;
			key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
			if (key != NULL) {
				strncpy(MavLinkVars[n].desc, (char *)key, 1023);
				xmlFree(key);
			}
		} else if ((!xmlStrcasecmp(cur->name, (const xmlChar *)"Group"))) {
			xmlChar *key;
			key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
			if (key != NULL) {
				strncpy(MavLinkVars[n].group, (char *)key, 20);
				xmlFree(key);
			}
		} else if ((!xmlStrcasecmp(cur->name, (const xmlChar *)"Values"))) {
			xmlChar *key;
			key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
			if (key != NULL) {
				strncpy(MavLinkVars[n].values, (char *)key, 1023);
				if (MavLinkVars[n].values[0] != 0) {
					MavLinkVars[n].min = atof(MavLinkVars[n].values);
					for (n2 = 0; n2 < strlen(MavLinkVars[n].values); n2++) {
						if (MavLinkVars[n].values[n2] == ',') {
							strncpy(tmp_str3, MavLinkVars[n].values + n3, 1023);
							for (n4 = 0; n4 < strlen(tmp_str3); n4++) {
								if (tmp_str3[n4] == ',') {
									tmp_str3[n4] = 0;
									break;
								}
							}
							n3 = n2 + 1;
						}
					}
					strncpy(tmp_str3, MavLinkVars[n].values + n3, 1023);
					MavLinkVars[n].max = atof(tmp_str3);
				}
				xmlFree(key);
			}
		} else if ((!xmlStrcasecmp(cur->name, (const xmlChar *)"Bits"))) {
			xmlChar *key;
			key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
			if (key != NULL) {
				strncpy(MavLinkVars[n].bits, (char *)key, 1023);
				if (MavLinkVars[n].bits[0] != 0) {
					MavLinkVars[n].min = 0;
					for (n2 = 0; n2 < strlen(MavLinkVars[n].bits); n2++) {
						if (MavLinkVars[n].bits[n2] == ',') {
							strncpy(tmp_str3, MavLinkVars[n].bits + n3, 1023);
							for (n4 = 0; n4 < strlen(tmp_str3); n4++) {
								if (tmp_str3[n4] == ',') {
									tmp_str3[n4] = 0;
									break;
								}
							}
							n3 = n2 + 1;
						}
					}
					strncpy(tmp_str3, MavLinkVars[n].bits + n3, 1023);
					MavLinkVars[n].max = (float)((1<<atoi(tmp_str3)) * (1<<atoi(tmp_str3)) - 1);
				}
				xmlFree(key);
			}
		} else if ((!xmlStrcasecmp(cur->name, (const xmlChar *)"DisplayName"))) {
			xmlChar *key;
			key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
			if (key != NULL) {
				strncpy(MavLinkVars[n].display, (char *)key, 100);
				xmlFree(key);
			}
		}
		cur = cur->next;
	}
	return;
}
コード例 #12
0
ファイル: contact.c プロジェクト: fenggangwu/vanetcsim
void load_contact_samples_with_hashtable(FILE *fsource, struct Region *aRegion, struct Hashtable *table, time_t *startAt, time_t *endAt)
{
	char buf[128], *vName1, *vName2, *tm, *strp, key[128];
	struct ContactSample *newContactSample;
	struct Item *aPairItem;
	struct Pair *aPair = NULL;
	time_t timestamp;
	time_t tableStartAt, tableEndAt;
	struct Point aPoint, bPoint;
	double distance;
	int rAngle, rSpeed;
	int needed;
	int first;
	
	if(table == NULL)
		return;

	first = 1;
	while(fgets(buf, 128, fsource)) {
		vName1 = strtok(buf, ",");
		vName2 = strtok(NULL, ",");
		tm = strtok(NULL, ",");
		strp = strtok(NULL, ",");
		aPoint.x = atof(strp);
		strp = strtok(NULL, ",");
		aPoint.y = atof(strp);
		strp = strtok(NULL, ",");
		bPoint.x = atof(strp);
		strp = strtok(NULL, ",");
		bPoint.y = atof(strp);
		strp = strtok(NULL, ",");
		distance = atof(strp);
		strp = strtok(NULL, ",");
		rAngle = atoi(strp);
		strp = strtok(NULL, ",");
		rSpeed = atoi(strp);
		timestamp = strtot(tm);

		if(aRegion == NULL && *startAt == 0 && *endAt == 0) {
			needed = 1;
		} else if (aRegion == NULL && *startAt == 0 && *endAt) {
			if (timestamp <= *endAt) needed = 1; else needed = 0;
		} else if (aRegion == NULL && *startAt && *endAt == 0) {
			if (timestamp >= *startAt) needed = 1; else needed = 0;
		} else if (aRegion == NULL && *startAt && *endAt) {
			if (timestamp <= *endAt && timestamp >= *startAt) needed = 1; else needed = 0;
		} else if (aRegion && *startAt == 0 && *endAt == 0) {
			if (is_point_in_polygon(&aPoint, aRegion->chosen_polygon) && is_point_in_polygon(&bPoint, aRegion->chosen_polygon) )
				needed = 1; else needed = 0;
		} else if (aRegion && *startAt == 0 && *endAt) {
			if (timestamp <= *endAt && is_point_in_polygon(&aPoint, aRegion->chosen_polygon) && is_point_in_polygon(&bPoint, aRegion->chosen_polygon))
				needed = 1; else needed = 0;
		} else if (aRegion && *startAt && *endAt == 0) {
			if (is_point_in_polygon(&aPoint, aRegion->chosen_polygon) && is_point_in_polygon(&bPoint, aRegion->chosen_polygon) && timestamp >= *startAt)
				needed = 1; else needed = 0;
		} else if (aRegion && *startAt && *endAt) {
			if (is_point_in_polygon(&aPoint, aRegion->chosen_polygon) && is_point_in_polygon(&bPoint, aRegion->chosen_polygon) && timestamp >= *startAt && timestamp <= *endAt)
				needed = 1; else needed = 0;
		} 
		if( needed ) {	
			newContactSample = (struct ContactSample*)malloc(sizeof(struct ContactSample));
			newContactSample->timestamp = timestamp;
			newContactSample->gPoint1.x = aPoint.x;
			newContactSample->gPoint1.y = aPoint.y;
			newContactSample->gPoint2.x = bPoint.x;
			newContactSample->gPoint2.y = bPoint.y;
			newContactSample->distance = distance;
			newContactSample->rSpeed = rSpeed;
			newContactSample->rAngle = rAngle;

			sprintf(key, "%s,%s", vName1, vName2);
			aPairItem = hashtable_find(table, key);
			if(aPairItem == NULL) {
				aPair = (struct Pair*)malloc(sizeof(struct Pair));
				pair_init_func(aPair);
				strncpy(aPair->vName1, vName1, strlen(vName1)+1);
				strncpy(aPair->vName2, vName2, strlen(vName2)+1);
				hashtable_add(table, key, aPair);
				aPair->startAt = timestamp;
				aPair->endAt = timestamp;
				if(first) {
					tableStartAt = aPair->startAt;
					tableEndAt = aPair->endAt;
					first = 0;
				}	
			} else {
				aPair = (struct Pair*)aPairItem->datap;
				if(timestamp < aPair->startAt) {
					aPair->startAt = timestamp;
					if(aPair->startAt < tableStartAt)
						tableStartAt = aPair->startAt;
				}
				if(timestamp > aPair->endAt) {
					aPair->endAt = timestamp;
					if(aPair->endAt > tableEndAt)
						tableEndAt = aPair->endAt;
				}
			}
			newContactSample->fromPair = aPair;
			duallist_add_to_tail(&aPair->contents, newContactSample);
		}
	}

	if(table->count) {
		*startAt = tableStartAt;
		*endAt = tableEndAt;
	}
}
コード例 #13
0
ファイル: e2ga.cpp プロジェクト: Sciumo/gasandbox
	char *string(const mv & obj, char *str, int maxLength, const char *fp /* = NULL */) {
		int stdIdx = 0, l;
		char tmpBuf[256], tmpFloatBuf[256]; 
		int i, j, k = 0, bei, ia = 0, s = mv_size[obj.gu()], p = 0, cnt = 0;

		// set up the floating point precision
		if (fp == NULL) fp = mv_string_fp;

		// start the string
		l = sprintf(tmpBuf, "%s", mv_string_start);
		if (stdIdx + l <= maxLength) {
			strcpy(str + stdIdx, tmpBuf);
			stdIdx += l;
		}
		else mv_throw_exception("Buffer supplied to string() is too small", MV_EXCEPTION_ERROR);

		// print all coordinates
		for (i = 0; i <= 2; i++) {
			if (obj.gu() & (1 << i)) {
				for (j = 0; j < mv_gradeSize[i]; j++) {
					float coord = (float)mv_basisElementSign[ia] * obj.m_c[k];
					/* goal: print [+|-]obj.m_c[k][* basisVector1 ^ ... ^ basisVectorN] */			
					sprintf(tmpFloatBuf, fp, fabs(coord));
					if (atof(tmpFloatBuf) != 0.0) {
						l = 0;

						// print [+|-]
						l += sprintf(tmpBuf + l, "%s", (coord >= 0.0) 
							? (cnt ? mv_string_plus : "")
							: mv_string_minus);
						// print obj.m_c[k]
						l += sprintf(tmpBuf + l, tmpFloatBuf);

						if (i) { // if not grade 0, print [* basisVector1 ^ ... ^ basisVectorN]
							l += sprintf(tmpBuf + l, "%s", mv_string_mul);

							// print all basis vectors
							bei = 0;
							while (mv_basisElements[ia][bei] >= 0) {
								l += sprintf(tmpBuf + l, "%s%s", (bei) ? mv_string_wedge : "", 
									mv_basisVectorNames[mv_basisElements[ia][bei]]);
								bei++;
							}
						}

						//copy all to 'str'
						if (stdIdx + l <= maxLength) {
							strcpy(str + stdIdx, tmpBuf);
							stdIdx += l;
						}
						else mv_throw_exception("Buffer supplied to string() is too small", MV_EXCEPTION_ERROR);
						cnt++;
					}
					k++; ia++;
				}
			}
			else ia += mv_gradeSize[i];
		}

		// if no coordinates printed: 0
		l = 0;
		if (cnt == 0) {
			l += sprintf(tmpBuf + l, "0");
		}

		// end the string
		l += sprintf(tmpBuf + l, "%s", mv_string_end);
		if (stdIdx + l <= maxLength) {
			strcpy(str + stdIdx, tmpBuf);
			stdIdx += l;
		}
		else mv_throw_exception("Buffer supplied to string() is too small", MV_EXCEPTION_ERROR);

		return str;
	}
コード例 #14
0
ファイル: exercise7-4.c プロジェクト: Kybrnts/BeginningC
int main(void) {

  const char *inputword = "input",
    *doneword = "done",
    *quitword = "quit";

  char *input = NULL;                 /* Input buffer                                                               */
  float **readings = NULL,            /* List of arrays of readings, one element points to an array of six elements */
    **tmpreadings = NULL;             /* Temporal storage for readings list                                         */
  double *averages = NULL;            /* Storage for averages of each element of the readings list                  */

  unsigned int i, j, k,
    readingslen = 0,
    tmpreadingslen = 0,
    averageslen = 0;

  bool domath = false;


  /* Allocate memory for the input */
  input = (char *)malloc(INPUTSIZE*sizeof(char));
  if(!input) {
    return 1;
  }
  
  /* Explain the user the program usage */
  printf("\nEnter %d temperature readings for an arbitrary number of days to be averaged for each day."
	 "\nUse the words \"%s\", \"%s\" and \"%s\" to finish the program, to start entering readings"
	 "\nand to proceed with the math respectively.\n\n", RDNGSSIZE, quitword, inputword, doneword);
  
  /* Read each day */
  while(1) {
    printf("Input readings for %s day? (%s/%s/%s)$ ",
	   readingslen < 1 ? "first" : "next", inputword, doneword, quitword);

    /* Get answer */
    for(i = 0; i < INPUTSIZE; i++)                /* Read from input         */
      if((*(input + i) = getchar()) == '\n') {
	*(input + i++) = '\0';
	break;                               
      }
    if(i == INPUTSIZE && *(input + i - 1)) {      /* Input size exceeded?    */
      printf("Error! Input buffer size exceeded. Try again.\n");
      while(getchar() != '\n');                   /* Flush the stdin (avoid fflush) */
      continue;
    }
    for(i = 0, j = 0; *(input + j); j++) {       /* Remove spaces from input */
      if(!(*(input + j) == SPACE || *(input + j) == TAB))
	*(input + i++) = tolower(*(input + j));
    }
    *(input + i) = '\0';                         /* Add string terminator    */

    /* If answer is non of the three possible options ask again */
    if(!(strcmp(input, inputword) == 0 || strcmp(input, doneword) == 0 || strcmp(input, quitword) == 0)) {
      printf("Please use one of the following: %s, %s or %s\n", inputword, doneword, quitword);
      continue;
    }

    /* If answer is to quit finish program */
    if(strcmp(input, quitword) == 0) {
      printf("Ok, bye then...\n");
      return 0;
    }

    /* If answer is done, go ahead with the math */
    if(strcmp(input, doneword) == 0) {
      if(readingslen < 1) {
	printf("There are no temperature readings yet, please input some or quit.\n");
	continue;
      }
      else
	domath = true;
      break;
    }    
    
    /* If the answer it to input, Get the required readings and store them in memory */
    if(strcmp(input, inputword) == 0) {

      /* Save the previously entered values in temporal memory space and create more space */
      tmpreadingslen = readingslen;
      tmpreadings = (float **)malloc(tmpreadingslen*sizeof(float *));
      if(!tmpreadings) {
	printf("Error! Unable to allocate memory for the temporal readings list. Finishing program...\n");
	return 1;
      }
      for(i = 0; i < readingslen; i++)
	*(tmpreadings + i) = *(readings + i);
      free(readings);
      readings = NULL;
      readingslen++;
      readings = (float **)malloc(readingslen*sizeof(float *));
      if(!readings) {
	printf("Error! Unable to allocate memory for the new readings list. Finishing program...\n");
	return 1;
      }
      for(i = 0; i < tmpreadingslen; i++)
	*(readings + i) = *(tmpreadings + i);
      free(tmpreadings);
      tmpreadings = NULL;
      /* Allocate memory for the array of readings in the matching element of the readings list */
      *(readings + readingslen - 1) = (float *)calloc(RDNGSSIZE, sizeof(float));
      if(!(*(readings + readingslen - 1))) {
	printf("Error! Unable to allocate memory for the new readings list element. Finishing program..\n");
	return 1;
      }
      /* Read RDNGSSIZE temperature values to input */
      for(i = 0; i < RDNGSSIZE; i++) {
	
	/* Get one temperature reading */
	printf("  Temperature reading #%d or %s? ", i + 1, quitword);
	for(j = 0; j < INPUTSIZE; j++)
	  if((*(input + j) = getchar()) == '\n') {
	    *(input + j++) = '\0';
	    break;
	  }
	if(j == INPUTSIZE && *(input + j - 1)) {
	  printf("Error! Input buffer size exceeded. This reading will be ignored.\n");
	  while(getchar() != '\n');
	  i--;
	  continue;
	}
	for(j = 0, k = 0; *(input + k); k++) {
	  if(!(*(input + k) == SPACE || *(input + k) == TAB))
	    *(input + j++) = tolower(*(input + k));
	}
	*(input + j) = '\0';

	/* If input is to quit finish program */
	if(strcmp(input, quitword) == 0) {
	  printf("Ok, bye then...\n");
	  return 0;
	}
		
	/* Discard input if not numeric */
	if(!(*input == PLUS || *input == MINUS || isdigit(*input))) {
	  printf("Last entered value is not a float. Will be ignored.\n");
	  i--;
	  continue;
	}
	for(j = 1; isdigit(*(input + j)); j++);
	if(*(input + j) != POINT) {
	  if(*(input + j)) {
	    printf("Last entered value is not a float. Will be ignored.\n");
	    i--;
	    continue;      
	  }
	}
	if(*(input + j)) {
	  for(j++; isdigit(*(input + j)); j++);
	  if(*(input + j)) {
	    printf("Last entered value is not a float. Will be ignored.\n");
	    i--;
	    continue;
	  }
	}
	/* Save when numeric */
	(*(readings + readingslen - 1))[i] = atof(input);
      }
      continue;
    }
  }

  /* Input is no loger needed */
  free(input);
  input = NULL;
  
  /* If we have to do the math.. */
  if(domath) {
    
    /* Allocate memory for the averages list */
    averageslen = readingslen;
    averages = (double *)calloc(averageslen, sizeof(double));
    if(!averages) {
      printf("Error! Unable to allocate memory for the averages list. Finishing program..\n");
      return 1;
    }

    /* Calculate each day's average */
    for(i = 0; i < readingslen; i++) {
      for(j = 0; j < RDNGSSIZE; j++)
	averages[i] += (double)(*(readings + i))[j];
        averages[i] /= (double)RDNGSSIZE;
    }

    /* Display results in a suitable table format */
    printf("\nTable of resuts:"
           "\n+-------");
    for(i = 0; i < RDNGSSIZE; i++)
      printf("+-------------");
    printf("+---------+\n");
    printf("| Day #");
    for(i = 0; i < RDNGSSIZE; i++)
      printf(" | Reading #%-2d", i + 1);
    printf(" | Average |\n");
    printf("+-------");
    for(i = 0; i < RDNGSSIZE; i++)
      printf("+-------------");
    printf("+---------+\n");
    for(i = 0; i < readingslen; i++) {
        printf("| %-5d", i + 1);
	for(j = 0; j < RDNGSSIZE; j++)
	  printf(" | %-11.1f", (*(readings + i))[j]);
	printf(" | %-7.1f |\n", averages[i]);
    }
    printf("+-------");
    for(i = 0; i < RDNGSSIZE; i++)
      printf("+-------------");
    printf("+---------+\n");
  }
  return 0;
}
コード例 #15
0
ファイル: lurker.c プロジェクト: wader/lurker
int main(int argc, char **argv)
{
    int r;
    int option;
    struct option getopt_options[] =
    {
        {"help", 0, 0, 'h'},
        {"input", 1, 0, 'i'},
        {"output", 1, 0, 'o'},
        {"append", 1, 0, 'a'},
        {"threshold", 1, 0, 't'},
        {"runlength", 1, 0, 'r'},
        {"filter", 1, 0, 'f'},
        {"start", 1, 0, 's'},
        {"divisor", 1, 0, 'd'},
        {NULL, 0, 0, 0}
    };

    /* defaults */
    input = NULL; /* stdin */
    output = "clip_%F_%H:%M:%S.wav";
    /* use .wav to be nice to people who like to listen while recording */
    recording_append = ".recording.wav";
    threshold = 0.1;
    runlength = 4;
    short_filter = 0; /* dont filter */
    time_start = 0; /* 0 = use system time */
    slice_divisor = 60;

    /* shameless plug */
    printf("lurker 0.4, (C)2004 Mattias Wadman <*****@*****.**>\n");

    while(1)
    {
        option = getopt_long(argc, argv, "hi:o:a:t:r:f:s:d:", getopt_options, NULL);

        if(option == -1)
            break;
        else if(option == 'h')
        {
            printf("Usage: %s [OPTION]...\n"
                   "    -i, --input PATH       Input file (stdin)\n"
                   "    -o, --output PATH      Output path, strftime formated (%s)\n"
                   "    -a, --append STRING    Append to filename while recording (%s)\n"
                   "    -t, --threshold NUMBER Sound level threshold to trigger (%g)\n"
                   "    -r, --runlength NUMBER Seconds of silence to untrigger (%g)\n"
                   "    -f, --filter NUMBER    Remove clip if length is less then NUMBER seconds (%g)\n"
                   "    -s, --start DATETIME   Use a given start time and offset with audio time\n"
                   "                           Eg: \"2000-01-02 03:04:05\"\n"
                   "                           Eg: now (use system clock as start)\n"
                   "    -d, --divisor NUMBER   Slice sample rate into NUMBER parts internally (%g)\n"
                   "",
                   argv[0], output, recording_append, threshold, runlength,
                   short_filter, slice_divisor
                   );

            return EXIT_SUCCESS;
        }
        else if(option == 'i')
            input = optarg;
        else if(option == 'o')
            output = optarg;
        else if(option == 'a')
            recording_append = optarg;
        else if(option == 't')
            threshold = atof(optarg);
        else if(option == 'r')
            runlength = atof(optarg);
        else if(option == 'f')
            short_filter = atof(optarg);
        else if(option == 's')
        {
            struct tm t;
            char *s;

            if(strcmp(optarg, "now") == 0)
                time_start = time(NULL);
            else
            {
                s = strptime(optarg, "%Y-%m-%d %H:%M:%S", &t);
                if(s == NULL || *s != '\0')
                {
                    fprintf(stderr, "Invalid time format\n");

                    return EXIT_FAILURE;
                }
                
                time_start = mktime(&t);
            }
        }
        else if(option == 'd')
            slice_divisor = atof(optarg);
        else
        {
            fprintf(stderr, "Error in argument: %c\n", option);

            return EXIT_FAILURE;
        }
    }
   
    /* string used to clear current line */
    clear_line = generate_clear_line_string();
    if(clear_line == NULL)
    {
        fprintf(stderr, "generate_clear_line_string failed, fallback to \"\\r\"\n");
        clear_line = strdup("\r");
    }
   
    /* get current working path and make sure it end with a slash */
    current_dir = get_current_dir_name();
    if(current_dir == NULL)
    {
        fprintf(stderr, "get_current_dir_name failed\n");

        return EXIT_FAILURE;
    }
    /* it is possible that it already ends with a slash, see man page about $PWD */
    else if(current_dir[strlen(current_dir) - 1] != '/')
    {
        char *t;

        if(asprintf(&t, "%s/", current_dir) == -1)
        {
            fprintf(stderr, "asprintf failed\n");

            return EXIT_FAILURE;
        }

        free(current_dir);
        current_dir = t;
    }

    r = lurk();
    free(current_dir);
    free(clear_line);

    return (r == -1 ? EXIT_FAILURE : EXIT_SUCCESS);
}
コード例 #16
0
void CPrefsDlg::LoadPrefs() {
	CString strBuff;
	CString strPrefab = g_strAppPath;
	AddSlash(strPrefab);
	strPrefab += "Prefabs\\";

	m_nMouseButtons = 3;

	m_bTextureLock = GetCvarInt( TLOCK_KEY, TLOCK_DEF );
	m_bRotateLock = GetCvarInt( RLOCK_KEY, TLOCK_DEF );
	m_strLastProject = GetCvarString( LASTPROJ_KEY, "" );
	m_strLastMap = GetCvarString( LASTMAP_KEY, "" );
	m_bLoadLast = GetCvarInt( LOADLAST_KEY, LOADLAST_DEF );
	m_bRunBefore = GetCvarInt( RUN_KEY, RUN_DEF );
	m_bFace = GetCvarInt( FACE_KEY, 1 );
	m_bRightClick = GetCvarInt( RCLICK_KEY, 1 );
	m_bVertex = GetCvarInt( VERTEX_KEY, 1 );
	m_bAutoSave = GetCvarInt( AUTOSAVE_KEY, 1 );
	m_bNewApplyHandling = GetCvarInt( NEWAPPLY_KEY, 0 );
	m_bLoadLastMap = GetCvarInt( LOADLASTMAP_KEY, 0 );
	m_bGatewayHack = GetCvarInt( HACK_KEY, 0 );
	m_bTextureWindow = GetCvarInt( TEXTURE_KEY, 0 );
	m_bCleanTiny = GetCvarInt( TINYBRUSH_KEY, 0 );
	strBuff = GetCvarString( TINYSIZE_KEY, "0.5" );
	m_fTinySize = atof(strBuff );
	m_nAutoSave = GetCvarInt( AUTOSAVETIME_KEY, 5 );
	if ( m_nAutoSave <= 0 ) { m_nAutoSave = 1; }
	m_strAutoSave.Format("%i", m_nAutoSave );
	m_bSnapShots = GetCvarInt( SNAPSHOT_KEY, 0 );
	m_nStatusSize = GetCvarInt( STATUS_KEY, 10 );
	m_nMoveSpeed = GetCvarInt( MOVESPEED_KEY, 400 );
	m_nAngleSpeed = GetCvarInt( ANGLESPEED_KEY, 300 );
	m_bCamXYUpdate = GetCvarInt( CAMXYUPDATE_KEY, 1 );
	m_bNewLightDraw = GetCvarInt( LIGHTDRAW_KEY, 1 );
	m_bCubicClipping = ( GetCvarInt( CUBICCLIP_KEY, 1) != 0  );
	m_nCubicScale = GetCvarInt( CUBICSCALE_KEY, 13 );
	m_bALTEdge = GetCvarInt( ALTEDGE_KEY, 0 );
	m_bQE4Painting = GetCvarInt( QE4PAINT_KEY, 1 );
	m_bSnapTToGrid = GetCvarInt( SNAPT_KEY, 0 );
	m_bXZVis = GetCvarInt( XZVIS_KEY, 0 );
	m_bYZVis = GetCvarInt( YZVIS_KEY, 0 );
	m_bZVis = GetCvarInt( ZVIS_KEY, 1 );
	m_bSizePaint = GetCvarInt( SIZEPAINT_KEY, 0 );
	m_bWideToolbar = GetCvarInt( WIDETOOLBAR_KEY, 1 );
	m_bNoClamp = GetCvarInt( NOCLAMP_KEY, 0 );
	m_nRotation = GetCvarInt( ROTATION_KEY, 45 );
	m_bHiColorTextures = GetCvarInt( HICOLOR_KEY, 1 );
	m_bChaseMouse = GetCvarInt( CHASEMOUSE_KEY, 1 );
	m_nEntityShowState = GetCvarInt( ENTITYSHOW_KEY, 0 );
	m_nTextureScale = GetCvarInt( TEXTURESCALE_KEY, 50 );
	m_bTextureScrollbar = GetCvarInt( TEXTURESCROLLBAR_KEY, TRUE );
	m_bDisplayLists = GetCvarInt( DISPLAYLISTS_KEY, TRUE );
	m_bSwitchClip = GetCvarInt( SWITCHCLIP_KEY, TRUE );
	m_bSelectWholeEntities = GetCvarInt( SELWHOLEENTS_KEY, TRUE );
	m_nTextureQuality = GetCvarInt( TEXTUREQUALITY_KEY, 6 );
	m_bGLLighting = GetCvarInt( GLLIGHTING_KEY, FALSE );
	m_bNoStipple = GetCvarInt( NOSTIPPLE_KEY, 0 );
	m_nUndoLevels = GetCvarInt( UNDOLEVELS_KEY, 63 );
	m_strMaps = GetCvarString( MAPS_KEY, "" );
	m_strModels = GetCvarString( MODELS_KEY, "" );
	m_bNoStipple = GetCvarInt( NEWMAPFORMAT_KEY, 1 );

	if ( m_bRunBefore == FALSE ) {
		SetGamePrefs();
	}
}
コード例 #17
0
ファイル: validator.cpp プロジェクト: freehal/boinc-freehal
int main(int argc, char** argv) {
    int i, retval;

    const char *usage = 
      "\nUsage: %s -app <app-name> [OPTIONS]\n"
      "Start validator for application <app-name>\n\n"
      "Optional arguments:\n"
      "  --one_pass_N_WU N       Validate at most N WUs, then exit\n"
      "  --one_pass              Make one pass through WU table, then exit\n"
      "  --mod n i               Process only WUs with (id mod n) == i\n"
      "  --max_claimed_credit X  If a result claims more credit than this, mark it as invalid\n"
      "  --max_granted_credit X  Grant no more than this amount of credit to a result\n"
      "  --grant_claimed_credit  Grant the claimed credit, regardless of what other results for this workunit claimed\n"
      "  --update_credited_job   Add record to credited_job table after granting credit\n"
      "  --credit_from_wu        Credit is specified in WU XML\n"
      "  --sleep_interval n      Set sleep-interval to n\n"
      "  -d n, --debug_level n   Set log verbosity level, 1-4\n\n";

    if ((argc > 1) && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
        printf (usage, argv[0] );
        exit(1);
    }


    check_stop_daemons();

    for (i=1; i<argc; i++) {
        if (is_arg(argv[i], "one_pass_N_WU")) {
            one_pass_N_WU = atoi(argv[++i]);
            one_pass = true;
        } else if (is_arg(argv[i], "sleep_interval")) {
            sleep_interval = atoi(argv[++i]);
        } else if (is_arg(argv[i], "one_pass")) {
            one_pass = true;
        } else if (is_arg(argv[i], "app")) {
            strcpy(app_name, argv[++i]);
        } else if (is_arg(argv[i], "d") || is_arg(argv[i], "debug_level")) {
            debug_level = atoi(argv[++i]);
            log_messages.set_debug_level(debug_level);
            if (debug_level == 4) g_print_queries = true;
        } else if (is_arg(argv[i], "mod")) {
            wu_id_modulus = atoi(argv[++i]);
            wu_id_remainder = atoi(argv[++i]);
        } else if (is_arg(argv[i], "max_granted_credit")) {
            max_granted_credit = atof(argv[++i]);
        } else if (is_arg(argv[i], "max_claimed_credit")) {
            max_claimed_credit = atof(argv[++i]);
        } else if (is_arg(argv[i], "grant_claimed_credit")) {
            grant_claimed_credit = true;
        } else if (is_arg(argv[i], "update_credited_job")) {
            update_credited_job = true;
        } else if (is_arg(argv[i], "credit_from_wu")) {
            credit_from_wu = true;
        } else {
            fprintf(stderr,
                "Invalid option '%s'\nTry `%s --help` for more information\n",
                argv[i], argv[0]
            );
            log_messages.printf(MSG_CRITICAL, "unrecognized arg: %s\n", argv[i]);
            exit(1);
        }
    }

    if (app_name[0] == 0) {
        log_messages.printf(MSG_CRITICAL,
            "must use '--app' to specify an application\n"
        );
        printf (usage, argv[0] );
        exit(1);      
    }

    retval = config.parse_file();
    if (retval) {
        log_messages.printf(MSG_CRITICAL,
            "Can't parse config.xml: %s\n", boincerror(retval)
        );
        exit(1);
    }

    log_messages.printf(MSG_NORMAL,
        "Starting validator, debug level %d\n", log_messages.debug_level
    );
    if (wu_id_modulus) {
        log_messages.printf(MSG_NORMAL,
            "Modulus %d, remainder %d\n", wu_id_modulus, wu_id_remainder
        );
    }

    install_stop_signal_handler();

    main_loop();
}
コード例 #18
0
ファイル: main.c プロジェクト: dlindelof/cintro
/* reverse Polish calculator */
int main()
{
    int type;
    double op2, op1;
    char s[MAXOP];

    while ((type = getop(s)) != EOF) {
        switch (type) {
        case NUMBER:
            push(atof(s));
            break;
        case '+':
            push(pop() + pop());
            break;
        case '*':
            push(pop() * pop());
            break;
        case '-':
            op2 = pop();
            push(pop() - op2);
            break;
        case '/':
            op2 = pop();
            if (op2 != 0.0)
                push(pop() / op2);
            else
                printf("error: zero divisor\n");
            break;
        case '%':
          op2 = pop();
          if (op2 != 0.0)
            push(fmod(pop(), op2));
          else
            printf("error: zero divisor\n");
          break;       
        case '?': /* print top element of the stack */
          op2 = pop();
          printf("\t%.8g\n", op2);
          push(op2);
          break;
        case 'd': /* duplicate top element of stack */
          op2 = pop();
          push(op2);
          push(op2);
          break;
        case 's': /* swap top elements */
          op2 = pop();
          op1 = pop();
          push(op2);
          push(op1);
          break;
        case '\n':
            printf("\t%.8g\n", pop());
            break;
        default:
            printf("error: unknown command %s\n", s);
            break;
        }
    }
    return 0;
}
コード例 #19
0
ファイル: LALHybridTest.c プロジェクト: smirshekari/lalsuite
/* Main Program */
INT4 main ( INT4 argc, CHAR *argv[] ) {

  static LALStatus status;
  INT4 c;
  UINT4 i;
  REAL8 dt, totTime;
  REAL8 sampleRate = -1;
  REAL8 totalMass = -1, massRatio = -1;
  REAL8 lowFreq = -1, df, fLow;
  CHAR  *outFile = NULL, *outFileLong = NULL, tail[50];
  size_t optarg_len;
  REAL8 eta;
  REAL8 newtonianChirpTime, PN1ChirpTime, mergTime;
  UINT4 numPts;
  LIGOTimeGPS epoch;
  REAL8 offset;

  PhenomCoeffs coeffs;
  PhenomParams params;

  REAL4FrequencySeries     *Aeff   = NULL, *Phieff  = NULL;
  COMPLEX8Vector           *uFPlus = NULL, *uFCross = NULL;

  COMPLEX8 num;

  REAL4Vector      *hPlus = NULL, *hCross = NULL;
  REAL4TimeSeries  *hP = NULL, *hC = NULL;
  /*  REAL4TimeSeries  *hP = NULL, *hC = NULL;*/
  REAL4FFTPlan     *prevPlus = NULL, *prevCross = NULL;

  /*REAL4Vector      *Freq = NULL;*/

  UINT4 windowLength;
  INT4 hPLength;
  REAL8 linearWindow;

  /* getopt arguments */
  struct option long_options[] =
  {
    {"mass-ratio",              required_argument, 0,                'q'},
    {"low-freq (Hz)",           required_argument, 0,                'f'},
    {"total-mass (M_sun)",      required_argument, 0,                'm'},
    {"sample-rate",             required_argument, 0,                's'},
    {"output-file",             required_argument, 0,                'o'},
    {"help",                    no_argument,       0,                'h'},
    {"version",                 no_argument,       0,                'V'},
    {0, 0, 0, 0}
  };

  /* parse the arguments */
  while ( 1 )
  {
    /* getopt_long stores long option here */
    int option_index = 0;

    /* parse command line arguments */
    c = getopt_long_only( argc, argv, "q:t:d:hV",
        long_options, &option_index );

    /* detect the end of the options */
    if ( c == -1 )
      {
	break;
      }

    switch ( c )
    {
      case 0:
        fprintf( stderr, "Error parsing option '%s' with argument '%s'\n",
            long_options[option_index].name, optarg );
        exit( 1 );
        break;

      case 'h':
        /* help message */
        print_usage( argv[0] );
        exit( 0 );
        break;

      case 'V':
        /* print version information and exit */
        fprintf( stdout, "%s - Compute Ajith's Phenomenological Waveforms " \
		 "(arXiv:0710.2335) and output them to a plain text file\n" \
            "CVS Version: %s\nCVS Tag: %s\n", PROGRAM_NAME, CVS_ID_STRING, \
            CVS_NAME_STRING );
        exit( 0 );
        break;

      case 'q':
        /* set mass ratio */
        massRatio = atof( optarg );
        break;

      case 'f':
        /* set low freq */
        lowFreq = atof( optarg );
        break;

      case 'm':
        /* set total mass */
        totalMass = atof( optarg );
        break;

      case 's':
        /* set sample rate */
        sampleRate = atof( optarg );
        break;

      case 'o':
	/* set name of output file */
        optarg_len = strlen(optarg) + 1;
        outFile = (CHAR *)calloc(optarg_len, sizeof(CHAR));
        memcpy(outFile, optarg, optarg_len);
	break;

      case '?':
        print_usage( argv[0] );
        exit( 1 );
        break;

      default:
        fprintf( stderr, "ERROR: Unknown error while parsing options\n" );
        print_usage( argv[0] );
        exit( 1 );
    }
  }

  if ( optind < argc )
  {
    fprintf( stderr, "ERROR: Extraneous command line arguments:\n" );
    while ( optind < argc )
      {
	fprintf ( stderr, "%s\n", argv[optind++] );
      }
    exit( 1 );
  }


  /* * * * * * * * */
  /* Main Program  */
  /* * * * * * * * */

  eta = massRatio / pow(1. + massRatio, 2.);

  /* This freq low is the one used for the FFT */
  /* fLow = 2.E-3/(totalMass*LAL_MTSUN_SI); */
  fLow = lowFreq;       /* Changed by Ajith. 5 May 2008 */

  /* Phenomenological coefficients as in Ajith et. al */
  GetPhenomCoeffsLongJena( &coeffs );

  /* Compute phenomenologial parameters */
  ComputeParamsFromCoeffs( &params, &coeffs, eta, totalMass );


  /* Check validity of arguments */

  /* check we have freqs */
  if ( totalMass < 0 )
    {
      fprintf( stderr, "ERROR: --total-mass must be specified\n" );
      exit( 1 );
    }

  /* check we have mass ratio and delta t*/
  if ( massRatio < 0 )
    {
      fprintf( stderr, "ERROR: --mass-ratio must be specified\n" );
      exit( 1 );
    }
  if ( lowFreq < 0 )
    {
      fprintf( stderr, "ERROR: --low-freq must be specified\n" );
      exit( 1 );
    }
  if ( sampleRate < 0 )
    {
      fprintf( stderr, "ERROR: --sample-rate must be specified\n" );
      exit( 1 );
    }
  if ( lowFreq > params.fCut )
    {
      fprintf( stderr, "\nERROR in --low-freq\n"\
	       "The value chosen for the low frequency is larger "\
	       "than the frequency at the merger.\n"
	       "Frequency at the merger: %4.2f Hz\nPick either a lower value"\
	       " for --low-freq or a lower total mass\n\n", params.fCut);
      exit(1);
    }
  if ( lowFreq < fLow )
    {
      fprintf( stderr, "\nERROR in --low-freq\n"\
	       "The value chosen for the low frequency is lower "\
	       "than the lowest frequency computed\nby the implemented FFT.\n"
	       "Lowest frequency allowed: %4.2f Hz\nPick either a higher value"\
	       " for --low-freq or a higher total mass\n\n", fLow);
      exit(1);
    }
  if ( outFile == NULL )
    {
      fprintf( stderr, "ERROR: --output-file must be specified\n" );
      exit( 1 );
    }

  /* Complete file name with details of the input variables */
  sprintf(tail, "%s-Phenom_M%3.1f_R%2.1f.dat", outFile, totalMass, massRatio);
  optarg_len = strlen(tail) + strlen(outFile) + 1;
  outFileLong = (CHAR *)calloc(optarg_len, sizeof(CHAR));
  strcpy(outFileLong, tail);

  /* check sample rate is enough */
  if (sampleRate > 4.*params.fCut)   /* Changed by Ajith. 5 May 2008 */
    {
      dt = 1./sampleRate;
    }
  else
    {
      sampleRate = 4.*params.fCut;
      dt = 1./sampleRate;
    }

  /* Estimation of the time duration of the binary           */
  /* See Sathya (1994) for the Newtonian and PN1 chirp times */
  /* The merger time is overestimated                        */
  newtonianChirpTime =
    (5./(256.*eta))*pow(totalMass*LAL_MTSUN_SI,-5./3.)*pow(LAL_PI*fLow,-8./3.);
  PN1ChirpTime =
    5.*(743.+924.*eta)/(64512.*eta*totalMass*LAL_MTSUN_SI*pow(LAL_PI*fLow,2.));
  mergTime = 2000.*totalMass*LAL_MTSUN_SI;
  totTime = 1.2 * (newtonianChirpTime + PN1ChirpTime + mergTime);

  numPts = (UINT4) ceil(totTime/dt);
  df = 1/(numPts * dt);

  /* Compute Amplitude and Phase from the paper (Eq. 4.19) */
  Aeff = XLALHybridP1Amplitude(&params, fLow, df, eta, totalMass, numPts/2+1);
  Phieff = XLALHybridP1Phase(&params, fLow, df, eta, totalMass, numPts/2 +1);

  /* Construct u(f) = Aeff*e^(i*Phieff) */
  XLALComputeComplexVector(&uFPlus, &uFCross, Aeff, Phieff);

  /* Scale this to units of M */
  for (i = 0; i < numPts/2 + 1; i++) {
    num = uFPlus->data[i];
    num.re *= 1./(dt*totalMass*LAL_MTSUN_SI);
    num.im *= 1./(dt*totalMass*LAL_MTSUN_SI);
    uFPlus->data[i] = num;
    num = uFCross->data[i];
    num.re *= 1./(dt*totalMass*LAL_MTSUN_SI);
    num.im *= 1./(dt*totalMass*LAL_MTSUN_SI);
    uFCross->data[i] = num;
  }

  /* Inverse Fourier transform */
  LALCreateReverseREAL4FFTPlan( &status, &prevPlus, numPts, 0 );
  LALCreateReverseREAL4FFTPlan( &status, &prevCross, numPts, 0 );
  hPlus = XLALCreateREAL4Vector(numPts);
  hCross = XLALCreateREAL4Vector(numPts);

  LALReverseREAL4FFT( &status, hPlus, uFPlus, prevPlus );
  LALReverseREAL4FFT( &status, hCross, uFCross, prevCross );

  /* The LAL implementation of the FFT omits the factor 1/n */
  for (i = 0; i < numPts; i++) {
    hPlus->data[i] /= numPts;
    hCross->data[i] /= numPts;
  }

  /* Create TimeSeries to store more info about the waveforms */
  /* Note: it could be done easier using LALFreqTimeFFT instead of ReverseFFT */
  epoch.gpsSeconds = 0;
  epoch.gpsNanoSeconds = 0;

  hP =
    XLALCreateREAL4TimeSeries("", &epoch, 0, dt, &lalDimensionlessUnit, numPts);
  hP->data = hPlus;
  hC =
    XLALCreateREAL4TimeSeries("", &epoch, 0, dt, &lalDimensionlessUnit, numPts);
  hC->data = hCross;

  /* Cutting off the part of the waveform with f < fLow */
  /*  Freq = XLALComputeFreq( hP, hC);
      hP = XLALCutAtFreq( hP, Freq, lowFreq);
      hC = XLALCutAtFreq( hC, Freq, lowFreq); */

  /* multiply the last few samples of the time-series by a linearly
   * dropping window function in order to avid edges in the data
   * Added by Ajith 6 May 2008 */

  hPLength = hP->data->length;
  windowLength = (UINT4) (20.*totalMass * LAL_MTSUN_SI/dt);
  for (i=1; i<= windowLength; i++){
    linearWindow =  (i-1.)/windowLength;
    hP->data->data[hPLength-i] *= linearWindow;
    hC->data->data[hPLength-i] *= linearWindow;
  }

  /* Convert t column to units of (1/M) */
  /*  offset *= (1./(totalMass * LAL_MTSUN_SI));
      hP->deltaT *= (1./(totalMass * LAL_MTSUN_SI)); */

  /* Set t = 0 at the merger (defined as the max of the NR wave) */
  XLALFindNRCoalescenceTimeFromhoft( &offset, hP);
  XLALGPSAdd( &(hP->epoch), -offset);
  XLALGPSAdd( &(hC->epoch), -offset);

  /* Print waveforms to file */
  LALPrintHPlusCross( hP, hC, outFileLong );

  /* Free Memory */

  XLALDestroyREAL4FrequencySeries(Aeff);
  XLALDestroyREAL4FrequencySeries(Phieff);

  XLALDestroyREAL4FFTPlan(prevPlus);
  XLALDestroyREAL4FFTPlan(prevCross);

  XLALDestroyCOMPLEX8Vector(uFPlus);
  XLALDestroyCOMPLEX8Vector(uFCross);
  XLALDestroyREAL4TimeSeries(hP);
  XLALDestroyREAL4TimeSeries(hC);
  /*  XLALDestroyREAL4TimeSeries(hP); */
  /*  XLALDestroyREAL4TimeSeries(hC); */

  return(0);

}
コード例 #20
0
ファイル: DF_GPS.cpp プロジェクト: arispujud/Arduino
double DFGPS::getLongitude () {
	double lon = (double)decToInt (gpsp[2], 2);
	return lon + atof (gpsp[2]+2) / 60.0;
}
コード例 #21
0
ファイル: imgpro.cpp プロジェクト: azrosen92/comp_vision
int 
main(int argc, char **argv)
{
  // Look for help
  for (int i = 0; i < argc; i++) {
    if (!strcmp(argv[i], "-help")) {
      ShowUsage();
    }
	if (!strcmp(argv[i], "-svdTest")) {
      R2Image *image = new R2Image();
	  image->svdTest();
	  return 0;
    }
  }

  // Read input and output image filenames
  if (argc < 3)  ShowUsage();
  argv++, argc--; // First argument is program name
  char *input_image_name = *argv; argv++, argc--; 
  char *output_image_name = *argv; argv++, argc--; 

  // Allocate image
  R2Image *image = new R2Image();
  if (!image) {
    fprintf(stderr, "Unable to allocate image\n");
    exit(-1);
  }

  // Read input image
  if (!image->Read(input_image_name)) {
    fprintf(stderr, "Unable to read image from %s\n", input_image_name);
    exit(-1);
  }

  // Initialize sampling method
  int sampling_method = R2_IMAGE_POINT_SAMPLING;

  // Parse arguments and perform operations 
  while (argc > 0) {
    if (!strcmp(*argv, "-brightness")) {
      CheckOption(*argv, argc, 2);
      double factor = atof(argv[1]);
      argv += 2, argc -=2;
      image->Brighten(factor);
    }
	else if (!strcmp(*argv, "-sobelX")) {
      argv++, argc--;
      image->SobelX();
    }
	else if (!strcmp(*argv, "-sobelY")) {
      argv++, argc--;
      image->SobelY();
    }
	else if (!strcmp(*argv, "-log")) {
      argv++, argc--;
      image->LoG();
    }
    else if (!strcmp(*argv, "-saturation")) {
      CheckOption(*argv, argc, 2);
      double factor = atof(argv[1]);
      argv += 2, argc -= 2;
      image->ChangeSaturation(factor);
    }
	else if (!strcmp(*argv, "-harris")) {
      CheckOption(*argv, argc, 2);
      double sigma = atof(argv[1]);
      argv += 2, argc -= 2;
      image->Harris(sigma);
    }
    else if (!strcmp(*argv, "-blur")) {
      CheckOption(*argv, argc, 2);
      double sigma = atof(argv[1]);
      argv += 2, argc -= 2;
      image->Blur(sigma);
    }
    else if (!strcmp(*argv, "-sharpen")) {
      argv++, argc--;
      image->Sharpen();
    }
    else if (!strcmp(*argv, "-matchTranslation")) {
      CheckOption(*argv, argc, 2);
      R2Image *other_image = new R2Image(argv[1]);
      argv += 2, argc -= 2;
      image->blendOtherImageTranslated(other_image);
      delete other_image;
    }
    else if (!strcmp(*argv, "-matchHomography")) {
      CheckOption(*argv, argc, 2);
      R2Image *other_image = new R2Image(argv[1]);
      argv += 2, argc -= 2;
      image->blendOtherImageHomography(other_image);
      delete other_image;
    }
    else {
      // Unrecognized program argument
      fprintf(stderr, "image: invalid option: %s\n", *argv);
      ShowUsage();
    }
  }

  // Write output image
  if (!image->Write(output_image_name)) {
    fprintf(stderr, "Unable to read image from %s\n", output_image_name);
    exit(-1);
  }

  // Delete image
  delete image;

  // Return success
  return EXIT_SUCCESS;
}
コード例 #22
0
ファイル: DF_GPS.cpp プロジェクト: arispujud/Arduino
double DFGPS::getSatellites () {
	double sat = (double)decToInt (gpsp[4], 3);
	return sat + atof (gpsp[4]+3) / 60.0;
}
コード例 #23
0
ファイル: LS_geoloc_driver.c プロジェクト: GEO-IASS/ledaps
int main(int argc, char **argv)
{

float coordinates[8];
double parm[13];
double radius, lat, lon, dl, ds;
double corner[2];
int i, l, s, ret;
int zonecode, sphercode, rows, cols;
float orientationangle, pixelsize, upperleftx, upperlefty;
double arg2, arg3;

int LSsphdz(float coordinates[8], double *parm, double *radius, double corner[2]);
int LSutminv(double s, double l, double *lon, double *lat);
int LSutmfor(double *s, double *l, double lon, double lat);
int get_data(char *filename, int *zonecode, int *sphercode, float *orientationangle, float *pixelsize, 
             float *upperleftx, float *upperlefty, int *rows, int *cols);

if (argc < 4) {
#ifdef INV
   printf("usage: %s <file> <sample> <line>\n", argv[0]);
#else
   printf("usage: %s <file> <longitude> <latitude>\n", argv[0]);
#endif
   printf("Jim Ray, SSAI, %s\n\n", __DATE__);
   exit(0);
   }

if ( (ret = get_data(argv[1], &zonecode, &sphercode, &orientationangle, &pixelsize, 
         &upperleftx, &upperlefty, &rows, &cols)) != 0) {
   printf("Error reading file %s, cannot continue\n", argv[1]);
   exit(1);
      } 

arg2 = atof(argv[2]);
arg3 = atof(argv[3]);

coordinates[4] = (double)zonecode;
coordinates[5] = (double)sphercode;
coordinates[6] = (double)orientationangle;
coordinates[7] = (double)pixelsize;
for(i=0;i<13;i++) parm[i] = 0.0;
corner[0] = (double)upperleftx;
corner[1] = (double)upperlefty;

LSsphdz(coordinates, parm, &radius, corner);


#ifdef INV
ds = arg2;
dl = arg3;

if (ds > (double)cols) {
   printf("Sample argument (%s) exceeds number of columns in file (%d): will use %d\n", 
               argv[2], cols, cols);
   ds = (double)cols;
   }

if (dl > (double)rows) {
   printf("Sample argument (%s) exceeds number of rows in file (%d): will use %d\n", 
               argv[3], rows, rows);
   dl = (double)rows;   
   }

ret = LSutminv(ds, dl, &lon, &lat);
printf("line   %5.1f  samp   %5.1f  => long %f lat %f\n", dl, ds, lon, lat);
#else
lon = arg2;
lat = arg3;

/* We need sanity checks on these as well */

ret = LSutmfor(&ds, &dl, lon, lat);
printf("long %f lat %f => line   %f  samp   %f  \n",  lon, lat, dl, ds);
#endif
}
コード例 #24
0
ファイル: DF_GPS.cpp プロジェクト: arispujud/Arduino
double DFGPS::getHDOP () {
	return atof (gpsp[8]);
}
コード例 #25
0
ファイル: sdma_t.cpp プロジェクト: Fabianx/cstk
 int main(int ac, char *argv[]) {

	if (ac<2) {
		printf("\n  This demo will show how a Sparse Distributed Memory\n");
		printf("  works. The implementation uses the advanced implementation \n");
		printf("  with different distributions.\n");
		printf("  The distributions are relativ and absolute, with linear\n");
		printf("  and gaussian functions (argument's are (1) linear,\n");
		printf("  (2) gaussian and (3) with NAND ditance masurement. After the\n");
		printf("  initialization phase rarely used entries are deleted.\n");
		printf("\n   syntax:");
		printf("\n     %s <df> <a/r> <al> <dl> <mems> <inits> <tests> <thrs> <rem>", argv[0]);
		printf("\n");
		printf("\n    <df> specifies the distribution function:");
		printf("\n		0=linear with Hamming distance,");
		printf("\n		1=gaussian with Hamming distance,");
		printf("\n		2=with NAND distance masurement.");   
		printf("\n    <a/r> absolute(0) or relativ(1) distance masurement.");
		printf("\n    <al> stands for the adress length.");
		printf("\n    <dl> stands for the data length.");
		printf("\n    <mems> specifies the number of address data vector tupels.");
		printf("\n    <inits> indicates the number of initialization vectors");
		printf("\n    <tests> indicates the number of vectors stored in the memory");
		printf("\n    <thres> specifies the threshold value indicates the percentage");
		printf("\n            that the influence goes down with each distance step.");
		printf("\n    <rem> indicates the minimum influence the initialization phase");
		printf("\n          must have had on each memory vector, so it doesn't gets deleted.\n"); 
		printf("\n    try for instance '%s 0 0 40 50 5000 500 6000 0.085 0.0',", argv[0]);
		printf("\n              or try '%s 1 0 40 50 2000 400 2400 0.075 0.0',", argv[0]);
		printf("\n              or try '%s 1 1 40 50 2000 500 2400 0.075 0.0',", argv[0]);
		printf("\n              or try '%s 2 1 40 50 2000 500 2400 0.07 0.0',", argv[0]);
		printf("\n              or try '%s 2 0 40 50 2000 500 2400 0.08 0.0'.", argv[0]);
		printf("\n\n");
		exit(0);
	}
	
	vei_t ADDR_LEN=atoi(argv[3]);
	vei_t DATA_LEN=atoi(argv[4]);
	vei_t MEM_SIZE=atoi(argv[5]);
	vei_t INIT_SIZE=atoi(argv[6]);
	vei_t TEST_SIZE=atoi(argv[7]);
	oas_t THRS=atof(argv[8]);
	oas_t REM=atof(argv[9]);
	ve_t AbsRel=atoi(argv[2]);
	ve_t fct=atoi(argv[1]);
	
	SDMAfct sdma(MEM_SIZE, ADDR_LEN, DATA_LEN);
	sdma.create(MEM_SIZE, ADDR_LEN, DATA_LEN, THRS);
	BinVector v1, v2, b1, b2; 
	KVector hd(MEM_SIZE); // keep all values in the vector
	vei_t d=0;
	
	v1.create(ADDR_LEN);  v2.create(ADDR_LEN);
	b1.create(DATA_LEN);  b2.create(DATA_LEN);
	for (vei_t i=0;i<ADDR_LEN;i++) { v1.set_comp(0,i);  v2.set_comp(0,i); }   
	for (vei_t i=0;i<DATA_LEN;i++) { b1.set_comp(0,i);  b2.set_comp(0,i); }
	v1.set_comp(1,2); v1.set_comp(1,11);  v1.set_comp(1,12); v1.tgl_comp(13); 
	v1.tgl_comp(23); v1.tgl_comp(27);   
	b1.set_comp(1,2); b1.set_comp(1,12); b1.set_comp(1,22); b1.set_comp(1,17);
	
	printf(" Creating %i random vectors as the address space.\n\r", MEM_SIZE);  
	sdma.random_init();  
	
	printf(" Adding %i (random) vectors i for initialization  tempsum = new BVector<oas_t>;n random places.\n\r", INIT_SIZE); 
	int tm;
	tm = clock();
	for (vei_t k=0; k<INIT_SIZE; k++) 
	{  
     		for (vei_t i=0;i<ADDR_LEN;i++) 
           		 v2.set_comp(floor(2.0*rand()/(RAND_MAX+1.0)),i); 
		switch (fct)
		{
			case 0: d = sdma.store(v2, b2, AbsRel); break;
			case 1: d = sdma.store_gauss(v2, b2, AbsRel, DENS_INIT); break;
			case 2: d = sdma.store_nand(v2, b2, AbsRel); break;
		}
		if (k<10) 
		{
			printf(" %i: ",d);
			for (vei_t i=0;i<v2.get_dim();i++) 
			printf("%i",v2.get_comp(i));
			printf("  ");
			printv(&b2);
		} else printf(".");     
  	}
	tm = clock() - tm;
	printf("time during calculation: %i", tm);   
	printf("\n\r");
	
	printf("remove all empty addresses, address space is now %i entries large.", sdma.remove(REM));   
	printf("\n\r");
	
	printf(" Storing v1's data vector, which is:\n\r");
	printv(&b1);
	//sdma.store(v1, b1, AbsRel);
	switch (fct)
	{
		case 0: sdma.store(v1, b1, AbsRel); d = sdma.store(v1, b1, AbsRel); break;
		case 1: sdma.store_gauss(v1, b1, AbsRel, DENS_INIT); d = sdma.store_gauss(v1, b1, AbsRel, DENS); break;
		case 2: sdma.store_nand(v1, b1, AbsRel); d = sdma.store_nand(v1, b1, AbsRel); break;
	}
	printf(" in %i locations on address:\n\r",d);
	printv(&v1);
	
	printf(" Adding %i other (random) vectors i   tempsum = new BVector<oas_t>;n random places.\n\r", TEST_SIZE); 
	tm = clock();
	for (vei_t k=0; k<TEST_SIZE; k++) {  
		for (vei_t i=0;i<ADDR_LEN;i++) 
			v2.set_comp(floor(2.0*rand()/(RAND_MAX+1.0)),i); 
		for (vei_t i=0;i<DATA_LEN;i++) 
			b2.set_comp(floor(2.0*rand()/(RAND_MAX+1.0)),i); 
		switch (fct)
		{
			case 0: d = sdma.store(v2, b2, AbsRel); break;
			case 1: d = sdma.store_gauss(v2, b2, AbsRel, DENS); break;
			case 2: d = sdma.store_nand(v2, b2, AbsRel); break;
		}
		if (k<10) 
		{
			printf(" %i: ",d);
			for (vei_t i=0;i<v2.get_dim();i++) 
			printf("%i",v2.get_comp(i));
			printf("  ");
			printv(&b2);
		} else printf(".");     
	}
	tm = clock() - tm;
	printf("time during calculation: %i", tm);   
	printf("\n\r");
	
	printf(" Adding the winner's counters from retrieval of address.\n\r");
	BVector<s_16b> tsum2(b1.get_dim());
	BVector<oas_t> tsum3(b1.get_dim());
	BinVector sum;
	sum.create(DATA_LEN);
	switch (fct)
	{
		case 0: d = sdma.retrieve(v1,sum,tsum3,AbsRel); break;
		case 1: d = sdma.retrieve_gauss(v1,sum,tsum3,AbsRel,DENS); break;
		case 2: d = sdma.retrieve_nand(v1,sum,tsum3,AbsRel); break;
	}
	//sdm.retrieve(v1, tsum2, c);
	
	//printf("Which sums up to:\n\r");
	//printv2(&tsum2);  printf("\n\r"); 
	
	printf("Which sums up to:\n\r");
	printv3(&tsum3);  printf("\n\r");
	
	printf("And results in:\n\r");
	printv(&sum);
	
	printf("Which should match:\n\r");
	printv(&b1);
	
	printf("\n\rDone.\n\r");
	
	
	return 0;
}
コード例 #26
0
ファイル: DF_GPS.cpp プロジェクト: arispujud/Arduino
double DFGPS::getAltidude () {
	return atof (gpsp[9]);
}
コード例 #27
0
ファイル: ta.c プロジェクト: bapt/heirloom-doctools
void
t_page(int n)	/* do whatever new page functions */
{
	int m, i;
	char buf[1024], *bp;

	pgnum[np++] = n;
	pgadr[np] = ftell(fp);
	if (np > npmax)
		npmax = np;
	if (output == 0) {
		output = in_olist(n);
		t_init(1);
		return;
	}
	/* have just printed something, and seen p<n> for next one */
	putpage();
	fflush(stdout);
	if (nowait)
		return;

  next:
	for (bp = buf; (*bp = readch()); )
		if (*bp++ == '\n' || bp >= &buf[sizeof buf - 1])
			break;
	*bp = 0;
	switch (buf[0]) {
	case 0:
		done();
		break;
	case '\n':
		output = in_olist(n);
		t_init(1);
		return;
	case '!':
		callunix(&buf[1]);
		fputs("!\n", stderr);
		break;
	case 'e':
		erase = 1 - erase;
		break;
	case 'w':
		wflag = 1 - wflag;
		break;
	case 'a':
		aspect = atof(&buf[1]);
		break;
	case '-':
	case 'p':
		m = atoi(&buf[1]) + 1;
		if (fp == stdin) {
			fputs("you can't; it's not a file\n", stderr);
			break;
		}
		if (np - m <= 0) {
			fputs("too far back\n", stderr);
			break;
		}
		np -= m;
		fseek(fp, pgadr[np], 0);
		output = 1;
		t_init(1);
		return;
	case '0': case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
		m = atoi(&buf[0]);
		for (i = 0; i < npmax; i++)
			if (m == pgnum[i])
				break;
		if (i >= npmax || fp == stdin) {
			fputs("you can't\n", stderr);
			break;
		}
		np = i + 1;
		fseek(fp, pgadr[np], 0);
		output = 1;
		t_init(1);
		return;
	case 'o':
		outlist(&buf[1]);
		output = 0;
		t_init(1);
		return;
	case '?':
		fputs("!cmd	unix cmd\n", stderr);
		fputs("p	print this page again\n", stderr);
		fputs("-n	go back n pages\n", stderr);
		fputs("n	print page n (previously printed)\n", stderr);
		fputs("o...	set the -o output list to ...\n", stderr);
		fputs("en	n=0 -> don't erase; n=1 -> erase\n", stderr);
		fputs("an	sets aspect ratio to n\n", stderr);
		break;
	default:
		fputs("?\n", stderr);
		break;
	}
	goto next;
}
コード例 #28
0
ファイル: DF_GPS.cpp プロジェクト: arispujud/Arduino
double DFGPS::getLevel () {
	return atof (gpsp[11]);
}
コード例 #29
0
bool RakNetCommandParser::OnCommand(const char *command, unsigned numParameters, char **parameterList, TransportInterface *transport, SystemAddress systemAddress, const char *originalString)
{
	(void) originalString;
	(void) numParameters;

	if (peer==0)
		return false;

	if (strcmp(command, "Startup")==0)
	{
		SocketDescriptor socketDescriptor((unsigned short)atoi(parameterList[1]), parameterList[3]);
		ReturnResult(peer->Startup((unsigned short)atoi(parameterList[0]), atoi(parameterList[2]), &socketDescriptor, 1), command, transport, systemAddress);
	}
	else if (strcmp(command, "InitializeSecurity")==0)
	{
		peer->InitializeSecurity(0,0,0,0);
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "DisableSecurity")==0)
	{
		peer->DisableSecurity();
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "AddToSecurityExceptionList")==0)
	{
		peer->AddToSecurityExceptionList(parameterList[1]);
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "RemoveFromSecurityExceptionList")==0)
	{
		peer->RemoveFromSecurityExceptionList(parameterList[1]);
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "IsInSecurityExceptionList")==0)
	{
		ReturnResult(peer->IsInSecurityExceptionList(parameterList[1]),command, transport, systemAddress);
	}
	else if (strcmp(command, "SetMaximumIncomingConnections")==0)
	{
		peer->SetMaximumIncomingConnections((unsigned short)atoi(parameterList[0]));
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "GetMaximumIncomingConnections")==0)
	{
		ReturnResult(peer->GetMaximumIncomingConnections(), command, transport, systemAddress);
	}
	else if (strcmp(command, "Connect")==0)
	{
		ReturnResult(peer->Connect(parameterList[0], (unsigned short)atoi(parameterList[1]),parameterList[2],atoi(parameterList[3])), command, transport, systemAddress);
	}
	else if (strcmp(command, "Disconnect")==0)
	{
		peer->Shutdown(atoi(parameterList[0]), (unsigned char)atoi(parameterList[1]));
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "IsActive")==0)
	{
		ReturnResult(peer->IsActive(), command, transport, systemAddress);
	}
	else if (strcmp(command, "GetConnectionList")==0)
	{
		SystemAddress remoteSystems[32];
		unsigned short count=32;
		unsigned i;
		if (peer->GetConnectionList(remoteSystems, &count))
		{
			if (count==0)
			{
				transport->Send(systemAddress, "GetConnectionList() returned no systems connected.\r\n");
			}
			else
			{
				transport->Send(systemAddress, "GetConnectionList() returned:\r\n");
				for (i=0; i < count; i++)
				{
					char str1[64];
					remoteSystems[i].ToString(false, str1);
					transport->Send(systemAddress, "%i %s %i:%i\r\n", i, str1, remoteSystems[i].binaryAddress, remoteSystems[i].port);
				}
			}
		}
		else
			transport->Send(systemAddress, "GetConnectionList() returned false.\r\n");
	}
	else if (strcmp(command, "CloseConnection")==0)
	{
		peer->CloseConnection(IntegersToSystemAddress(atoi(parameterList[0]), atoi(parameterList[1])),atoi(parameterList[2])!=0,(unsigned char)atoi(parameterList[3]));
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "IsConnected")==0)
	{
		ReturnResult(peer->IsConnected(IntegersToSystemAddress(atoi(parameterList[0]), atoi(parameterList[1]))), command, transport, systemAddress);
	}
	else if (strcmp(command, "GetIndexFromSystemAddress")==0)
	{
		ReturnResult(peer->GetIndexFromSystemAddress(IntegersToSystemAddress(atoi(parameterList[0]), atoi(parameterList[1]))), command, transport, systemAddress);
	}
	else if (strcmp(command, "GetSystemAddressFromIndex")==0)
	{
		ReturnResult(peer->GetSystemAddressFromIndex(atoi(parameterList[0])), command, transport, systemAddress);
	}
	else if (strcmp(command, "AddToBanList")==0)
	{
		peer->AddToBanList(parameterList[0], atoi(parameterList[1]));
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "RemoveFromBanList")==0)
	{
		peer->RemoveFromBanList(parameterList[0]);
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "ClearBanList")==0)
	{
		peer->ClearBanList();
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "IsBanned")==0)
	{
		ReturnResult(peer->IsBanned(parameterList[0]), command, transport, systemAddress);
	}
	else if (strcmp(command, "Ping1")==0)
	{
		peer->Ping(IntegersToSystemAddress(atoi(parameterList[0]), atoi(parameterList[1])));
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "Ping2")==0)
	{
		peer->Ping(parameterList[0], (unsigned short) atoi(parameterList[1]), atoi(parameterList[2])!=0);
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "GetAveragePing")==0)
	{
		ReturnResult(peer->GetAveragePing(IntegersToSystemAddress(atoi(parameterList[0]), atoi(parameterList[1]))), command, transport, systemAddress);
	}
	else if (strcmp(command, "GetLastPing")==0)
	{
		ReturnResult(peer->GetLastPing(IntegersToSystemAddress(atoi(parameterList[0]), atoi(parameterList[1]))), command, transport, systemAddress);
	}
	else if (strcmp(command, "GetLowestPing")==0)
	{
		ReturnResult(peer->GetLowestPing(IntegersToSystemAddress(atoi(parameterList[0]), atoi(parameterList[1]))), command, transport, systemAddress);
	}
	else if (strcmp(command, "SetOccasionalPing")==0)
	{
		peer->SetOccasionalPing(atoi(parameterList[0])!=0);
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "SetOfflinePingResponse")==0)
	{
		peer->SetOfflinePingResponse(parameterList[0], atoi(parameterList[1]));
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "GetInternalID")==0)
	{
		ReturnResult(peer->GetInternalID(), command, transport, systemAddress);
	}
	else if (strcmp(command, "GetExternalID")==0)
	{
		ReturnResult(peer->GetExternalID(IntegersToSystemAddress(atoi(parameterList[0]), atoi(parameterList[1]))), command, transport, systemAddress);
	}
	else if (strcmp(command, "SetTimeoutTime")==0)
	{
		peer->SetTimeoutTime(atoi(parameterList[0]), IntegersToSystemAddress(atoi(parameterList[0]), atoi(parameterList[1])));
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "SetMTUSize")==0)
	{
		ReturnResult(peer->SetMTUSize(atoi(parameterList[0]), UNASSIGNED_SYSTEM_ADDRESS), command, transport, systemAddress);
	}
	else if (strcmp(command, "GetMTUSize")==0)
	{
		ReturnResult(peer->GetMTUSize(UNASSIGNED_SYSTEM_ADDRESS), command, transport, systemAddress);
	}
	else if (strcmp(command, "GetNumberOfAddresses")==0)
	{
		ReturnResult((int)peer->GetNumberOfAddresses(), command, transport, systemAddress);
	}
	else if (strcmp(command, "GetLocalIP")==0)
	{
		ReturnResult((char*) peer->GetLocalIP(atoi(parameterList[0])), command, transport, systemAddress);
	}
	else if (strcmp(command, "AllowConnectionResponseIPMigration")==0)
	{
		peer->AllowConnectionResponseIPMigration(atoi(parameterList[0])!=0);
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "AdvertiseSystem")==0)
	{
		peer->AdvertiseSystem(parameterList[0], (unsigned short) atoi(parameterList[1]),parameterList[2],atoi(parameterList[3]));
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "ApplyNetworkSimulator")==0)
	{
		peer->ApplyNetworkSimulator(atof(parameterList[0]), (unsigned short) atoi(parameterList[1]),(unsigned short) atoi(parameterList[2]));
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "IsNetworkSimulatorActive")==0)
	{
		ReturnResult(peer->IsNetworkSimulatorActive(), command, transport, systemAddress);
	}
	else if (strcmp(command, "SetIncomingPassword")==0)
	{
		peer->SetIncomingPassword(parameterList[0], atoi(parameterList[1]));
		ReturnResult(command, transport, systemAddress);
	}
	else if (strcmp(command, "GetIncomingPassword")==0)
	{
		char password[256];
		int passwordLength;
		peer->GetIncomingPassword(password, &passwordLength);
		if (passwordLength)
			ReturnResult((char*)password, command, transport, systemAddress);
		else
			ReturnResult(0, command, transport, systemAddress);
	}

	return true;
}
コード例 #30
0
ファイル: mapcontour.c プロジェクト: aeichner/mapserver
static int msContourLayerGenerateContour(layerObj *layer)
{
  OGRSFDriverH hDriver;
  OGRFieldDefnH hFld;
  OGRLayerH hLayer;
  const char *elevItem;
  char *option;
  double interval = 1.0, levels[1000];
  int levelCount = 0;
  GDALRasterBandH hBand = NULL;
  CPLErr eErr;

  contourLayerInfo *clinfo = (contourLayerInfo *) layer->layerinfo;

  OGRRegisterAll();

  if (clinfo == NULL) {
    msSetError(MS_MISCERR, "Assertion failed: Contour layer not opened!!!",
               "msContourLayerCreateOGRDataSource()");
    return MS_FAILURE;
  }

  hBand = GDALGetRasterBand(clinfo->hDS, 1);
  if (hBand == NULL)
  {
    msSetError(MS_IMGERR,
               "Band %d does not exist on dataset.",
               "msContourLayerGenerateContour()", 1);
    return MS_FAILURE;
  }

  /* Create the OGR DataSource */
  hDriver = OGRGetDriverByName("Memory");
  if (hDriver == NULL) {
    msSetError(MS_OGRERR,
               "Unable to get OGR driver 'Memory'.",
               "msContourLayerCreateOGRDataSource()");
    return MS_FAILURE;
  }

  clinfo->hOGRDS = OGR_Dr_CreateDataSource(hDriver, NULL, NULL);
  if (clinfo->hOGRDS == NULL) {
    msSetError(MS_OGRERR,
               "Unable to create OGR DataSource.",
               "msContourLayerCreateOGRDataSource()");
    return MS_FAILURE;
  }

  hLayer = OGR_DS_CreateLayer(clinfo->hOGRDS, clinfo->ogrLayer.name, NULL,
                              wkbLineString, NULL );

  hFld = OGR_Fld_Create("ID", OFTInteger);
  OGR_Fld_SetWidth(hFld, 8);
  OGR_L_CreateField(hLayer, hFld, FALSE);
  OGR_Fld_Destroy(hFld);

  /* Check if we have a coutour item specified */
  elevItem = CSLFetchNameValue(layer->processing,"CONTOUR_ITEM");
  if (elevItem && strlen(elevItem) > 0) {
    hFld = OGR_Fld_Create(elevItem, OFTReal);
    OGR_Fld_SetWidth(hFld, 12);
    OGR_Fld_SetPrecision(hFld, 3);
    OGR_L_CreateField(hLayer, hFld, FALSE);
    OGR_Fld_Destroy(hFld);
  }
  else {
    elevItem = NULL;
  }

  option = msContourGetOption(layer, "CONTOUR_INTERVAL");
  if (option) {
    interval = atof(option);
    free(option);
  }

  option = msContourGetOption(layer, "CONTOUR_LEVELS");
  if (option) {
    int i,c;
    char **levelsTmp;
    levelsTmp = CSLTokenizeStringComplex(option, ",", FALSE, FALSE);
    c = CSLCount(levelsTmp);
    for (i=0;i<c && i<(int)(sizeof(levels)/sizeof(double)) ;++i)
      levels[levelCount++] = atof(levelsTmp[i]);

    CSLDestroy(levelsTmp);
    free(option);
  }
    
  eErr = GDALContourGenerate( hBand, interval, 0.0,
                              levelCount, levels,
                              FALSE, 0.0, hLayer,
                              OGR_FD_GetFieldIndex(OGR_L_GetLayerDefn( hLayer),
                                                    "ID" ),
                              (elevItem == NULL) ? -1 :
                              OGR_FD_GetFieldIndex(OGR_L_GetLayerDefn( hLayer), 
                                                    elevItem ),
                              NULL, NULL );

  msConnPoolRegister(&clinfo->ogrLayer, clinfo->hOGRDS, msContourOGRCloseConnection);

  return MS_SUCCESS;

}