int main(int argc, char  *argv[]) {
	
	int status;
	printf(".:: Starting Simple UDP Host Discover Server - Cliente ::.\n\n");
	
	status = processArguments(argc, argv);
	
	if(status != 0) {
		fprintf(stderr,"Error al procesar el argumento %i\n",status);
		return -1;
	}
	
	switch(mode) {
		case SERVER:
			startServer(listenIP, listenPort);
			break;
		case CLIENT:
			if(strcmp(listenIP,"0.0.0.0")==0) {
				printHelp(argv[0],true,"En modo cliente es necesario especificar la IP con -i");
			}
			startClient(listenIP,listenPort);
			break;
		case NOT_DEFINE:
			printHelp(argv[0],true,"Es necesario indicar el modo de operación\n");
			break;
	}
	
	return 0;
}
/**
 * Main program to execute the decrypt functionality using a provided cipher
 * text and plain text dictionary.
 *
 * @param argc - count of arguments
 * @param argv - array of c-style strings
 * @return
 */
int main(int argc, char **argv) {

	// process optional command line arguments
	processArguments(argc, argv);

	std::cout << "hello authorize";
}
Exemple #3
0
int doRunMode(int argc, char** argv )
{
  if( !processArguments(argc, argv) ) return 1;

  signal(SIGINT, term);
  signal(SIGABRT, term);
  signal(SIGTERM, term);

  server.setCommandLine(ATRUN::m_server);
  server.setWorkingDirectory(ATRUN::m_serverDir);
  server.create();

  client.setCommandLine(ATRUN::m_client);
  client.setWorkingDirectory(ATRUN::m_clientDir);
  if(ATRUN::m_outfile.size())
  {
    client.setOutFile(ATRUN::m_outfile);
    client.sendToFile(true);
  }
  else
    client.sendToStd(true);

  client.create();

  client.waitFor();
  server.terminate();

  return client.getExitCode();
}
Exemple #4
0
static void
parseCommandLine(xmlrpc_env *         const envP,
                 int                  const argc,
                 const char **        const argv,
                 struct cmdlineInfo * const cmdlineP) {

    cmdlineParser const cp = cmd_createOptionParser();

    const char * error;

    cmd_defineOption(cp, "transport", OPTTYPE_STRING);
    cmd_defineOption(cp, "username",  OPTTYPE_STRING);
    cmd_defineOption(cp, "password",  OPTTYPE_STRING);

    cmd_processOptions(cp, argc, argv, &error);

    if (error) {
        setError(envP, "Command syntax error.  %s", error);
        strfree(error);
    } else {
        cmdlineP->username  = cmd_getOptionValueString(cp, "username");
        cmdlineP->password  = cmd_getOptionValueString(cp, "password");

        if (cmdlineP->username && !cmdlineP->password)
            setError(envP, "When you specify -username, you must also "
                     "specify -password.");
        else {
            cmdlineP->transport = cmd_getOptionValueString(cp, "transport");
            
            processArguments(envP, cp, cmdlineP);
        }
    }
    cmd_destroyOptionParser(cp);
}
Exemple #5
0
int main(int argc, char **argv)
{
    Arguments *args;
    Rule *rules;
    int rules_number;
    int i;
    
    srand(time(NULL));
    args = processArguments(argc, argv);
    if(args->mode == 0)
    {
        rules = processRuleFile(args);
        for(i=0;i<args->name_number;i++)
        {
            if(args->name_length<1)
                generateName(args->output_file, rules, 3+rand()%6);
            else
                generateName(args->output_file, rules, args->name_length);
        }
    }
    else if(args->mode == 1)
    {
        rules = generateRules(args, &rules_number);
        writeRules(rules, rules_number, args->output_file);
    }
    fclose(args->output_file);
    return 0;
}
Exemple #6
0
lcpp::Ptr<lcpp::LispObject>
lcpp::LispFunction_UserDefined::call(Ptr<LispObject> pArgList)
{
    EZ_ASSERT(m_pBody, "The function body MUST be valid!");
    RecursionCounter counter(LispRuntime::instance());

    auto pEnv = LispEnvironment::create(m_pName, m_pParentEnv);

    // Process args
    //////////////////////////////////////////////////////////////////////////
    processArguments(pEnv, pArgList);

    // Process body
    //////////////////////////////////////////////////////////////////////////
    Ptr<LispObject> pCodePointer = m_pBody;
    Ptr<LispObject> pResult = LCPP_NIL;

    while(!isNil(pCodePointer))
    {
        EZ_ASSERT(pCodePointer->is<LispCons>(), "Function body must be a cons.");

        auto pCons = pCodePointer.cast<LispCons>();
        pResult = LispRuntime::instance()->evaluator()->evalulate(pEnv, pCons->car());
        pCodePointer = pCons->cdr();
    }

    return pResult;
}
Exemple #7
0
int main(int argc, char *argv[])
{
    QLoggingCategory::setFilterRules(QStringLiteral("*.debug=false"));

    QCoreApplication::setOrganizationName(QStringLiteral("QtProject"));
    QCoreApplication::setOrganizationDomain(QStringLiteral("qt-project.org"));
    QCoreApplication::setApplicationName(QStringLiteral("ClangBackend"));
    QCoreApplication::setApplicationVersion(QStringLiteral("1.0.0"));

    QCoreApplication application(argc, argv);

    const QString connection =  processArguments(application);

    ClangBackEnd::Messages::registerMessages();

    clang_toggleCrashRecovery(true);
    clang_enableStackTraces();

    ClangBackEnd::ClangIpcServer clangIpcServer;
    ClangBackEnd::ConnectionServer connectionServer(connection);
    connectionServer.start();
    connectionServer.setIpcServer(&clangIpcServer);

    return application.exec();
}
int main(int argc, char *argv[]) {

printf(".:: FILE TRANSFER SERVER ::.\n");
if(!processArguments(argc, argv)) return -1;

start_server(port,baseDir);
}
Exemple #9
0
void Launcher::prepareSettings() {
#ifdef Q_OS_MAC
#ifndef OS_MAC_OLD
	if (QSysInfo::macVersion() >= QSysInfo::MV_10_11) {
		gIsElCapitan = true;
	}
#else // OS_MAC_OLD
	if (QSysInfo::macVersion() < QSysInfo::MV_10_7) {
		gIsSnowLeopard = true;
	}
#endif // OS_MAC_OLD
#endif // Q_OS_MAC

	switch (cPlatform()) {
	case dbipWindows:
#ifndef OS_WIN_STORE
		gPlatformString = qsl("Windows");
#else // OS_WIN_STORE
		gPlatformString = qsl("WinStore");
#endif // OS_WIN_STORE
	break;
	case dbipMac:
#ifndef OS_MAC_STORE
		gPlatformString = qsl("MacOS");
#else // OS_MAC_STORE
		gPlatformString = qsl("MacAppStore");
#endif // OS_MAC_STORE
	break;
	case dbipMacOld:
		gPlatformString = qsl("MacOSold");
	break;
	case dbipLinux64:
		gPlatformString = qsl("Linux64bit");
	break;
	case dbipLinux32:
		gPlatformString = qsl("Linux32bit");
	break;
	}

	auto path = Platform::CurrentExecutablePath(_argc, _argv);
	LOG(("Executable path before check: %1").arg(path));
	if (!path.isEmpty()) {
		auto info = QFileInfo(path);
		if (info.isSymLink()) {
			info = info.symLinkTarget();
		}
		if (info.exists()) {
			const auto dir = info.absoluteDir().absolutePath();
			gExeDir = (dir.endsWith('/') ? dir : (dir + '/'));
			gExeName = info.fileName();
		}
	}
	if (cExeName().isEmpty()) {
		LOG(("WARNING: Could not compute executable path, some features will be disabled."));
	}

	processArguments();
}
int MatchingApplication::match() {
    try{
        addOptions();
        processArguments();
        initConfiguration();

        // Cleaning
        if(w_)
            delete w_;
        if(g1_)
            delete g1_;
        if(g2_)
            delete g2_;
        if(gl1_)
            delete gl1_;
        if(gl2_)
            delete gl2_;
        w_ = 0;
        g1_ = g2_ = 0;
        gl1_ = gl2_ = 0;

        // Check number of arguments
        QStringList args = positionalArguments();
        if(args.size() != 2)
            Exception(QString("You must provide exactly two %1 (%2 given)").arg(isMultiMatching_?"directories":"graphs").arg(args.size()));

        // Loading weights and graphs
        w_ = new Weights(cfg_->substitution, cfg_->creation);
        if(isMultiMatching_) {
            gl1_ = new GraphList(QDir(args.at(0)), cfg_->ext);
            gl2_ = (args.at(0).compare(args.at(1)) == 0)? gl1_ : new GraphList(QDir(args.at(1)), cfg_->ext);
        } else {
            g1_ = new Graph(args.at(0));
            g2_ = new Graph(args.at(1));
        }
        initMatrix();
        QThreadPool::globalInstance()->setMaxThreadCount(cfg_->parallelInstances);

        // Running the matching(s)
        if(isMultiMatching_) {
            for(auto i : *gl1_)
                for(auto j : *gl2_)
                    if((gl1_ != gl2_) || (j->getIndex() > i->getIndex()))
                        queue_.enqueue(qMakePair(i,j));
        } else {
            queue_.enqueue(qMakePair(g1_, g2_));
        }
        populate();

        return exec();
    } catch(std::exception &e) {
        error(e);
    }
    return EXIT_FAILURE;
}
Exemple #11
0
int start(int argc, char *argv[]) {
	
	printf(".:: TCP PING ::.\n");
	if(!processArguments(argc, argv)) return -1;
	
	if(mode == SERVER) {
		start_server(CONFIG_LISENT_IFACE, port, CONFIG_MAX_CLIENT);
	} else if(mode == CLIENT) {
		start_client(ip_dst,port,msg_count,msg_size);
	}
	
	return 0;
}
Exemple #12
0
Value *ValueProcessor::processFunction(const Token &function,
                                       TokenList::const_iterator &i,
                                       TokenList::const_iterator &end,
                                       const ValueScope &scope) const {
  // Use a temporary iterator so we don't disturb <code>i</code> if
  // processing fails
  TokenList::const_iterator i2 = i;

  vector<const Value *> arguments;

  const FuncInfo *fi;
  Value *ret = NULL;
  vector<const Value *>::iterator it;
  string arg_str;
  
  std::ostringstream fnc_str;
  
  fi = functionLibrary.getFunction(function.c_str());

  if (fi == NULL)
    return NULL;

  if (processArguments(i2, end, scope, arguments)) {
    
    if (!functionLibrary.checkArguments(fi, arguments)) {
      fnc_str << function << "(";
      for (it = arguments.begin(); it != arguments.end(); it++) {
        if (it != arguments.begin())
          fnc_str << ", ";
        fnc_str << (*it)->getTokens()->toString() << "(" <<
          (*it)->typeToString((*it)->type) << ")";
      }
      fnc_str << ")";
      throw new ParseException(fnc_str.str(),
                               functionLibrary.functionDefToString(function.c_str(), fi),
                               function.line, function.column, function.source);
    }
    ret = fi->func(arguments);
    ret->setLocation(function);
    // advance the iterator
    i = i2;
  } else
    ret = NULL;

  // delete arguments
  for (it = arguments.begin(); it != arguments.end(); it++) {
    delete (*it);
  }

  return ret;
}
bool
SimInterior::onAdd()
{
   if (Parent::onAdd() == false)
      return false;

   set(renderImage.transform, true);

   if (m_pFilename) {
      const char* pFilename = m_pFilename;
      m_pFilename = NULL;
      processArguments(1, (const char**)&pFilename);
      setState(m_currentState);
   }
   updateBoundingBox();

   return true;
}
/* init rendering variables */
void init_rendering(int argc, char** argv) {

	// init window size
	processArguments(argc, argv);

	// init GLUT and create window
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(screenWidth, screenHeight);
	glutCreateWindow("Cubie-boids");

	/* init lighting */
	init_lighting();

	// register callback functions
	register_callbacks();

}
Exemple #15
0
int main(int argc, char *argv[]) {
  // On Mac, the first printf does an InstallConsole which sets AE handlers
  // so init os first to clear SIOUXSettings.standalone to fix this
  OS::init();
  OS::set_args(argc, argv);

  /* Do not buffer stdin. If stdin is buffered, input will disappear at the
     Self level. The reason is that the VM will use fread(stdin, ...) which 
     does a read-ahead on the descriptor for stdin (0). Self, however, reads 
     directly from the descriptor, so any characters that were read ahead 
     in the fread(stdin, ...) call will not show up at the Self level. */

  OS::do_not_buffer(stdin);

  /* Set the maximum core size to be large, so that core dumps are produced
     when Self crashes.  (Under Mac OS X, the default core size is 0, so
     core dumps weren't produced. -mabdelmalek 4/28/03 */
  OS::enable_core_dumps();

  processArguments(argc, (const char **)argv);
  
  TrackCHeapInMonitor::reset();
  init_globals();
  set_flags_for_platform();
  bootstrapping = false; 

# ifdef DYNLINK_SUPPORTED
    initDynLinker(argc, (const char **)argv);
# endif

  if (spyLogFile) TheSpy->activate(spyLogFile);

# ifdef EXPERIMENT_WITH_APPLE_EVENTS
  extern void handle_dropped_snapshot();
  handle_dropped_snapshot();
# endif  
  
  vmProcess = new Process(NULL, SelfStackLimit);
  processes->startVMProcess();
  ShouldNotReachHere();
  return 0;
}
void Interpreter::execute(const std::string& line)
{
    const auto separator = line.find(':');
    if (separator != std::string::npos)
    {
        const auto cmdName = line.substr(0, separator);
        const auto cmd = _commands.find(cmdName);
        if (cmd != _commands.end())
        {
            cmd->second->execute(processArguments(line.substr(separator + 1)), _ctx);
        }
        else
        {
            throw "Command not found";
        }
    }
    else
    {
        throw "Malformed command line.";
    }
}
Exemple #17
0
int XConf::readParams( int argc, char** argv ) {
  init();
  if (argc<2) return 1;
  int i=0;
  while (i<argc-1) {
    i++;
    xstring key = argv[i];
    key = key.toLowerCase();
    std::map<xstring, int>::const_iterator it = arguments_defs.find( key ); 
    if (it == arguments_defs.end()) continue;
    std::vector<xstring> strs;

    std::map< xstring, std::vector<xstring> >::iterator in_it = arguments.find( key ); 
    if ( in_it == arguments.end() ) {
      arguments.insert( make_pair( key, strs ) );
      in_it = arguments.find( key ); 
    }

    int n = (*it).second;
    if (n < 0) {
      i++;
      if (argc-i < 1) break;
      strs = scan_strings( argv[i] );
    } else
    for (int p=0; p<n; p++) {
      i++;
      if (argc-i < 1) break;
      strs.push_back( argv[i] );
    }

    for (int x=0; x<strs.size(); x++)  
      in_it->second.push_back( strs[x] );

  } // while (i<argc-1)

  processArguments();
  cureParams();
  return 0;
}
int main( int argc, char *argv[] ) {
    int numInputs;
    Layer *hiddenLayer, *outputLayer;
    TestCase testCase;
    int i;

    initRand();

    if( !processArguments( argc, argv ) ) {
        fprintf( stderr, "Usage: main [-r, -t] [node definition file] [input file, training file]\n" );
        exit( EXIT_FAILURE );
    }

    numInputs = buildLayers( &hiddenLayer, &outputLayer );
    if( !numInputs ) {
        exit( EXIT_FAILURE );
    }

    getDefaultTestCase( numInputs, outputLayer->numNodes, &testCase );

    if( trainingFlag ) {
        for( i = 0; i < 1000; ++i ) {
            populateNextTestCase( &testCase );
            train( &testCase, hiddenLayer, outputLayer );
        }

        if( !persistWeights( numInputs, hiddenLayer, outputLayer ) ) {
            exit( EXIT_FAILURE );
        }
    } else {
        while( populateNextTestCase( &testCase ) == NEW_INPUT ) {
            forwardPropagate( testCase.inputs, hiddenLayer, outputLayer );
            printTestResults( testCase.inputs, outputLayer, testCase.desiredOutputs );
        }
    }

    exit( EXIT_SUCCESS );
}
int main( int argc, char* argv[] ) {
    processArguments( argc, argv );

    // open connection to X server
    Display* display; /* pointer to X display */
#ifdef DEBUG
    printf("%-50s", "connect to X-server...");
#endif
    display = XOpenDisplay( getenv( "DISPLAY" ) );
    if( display == NULL ) {
        fprintf( stderr, "\nCannot connect to X server '%s'\n", getenv( "DISPLAY" ) );
        exit( 1 );
    }
#ifdef DEBUG
    printf( "[ok]\n" );
#endif

#ifdef DEBUG
    printf( "%-50s", "creating undecorated window..." );
#endif
    Window w = createUndecoratedWindow( display );
#ifdef DEBUG
    printf( "[ok]\n" );
#endif

#ifdef DEBUG
    printf( "%-50s", "registering for input events..." );
#endif
    XSelectInput( display, w, PointerMotionMask );
#ifdef DEBUG
    printf( "[ok]\n" );
#endif

#ifdef DEBUG
    printf( "now entering event loop (infinite); ctrl-c to abort.\n" );
#endif
    XEvent e;
    for (;;) {
        // non-busy blocking wait if eventqueue is empty.
        // we only get events if the mouse enters the window!
        XNextEvent( display, &e );

        if( e.type == MotionNotify ) {
            int x = e.xmotion.x; /* x mouse coordinate */
            int y = e.xmotion.y; /* y mouse coordinate */
            int dx = 0, dy = 0;

            if( mode == 0 )
            {
                // these are used to determine closest edge
                int ldist = x;
                int rdist = void_width - x;
                int tdist = y;
                int bdist = void_height - y;

                // determine action required
                // First, handle special cases where mouse is near screen edge
                if( ((x == 0) && (void_x == 0)) || ((x + void_x) >= (screen_width - 1)) )
                {   // void is aligned with vertical screen edge and mouse is at vertical screen edge
                    if( tdist < bdist )
                        dy = -y - 1;
                    else
                        dy = void_height - y;
                }
                else if( ((y == 0) && (void_y == 0)) || ((y + void_y) >= (screen_height - 1)) )
                {   // void is aligned with horizontal screen edge and mouse is at horizontal screen edge
                    if( ldist < rdist )
                        dx = -x - 1;
                    else
                        dx = void_width - x;
                }
                // now, handle normal cases
                else if( ldist < rdist ) {
                    if( ldist < tdist ) {
                        if( ldist < bdist )
                            dx = -x - 1;
                        else
                            dy = void_height - y;
                    } else {
                        if( tdist < bdist )
                            dy = -y - 1;
                        else
                            dy = void_height - y;
                    }
                } else {
                    if( rdist < tdist ) {
                        if( rdist < bdist )
                            dx = void_width - x;
                        else
                            dy = void_height - y;
                    } else {
                        if( tdist < bdist )
                            dy = -y - 1;
                        else
                            dy = void_height - y;
                    }
                }
            }
            else
            {
                switch (mode) {
                case 'd':
                    dy = void_height - y;
                    break;

                case 'u':
                    dy = -y - 1;
                    break;

                case 'l':
                    dx = -x - 1;
                    break;

                case 'r':
                    dx = void_width - x;
                    break;

                default:
                    printf( "Unknown mode: %d\n", mode );
                    exit( 1 );
                    break;
                }
            }

#ifdef DEBUG
            printf( "mouse @ %4d %4d warpby %4d %4d\n", x, y, dx, dy );
#endif
            XWarpPointer( display, None, None, 0, 0, 0, 0, dx, dy );
        }
    }

    XCloseDisplay( display );
    return 0;
}
Exemple #20
0
int main (int argc, char ** argv) {
  long seqNum, i, k  = 0;
 
  char * * sequences = NULL;
  long * seqLen = NULL;
  char * * * algnseq = NULL;
  long * aSeqLen = NULL;
  int alignmentsNo=0;
  MOA_rec * msaAlgn = NULL;
 
  int stype = 0;
  long currentScore, currentCell = 0;
  long prevScore, prevCell = 0;
  Mode = Sequential;
  processArguments(argc, argv, &seqNum, &sequences, &seqLen, &stype);
  prevNow = NULL;
  prevNow = (struct tm *) mmalloc (sizeof(struct tm));
  currNow = getTime();
  prevNow->tm_hour = currNow->tm_hour;
  prevNow->tm_isdst = currNow->tm_isdst;
  prevNow->tm_mday = currNow->tm_mday;
  prevNow->tm_min = currNow->tm_min;
  prevNow->tm_mon = currNow->tm_mon;
  prevNow->tm_sec = currNow->tm_sec;
  prevNow->tm_wday = currNow->tm_wday;
  prevNow->tm_yday = currNow->tm_yday;
  prevNow->tm_year = currNow->tm_year;
    

  
  /* A. Crteate MOA Alignment Tensor */
  /*msaAlgn = (MOA_rec *) mmalloc(sizeof(MOA_rec));*/
  createMOAStruct (&msaAlgn);
  
  createMOA(seqLen /* shape*/, seqNum /* dimension*/, msaAlgn /* MOA structure*/,0,0);
  if (pdebug == 1)
    mprintf(outputfilename, "MOA dimn %d, elm ub %d\n", 2, msaAlgn->dimn, msaAlgn->elements_ub); 
  /* B. Fill the Tensor */
 
  if (AlignmentType == Global) 
    initTensor (msaAlgn, stype);
  fillTensor (sequences, msaAlgn, stype);
  if (pdebug == 1) 
    printMOA(msaAlgn);

  /* C. trace back */
  aSeqLen = (long *)   mmalloc (sizeof(long));
  aSeqLen[0] = 0;
  prevCell = -1;
  algnseq = (char * * *) mmalloc(sizeof(char * *));
  algnseq[0] = (char * *) mmalloc (seqNum * sizeof(char *));    
  if (AlignmentType == Global) { /* if Global Alignment */
    /*PrintPrevChains(msaAlgn);
    // Get Max Cell on Last Border as Current Cell */
    alignmentsNo = 0;
    currentScore = getMaxOnLastBorder (msaAlgn, &currentCell);
    traceBack (seqNum, sequences, seqLen, msaAlgn, stype, &algnseq, &aSeqLen, &alignmentsNo, &currentCell, &currentScore, 0);
  }
  else { /* if Local Alignment */
    alignmentsNo = -1;
    for (k = 0;k<maxAlignmentsNumber;k++) {
      if (k == 0)
	currentScore = MOA_max(msaAlgn, 0, 0, &currentCell);
      else {
	currentScore = MOA_max(msaAlgn, 1, currentScore, &currentCell);
      }
      if ((prevCell != currentCell) && (currentScore > 0)){
	alignmentsNo ++;
	algnseq = (char * * *) realloc (algnseq, (alignmentsNo + 1) * sizeof(char * *));
     if (algnseq == NULL) {
		mprintf(outputfilename, "Could not reallocate memory for Aligned Sequence Set %d!\n", 1, alignmentsNo + 1);
		return -1;
      }
	algnseq[alignmentsNo] = (char * *) mmalloc (seqNum * sizeof(char *));
	aSeqLen = (long *)  realloc (aSeqLen, (alignmentsNo + 1) * sizeof(long));
     if (aSeqLen == NULL) {
		mprintf(outputfilename, "Could not reallocate memory for Aligned Sequence Length %d!\n", 1, alignmentsNo + 1);
		return -1;
      }
	traceBack_loc (seqNum, sequences, seqLen, msaAlgn, stype, &algnseq, &aSeqLen, &alignmentsNo, &currentCell, &currentScore, 0);
	}
	prevCell = currentCell;
	prevScore = currentScore;
    }
  }

  /* D. Print the resulting Alignemnts */
  PrintASeq (seqNum, sequences, seqLen, &algnseq, aSeqLen, alignmentsNo+1) ;

  /* Free all Memory Allocations & Exit. */
  deleteMOA (msaAlgn);
  if (sequences != NULL) {
    for (i=0;i<seqNum;i++) {
      if (sequences[i] != NULL) 
        free(sequences[i]);
	}
    free(sequences);
  }
  if (algnseq != NULL) {
    for (k=0;k<=alignmentsNo;k++) {
	  if (algnseq[k] != NULL) {
        for (i=0;i<seqNum;i++) {
          if (algnseq[k][i] != NULL)
	        free(algnseq[k][i]);
        }
        free(algnseq[k]);
	  }
    }
    free(algnseq);
  }
  if (seqLen != NULL)
    free(seqLen);
  if (aSeqLen != NULL)
    free(aSeqLen);
  if (prevNow != NULL)
    free(prevNow);

  return 0;

}
Exemple #21
0
int main (int argc, char** argv)
{
	// for storing results of argument processing
	// general
	bool displayInfo = true;
	char* inFileName = "";

	// threshold filter
	bool runThreshold = false;
	float threshold = THRESH_ERROR;

	// crop
	bool runCrop = false;
	int cropWidth = CROP_DIM_ERROR;
	int cropHeight = CROP_DIM_ERROR;
	int cropStart[] = {0,0};

	// resize
	bool runResize = false;
	float scaling = SCALING_ERROR;
	char* resType = "";

	// default output file name
	char* outFileName = "out.bmp";
	
	// process arguments, checking for errors
	if (processArguments(argc, argv, &runThreshold, &runCrop, &runResize, 
		&displayInfo, &inFileName, &outFileName, &threshold, &cropWidth, 
		&cropHeight, cropStart, &scaling, &resType) != EXIT_SUCCESS)
	{
		fprintf(stderr, "Unable to process arguments.\n");
		return EXIT_FAILURE;
	}

	// open the file
	FILE *inFile = fopen(inFileName, "r");

	// check that file opened okay
	if (inFile == NULL)
	{
		fprintf(stderr, "Unable to open file: %s\n", inFileName);
		return EXIT_FAILURE;
	}

	// read in the file header and check that it went okay
	struct bmpFileHeader *fileHead = getFileHeader(inFile);

	if (fileHead == NULL)
	{
		fprintf(stderr, "Unable to set up file header.\n");
		return EXIT_FAILURE;
	}

	struct bmpInfoHeader *infoHead = getInfoHeader(inFile);

	if (infoHead == NULL)
	{
		fprintf(stderr, "Unable to set up info header.\n");
		return EXIT_FAILURE;
	}

	// check the format of the file
	if (formatCheck(fileHead, infoHead) != EXIT_SUCCESS)
	{
		fprintf(stderr, "Program cannot handle this format.\n");
		return EXIT_FAILURE;
	}


	// if we're displaying info, do so
	if (displayInfo)
	{
		// print out header information
		printInfo(fileHead, infoHead);
	}

	// move file pointer on to start of image, if necessary
	if (fileHead->offset != (sizeof(struct bmpFileHeader) + 
		sizeof(struct bmpInfoHeader)))
	{
		fseek(inFile, 
			((int)fileHead->offset - (sizeof(struct bmpFileHeader) + 
				sizeof(struct bmpInfoHeader))), SEEK_CUR);
	}

	// if we're running a threshold filter, do so
	if (runThreshold)
	{
		// apply threshold filter to image, checking for errors
		if (applyThreshold(inFile, fileHead, infoHead, outFileName, threshold) 
			== EXIT_FAILURE)
		{
			fprintf(stderr, "Unable to apply threshold.\n");
			return EXIT_FAILURE;
		}
	}

	// if we're cropping the image, do so
	if (runCrop)
	{
		// crop the image, checking for errors
		if (cropImage(inFile, fileHead, infoHead, outFileName, cropWidth,
			cropHeight, cropStart) == EXIT_FAILURE)
		{
			fprintf(stderr, "Unable to crop image.\n");
			return EXIT_FAILURE;
		}
	}

	// if we're resizing the image do so
	if (runResize)
	{
		// resize image checking for errors
		if (resizeImage(inFile, fileHead, infoHead, outFileName, scaling, resType) 
			== EXIT_FAILURE)
		{
			fprintf(stderr, "Unable to resize image.\n");
			return EXIT_FAILURE;
		}
	}

	// free up allocated memory
	free(infoHead);
	free(fileHead);

	// close input file, checking for errors
	if (fclose(inFile) != 0)
	{
		fprintf(stderr, "Unable to close input file.\n");
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
int main(int argc, char *argv[]) {	
	printf(".--FILE TRANSFER CLIENT --.\n");
	if(!processArguments(argc, argv)) return -1;
	start_client(port,ip,remoteFilename,localFilename);
}
Exemple #23
0
void 
QLuaApplication::Private::stateChanged(int state)
{
  // safeguard
  if (closingDown || !theEngine)
    return;
  // timing
  if (state == QtLuaEngine::Running)
    {
      if (ttyPauseReceived)
        {
          ttyPauseReceived = false;
          theConsole->abortReadLine();
        }
      startTime = QDateTime::currentDateTime();
    }
  else
    {
      QDateTime now = QDateTime::currentDateTime();
      int secs = startTime.secsTo(now);
      int msecs = startTime.time().msecsTo(now.time()) % 1000;
      elapsed += secs + (msecs * 0.001);
    }
  // dealing with pauses
  if (state == QtLuaEngine::Paused)
    {
      if (theEngine->isPaused())
        {
          if (! interactionStarted)
            {
              theEngine->resume(false);
            }
          else if (ttyConsole)
            {
              QByteArray prompt = "[Pause -- press enter to continue] ";
              ttyPauseReceived = true;
              theConsole->readLine(prompt);
            }
        }
    }
  // accepting new commands
  if (state == QtLuaEngine::Ready)
    {
      while (! savedNamedObjects.isEmpty())
        {
          QObjectPointer ptr = savedNamedObjects.takeFirst();
          if (ptr) theEngine->nameObject(ptr);
        }
      if (! argumentsDone)
        {
          argumentsDone = true;
          theEngine->setPrintResults(false);
          theApp->setQuitOnLastWindowClosed(false);
          int status = processArguments(savedArgc, savedArgv);
          if (status && !interactive)
            { theApp->exit(status = EXIT_FAILURE); return; }
          else if (!interactive)
            { theApp->exit(status = EXIT_SUCCESS); return; }
        }
      // go in interactive mode
      if (!interactionStarted)  
        {
          interactionStarted = true;
          theApp->setupConsoleOutput();
          theApp->setQuitOnLastWindowClosed(!ttyConsole);
          bool capture = theConsole->captureOutput();
          theEngine->setPrintResults(ttyConsole || capture);
          if (forceVersion || theEngine->printResults())
            printLuaVersion();
        }
      // accept fresh commands
      if (theEngine->isReady())
        acceptInput(false);
    }
}
Exemple #24
0
int main (int argc, char * argv[]) {
    MOATypeDimn seqNum;
    MOATypeShape * seqLen = NULL;
    char * * sequences = NULL,  * * seqName = NULL, msg[MID_MESSAGE_SIZE];
    long partitionSize;
    long ID1;
    int stype, MPI_return;
    /*char ufilename[SHORT_MESSAGE_SIZE];*/
    int ret;
    ProcessData * pData;
    ScoringData * sData;
    WavesData * wData;
	
    TBFlag = 1;
    prevNow = NULL;
    prevNow = mmalloc ((MOATypeInd) sizeof *prevNow);
    currNow = NULL;
    //currNow = mmalloc ((MOATypeInd) sizeof *currNow);
    currNow = getTime();
    if (currNow == NULL) {
        printf ("Could not read current time. Exiting.\n");
        return -1;
    }
    ID1 = getpid();

    printf("[%d]>PID = %ld Started at time (%d, %d, %d, %d)\n", myProcid, ID1, currNow->tm_yday, currNow->tm_hour, currNow->tm_min, currNow->tm_sec);
    /* 1. Process Arguments*/
    processArguments(argc, argv, &seqNum, &sequences, &seqName, &seqLen, &stype, &partitionSize);
    /*strcpy (ufilename, outputfilename);*/
    strcpy (outPrefix, "b");
    /*sprintf (outputfilename, "mmtb%s", ufilename);*/
    init_output();
    sprintf (msg, "Program Arguments: debuglevel = %d maxAlignmentsNumber = %d Epsilons= %ld Alignment Type = %d stype %d outputfilename = %s partitionSize = %ld\n", pdebug, maxAlignmentsNumber, Epsilons, AlignmentType, stype, outputfilename, partitionSize);
    mprintf (1, msg, 1);
  
    /*2. Do the Master Tasks: Synchronize with Slaves to trace back*/
    /* one path for now*/
  
    ret = initProcessMemory(&pData, &sData, &wData, seqNum, seqLen, sequences, seqName, stype, partitionSize);  
    if (ret != 0) { 
        mprintf (1, " Could not initialize process memory\n", 1);
        freeProcessMemory (&pData, &sData, &wData);
        return -1;
    }
    /*3. Load Tensor Partitions Computed*/
    ret = restoreCheckPoint (pData, wData);
    if (ret != 0) {
        printf (" Could not read Slave data from checkpoint file\n");
        freeProcessMemory (&pData, &sData, &wData);
        return -1;
    }
    if (pData->computedPartitions <= 0) {
        mprintf (1, " No Partitions read in this process\n", 1);
        /*ExitProcess (pData);*/
        /*return -1;*/
    }
    else {
        sprintf (msg, "read Slave data from checkpoint file partitions %ld last score in last partition is %ld sqm %ld sqlen0 %ld %ld %ld\n", pData->partitionsCount, pData->msaAlgn->elements[pData->msaAlgn->elements_ub - 1].val, pData->seqNum, pData->seqLen[0], pData->seqLen[1], pData->seqLen[2]);
        mprintf(3, msg, 1);
    }

    tbMaster(pData, wData);
        /* Getting Process Resources Usage ===================== */
        struct rusage usageRec;
        double utime, stime;

        ret = getrusage(RUSAGE_SELF, &usageRec);
        if (ret == 0) {
            //printf ("[%d]Resources Usage: UTime %ld, STime %ld, Mem %ld, Virt %ld\n", myProcid, usageRec.ru_utime.tv_sec, usageRec.ru_stime.tv_sec, usageRec.ru_maxrss, usageRec.ru_ixrss);
            utime = (double) usageRec.ru_utime.tv_sec + 1.e-6 * (double) usageRec.ru_utime.tv_usec;
            stime = (double) usageRec.ru_stime.tv_sec + 1.e-6 * (double) usageRec.ru_stime.tv_usec;	
            //printf ("[%d]Resources Usage: UTime %f, STime %f\n", myProcid, utime, stime);
        }
        else
            printf ("Failed to retrieve Process Resources Usage, errno %d\n", errno);

        //struct mallinfo info;
        //info = mallinfo();

        //printf("[%d] STime\tUTime\theap\tMemory\t\n",myProcid);
        //printf("[%d] %f\t%f\t%d\t%d\n", myProcid, stime, utime, info.arena, info.usmblks + info.uordblks);

        printf("STime\tUTime\n");
        printf("%f\t%f\n", stime, utime);
        currNow = getTime();
        printf("Finalized at time (%d, %d, %d, %d)\n", currNow->tm_yday, currNow->tm_hour, currNow->tm_min, currNow->tm_sec);
   freeProcessMemory (&pData, &sData, &wData);

    return 0;
}
Exemple #25
0
int main(int argc, char* argv[])
{
    SCANPARAMS* myScan;
    
    int real[RAM_SIZE];         // (16*1024)
    int imag[RAM_SIZE];
    
    char fid_fname[FNAME_SIZE];
	char jcamp_fname[FNAME_SIZE];
	char ascii_fname[FNAME_SIZE];
    
	myScan = (SCANPARAMS*)malloc( sizeof(SCANPARAMS) );
	memset((void*)myScan, 0, sizeof(SCANPARAMS));
	
	if( processArguments(argc,argv,myScan) == 0)
	{
        
        if(pb_count_boards() <= 0)
        {
           if(myScan->verbose) printf("No RadioProcessor boards were detected in your system.\n");
           return BOARD_NOT_DETECTED;
        }
        
        if(myScan->verbose) 
           outputScanParams(myScan);
           
        strncpy(fid_fname, myScan->outputFilename, FNAME_SIZE);
        strncat(fid_fname, ".fid", FNAME_SIZE);
		strncpy(jcamp_fname, myScan->outputFilename, FNAME_SIZE);
		strncat(jcamp_fname, ".jdx", FNAME_SIZE);
		strncpy(ascii_fname, myScan->outputFilename, FNAME_SIZE);
		strncat(ascii_fname, ".txt", FNAME_SIZE);	
        
        pb_select_board( myScan->board_num );
        
        configureBoard(myScan); //Set board defaults.
        
        if(programBoard(myScan)!=0) //Program the board.
        {
           if(myScan->verbose) printf("Error: Failed to program board.\n");
           return PROGRAMMING_FAILED;
        }
        printf("pb_Start()\n");
        pb_start();
            
        if(myScan->verbose) 
            printf("Waiting for the data acquisition to complete.\n");
            
        while(pb_read_status() != BOARD_STATUS_IDLE) //Wait for the board to complete execution.
        {
            pb_sleep_ms(100);
        }
            
    	if(myScan->enable_rx)
		{
			pb_get_data(RAM_SIZE, real, imag);
				
			pb_write_felix(fid_fname, myScan->nPoints , myScan->actualSpectralWidth, myScan->spectrometerFrequency, real, imag);
			pb_write_ascii_verbose(ascii_fname, myScan->nPoints, myScan->actualSpectralWidth, myScan->spectrometerFrequency, real, imag);
			pb_write_jcamp(jcamp_fname, myScan->nPoints, myScan->actualSpectralWidth, myScan->spectrometerFrequency, real, imag);
		}
		
   	    pb_close();
	}

	free(myScan);
	
	return 0;
}
Exemple #26
0
/* =============================================================================
	The main function:
		Initialize MPI, 
		Process arguments (processArguments)
		Initialize output debugging files (init_output)
		call MainProcess function, 
		and finalizes MPI.

============================================================================= */
int main(int argc, char **argv) {
    MPI_Group orig_group;	
    char * * sequences = NULL;/*, ufilename[SHORT_MESSAGE_SIZE];*/
    char * * seqName = NULL;
    long partitionSize;
    MOATypeDimn seqNum;
    MOATypeShape * seqLen = NULL;
    int stype;
    long ID1;
#ifndef NDEBUG
    char msg[SHORT_MESSAGE_SIZE];
#endif			
    /* MPI Initiliaztion ==================================================*/
    MPI_Init(&argc, &argv);
    /* Get my Rank in myProcid*/
    MPI_Comm_rank(MPI_COMM_WORLD, &myProcid);
    /* Get the number of processes running in the ClusterSize*/
    MPI_Comm_size(MPI_COMM_WORLD, &ClusterSize);
    /* Get the group associated with the communicator ===============*/
    MPI_Comm_group (MPI_COMM_WORLD, &orig_group);
    MPI_Comm_create(MPI_COMM_WORLD, orig_group, &MOAMSA_COMM_WORLD);
    /* ============================================ end MPI initialization*/
    TBFlag = 0;
    /* 1. Process Arguments, Sequences, lengths, scoring type, partition Size, output prefix, ... etc*/
    processArguments(argc, argv, &seqNum, &sequences, &seqName, &seqLen, &stype, &partitionSize);
    /*  Thought I can run the same program in Distributed and Sequential Mode, but only now the Distributed one is being tested, so ignore this one*/

    /* Initialize output debugging files*/
    strcpy (outPrefix, "c");
    if (init_output() == 0) {
        /* Initialize timing variables, previous Time (prevNow) and Current Time  (currNow)*/
        prevNow = NULL;
        prevNow = mmalloc ((MOATypeInd) sizeof *prevNow);
        currNow = NULL;
        //currNow = mmalloc ((MOATypeInd) sizeof *currNow);
        currNow = getTime();
        if (currNow == NULL) {
            printf ("Could not read current time. Exiting.\n");
            return -1;
        }
        ID1 = getpid();

        printf("[%d]>PID = %ld Started at time (%d, %d, %d, %d)\n", myProcid, ID1, currNow->tm_yday, currNow->tm_hour, currNow->tm_min, currNow->tm_sec);
#ifndef NDEBUG
        sprintf(msg, "[%d]>Started at time (%d, %d, %d, %d)\n", myProcid, currNow->tm_yday, currNow->tm_hour, currNow->tm_min, currNow->tm_sec);	
        mprintf(0, msg, 1);
#endif
        cpTime (currNow, &prevNow);

        /* Calling the main process ==========================================*/
        MainProcess(seqNum, sequences, seqName, seqLen, stype, partitionSize);
        currNow = getTime();
if (myProcid == 0) {
        printf("[%d]>Finalized at time (%d, %d, %d, %d)\n", myProcid, currNow->tm_yday, currNow->tm_hour, currNow->tm_min, currNow->tm_sec);
}
#ifndef NDEBUG
        sprintf(msg, "[%d]>Finalized at time (%d, %d, %d, %d)\n", myProcid, currNow->tm_yday, currNow->tm_hour, currNow->tm_min, currNow->tm_sec);	
        mprintf(0, msg, 1);
#endif
        if (prevNow != NULL)
            free (prevNow);
    }
    if (close_output () != 0) 
        printf ("[%d] Error closing output files\n", myProcid);
    /* Finalize MPI ==================================================*/
    MPI_Finalize();

    return 0;
} /* of main */