Example #1
0
//=============
// Constructor
//=============
cJulius::cJulius( void ) : m_jconf( NULL ), m_recog( NULL ), m_opened( false ), m_threadHandle( NULL ), m_fpLogFile( NULL ), m_modelLocale( NULL )
{
#ifdef APP_ADIN
	m_appsource = 0;
#endif
	setLogFile( "juliuslog.txt" );
}
Example #2
0
bool Magic3D::Log::clear() {
#ifdef MAGIC3D_LOG
    FILE*  pFile;
    time_t ttime;
    tm* pCurTime;
    char cLogStart[128];

    if (logFile == NULL)
    {
        setLogFile(std::string(Magic3D::Magic3D::getApplicationPath() + "magic3d.log.html").c_str());
    }

    time(&ttime);
    pCurTime = localtime(&ttime);
    strftime(cLogStart, 128, "Magic3D Log Started on %m/%d/%Y at %H:%M:%S", pCurTime);

    pFile = fopen(logFile, "wt");

    if(!pFile) {
        return false;
    }

    fprintf(pFile, "<HTML>\n<TITLE>%s</TITLE>\n"
            "<BODY BGCOLOR= \"#000000\">\n"
            "<FONT COLOR= \"#FFFFFF\">%s</FONT><BR><BR>\n"
            "</BODY>\n</HTML>", cLogStart, cLogStart);

    fclose(pFile);
#endif
    return true;
}
Example #3
0
Log::Log(const Char8 *fileName, LogLevel logLevel) :
    std::ostream  (_nilbufP == NULL ?
                   _nilbufP = new Log::nilbuf() : _nilbufP),
    _logType       (LOG_FILE      ),
    _logLevel      (logLevel      ),
    _fileStream    (              ),
    _logBuf        (              ),
    _headerElem    (             0),
    _moduleHandling(LOG_MODULE_ALL),
    _moduleList    (              ),
    _refTime       (             0)
{
    if(_nilstreamP == NULL)
        _nilstreamP = new std::ostream(_nilbufP);

    for(UInt32 i = 0; i < sizeof(_streamVec)/sizeof(LogOStream *); i++)
    {
#ifdef OSG_HAS_NILBUF
        _streamVec[i] = new LogOStream(_nilbufP);
#else
        _streamVec[i] = new LogOStream(_nilStreamP->rdbuf());
#endif
    }

    _refTime = getSystemTime();

    setHeaderElem(LOG_TYPE_HEADER);
    setLogFile   (fileName);
    setLogLevel  (logLevel);
}
Example #4
0
ChunkGraph::ChunkGraph(const char *output_prefix) {

  setLogFile(output_prefix, "ChunkGraph");

  _maxFragment     = FI->numFragments();

  _pathLen         = new uint32      [_maxFragment * 2 + 2];
  _chunkLength     = new ChunkLength [_maxFragment];
  _chunkLengthIter = 0;

  memset(_pathLen,     0, sizeof(uint32)      * (_maxFragment * 2 + 2));
  memset(_chunkLength, 0, sizeof(ChunkLength) * (_maxFragment));

  for (uint32 fid=1; fid <= _maxFragment; fid++) {
    if (OG->isContained(fid))
      continue;

    _chunkLength[fid-1].fragId = fid;
    _chunkLength[fid-1].cnt    = (countFullWidth(FragmentEnd(fid, false)) +
                                  countFullWidth(FragmentEnd(fid, true)));
  }

  delete [] _pathLen;
  _pathLen = NULL;

  std::sort(_chunkLength, _chunkLength + _maxFragment);
}
Example #5
0
void Logger::enterNextLogFile()
{
    if (!_logDirectory.isEmpty()) {
        QDir dir(_logDirectory);
        if (!dir.exists()) {
            dir.mkpath(".");
        }

        // Find out what is the file with the highest nymber if any
        QStringList files = dir.entryList(QStringList("owncloud.log.*"),
                                    QDir::Files);
        QRegExp rx("owncloud.log.(\\d+)");
        uint maxNumber = 0;
        QDateTime now = QDateTime::currentDateTime();
        foreach(const QString &s, files) {
            if (rx.exactMatch(s)) {
                maxNumber = qMax(maxNumber, rx.cap(1).toUInt());
                if (_logExpire > 0) {
                    QFileInfo fileInfo = dir.absoluteFilePath(s);
                    if (fileInfo.lastModified().addSecs(60*60 * _logExpire) < now) {
                        dir.remove(s);
                    }
                }
            }
        }

        QString filename = _logDirectory + "/owncloud.log." + QString::number(maxNumber+1);
        setLogFile(filename);
    }
Example #6
0
str
CMDsetProfilerFile(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci)
{
	str *fnme = getArgReference_str(stk,pci,1);
	(void) mb;		/* fool compiler */
	return setLogFile(cntxt->fdout,cntxt->nspace, *fnme);
}
Example #7
0
ChunkGraph::ChunkGraph(const char *output_prefix) {

  setLogFile(output_prefix, "ChunkGraph");

  _maxFragment = FI->numFragments();
  _restrict    = NULL;

  _pathLen         = new uint32      [_maxFragment * 2 + 2];
  _chunkLength     = new ChunkLength [_maxFragment];
  _chunkLengthIter = 0;

  memset(_pathLen,     0, sizeof(uint32)      * (_maxFragment * 2 + 2));
  memset(_chunkLength, 0, sizeof(ChunkLength) * (_maxFragment));

  for (uint32 fid=1; fid <= _maxFragment; fid++) {
    if (OG->isContained(fid))
      continue;

    if (OG->isSuspicious(fid))
      //  Fragment is suspicious.  We won't seed a BOG from it, and populateUnitig will make only a
      //  singleton.
      continue;

    _chunkLength[fid-1].fragId = fid;
    _chunkLength[fid-1].cnt    = (countFullWidth(FragmentEnd(fid, false)) +
                                  countFullWidth(FragmentEnd(fid, true)));
  }

  delete [] _pathLen;
  _pathLen = NULL;

  std::sort(_chunkLength, _chunkLength + _maxFragment);
}
Example #8
0
/**
 * Main method.
 *
 * @param argc the number of command line arguments.
 * @param argv the command line arguments.
 */
int main(int argc, char* argv[])
{
	struct argp argp = { argpoptions, parse_opt, NULL, argpdoc, NULL, NULL, NULL };
	setenv("ARGP_HELP_FMT", "no-dup-args-note", 0);
	if (argp_parse(&argp, argc, argv, ARGP_IN_ORDER, NULL, &opt) != 0)
		return EINVAL;

	s_messageMap = new MessageMap(opt.checkConfig && opt.scanConfig);
	if (opt.checkConfig) {
		logNotice(lf_main, "Performing configuration check...");

		result_t result = loadConfigFiles(s_messageMap, true);

		if (result == RESULT_OK && opt.checkConfig > 1) {
			logNotice(lf_main, "Configuration dump:");
			s_messageMap->dump(cout);
		}
		delete s_messageMap;
		s_messageMap = NULL;
		globalTemplates.clear();

		return 0;
	}

	// open the device
	Device *device = Device::create(opt.device, !opt.noDeviceCheck, opt.readonly, &logRawData);
	if (device == NULL) {
		logError(lf_main, "unable to create device %s", opt.device);
		return EINVAL;
	}

	if (!opt.foreground) {
		setLogFile(opt.logFile);
		daemonize(); // make me daemon
	}

	// trap signals that we expect to receive
	signal(SIGHUP, signalHandler);
	signal(SIGINT, signalHandler);
	signal(SIGTERM, signalHandler);

	logNotice(lf_main, PACKAGE_STRING "." REVISION " started");

	// load configuration files
	loadConfigFiles(s_messageMap);
	if (s_messageMap->sizeConditions()>0 && opt.pollInterval==0)
		logError(lf_main, "conditions require a poll interval > 0");

	// create the MainLoop and run it
	s_mainLoop = new MainLoop(opt, device, s_messageMap);
	s_mainLoop->start("mainloop");
	s_mainLoop->join();

	// shutdown
	shutdown();
}
Example #9
0
int main(int argc, char *argv[])
{
	string configFilename = "Config.json";
	string logFilename = "-";

#ifndef _WIN32
	cmdline::parser arg;
	arg.add<string>("config", 'c', "configuration file", false, "Config.json");
	arg.add<string>("log", 'l', "log file", false, "-");
	arg.parse_check(argc, argv);
	configFilename = arg.get<string>("config");
	logFilename = arg.get<string>("log");
#endif 

	log_normal("Using configuration file: %s", configFilename.c_str());
	log_normal("Log file: %s", logFilename.c_str());

	setLogFile(logFilename);

	Document configDoc = loadConfigObj(configFilename);
	Value &roomsVal = configDoc["Rooms"];
	assert(roomsVal.IsArray());
	vector<RoomInfo> rooms(loadRooms(roomsVal));

	initLibraries();

	CubeServer server;
	configRooms(server, rooms);

	server.EnableTimer(CHECK_INTERVAL_uS);

	configServer(server, configDoc["Server"]);

	server.IsRunning = true;
	thread th(eventEntry, &server);

	initHandlers();
	handleCommand(server);

	server.Stop();
	th.join();

	log_normal("%s", "Stopped.");

#ifdef MEM_DEBUG
#ifdef _WIN32
	_CrtDumpMemoryLeaks();
#endif 
#endif 

	return 0;
}
Example #10
0
Log::~Log(void)
{
    setLogFile(NULL, true);

    delete _nilstreamP;
    delete _nilbufP;

    _nilstreamP = NULL;
    _nilbufP    = NULL;

    for(UInt32 i = 0; i < sizeof(_streamVec)/sizeof(LogOStream *); i++)
    {
        delete _streamVec[i];

        _streamVec[i] = NULL;
    }

}
Example #11
0
ChunkGraph::ChunkGraph(const char *output_prefix) {

  setLogFile(output_prefix, "ChunkGraph");

  _maxFragment = FI->numFragments();
  _restrict    = NULL;

  _pathLen         = new uint32      [_maxFragment * 2 + 2];
  _chunkLength     = new ChunkLength [_maxFragment];
  _chunkLengthIter = 0;

  memset(_pathLen,     0, sizeof(uint32)      * (_maxFragment * 2 + 2));
  memset(_chunkLength, 0, sizeof(ChunkLength) * (_maxFragment));

  for (uint32 fid=1; fid <= _maxFragment; fid++) {
    if (OG->isContained(fid)) {
      if (logFileFlagSet(LOG_CHUNK_GRAPH))
        writeLog("read %u contained\n", fid);
      continue;
    }

    if (OG->isSuspicious(fid)) {
      if (logFileFlagSet(LOG_CHUNK_GRAPH))
        writeLog("read %u suspicious\n", fid);
      continue;
    }

    uint32  l5 = countFullWidth(FragmentEnd(fid, false));
    uint32  l3 = countFullWidth(FragmentEnd(fid, true));

    _chunkLength[fid-1].fragId = fid;
    _chunkLength[fid-1].cnt    = l5 + l3;
  }

  delete [] _pathLen;
  _pathLen = NULL;

  std::sort(_chunkLength, _chunkLength + _maxFragment);
}
Example #12
0
/// 功能介绍
// 显示历史log的地方
QJDHistoryBrowser::QJDHistoryBrowser(QWidget *parent) :
        QTableWidget(parent)
{
    setContextMenuPolicy(Qt::CustomContextMenu);
    setFocusPolicy(Qt::NoFocus);
    this->setObjectName(QString::fromUtf8("processWidget"));
    this->setMinimumSize(QSize(0, 0));

    this->setFrameShape(QFrame::WinPanel);
    this->setFrameShadow(QFrame::Raised);
    this->setAutoScroll(false);
    this->setEditTriggers(QAbstractItemView::NoEditTriggers);
    this->setAlternatingRowColors(true);
    this->setSelectionMode(QAbstractItemView::SingleSelection);
    this->setSelectionBehavior(QAbstractItemView::SelectRows);
    this->setTextElideMode(Qt::ElideRight);
    this->setShowGrid(true);
    this->setGridStyle(Qt::SolidLine);
    this->setSortingEnabled(false);
    this->setWordWrap(true);
    this->setCornerButtonEnabled(true);

    // --------------------------------------------------------------- //
    _hasLog=false;
    saveSelect=0;

    setRowCount(4);
    setColumnCount(4);

    setLogFile();
    connect(this,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(emitShowLog(QModelIndex)));

    QJDArgu *argu=new QJDArgu;
    QTimer *timer=new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(clearAndReset()));
    timer->start(argu->HistoryLogRefreshInterval);   //每隔10秒钟才刷新一次

}
Example #13
0
// 清除原始数据,定时检查
void QJDHistoryBrowser::clearAndReset()
{
    this->clear();
    setLogFile();
}
/**
   @param fname the file to connect to, if NULL (default) then robot.log
   @return 0 for success, otherwise one of the open enums
   @see getOpenMessage
*/
AREXPORT int ArLogFileConnection::open(const char *fname)
{
  setLogFile(fname);
  return internalOpen();
}
Example #15
0
void Debug::setDefaultLogFile(void)
{
    setLogFile(LOG_FILE);
}
Example #16
0
int main(){
	setLogDebugLevel( dbgLevel );
	setLogFile( logFile );
	setLogSilentMode(1);

	writeLog( 0, "Starting remoteAdv Master Client - Version: %s", version );
	
	// Gets a hostent struct containing data about the given host
	struct hostent *server = gethostbyname( server_ip );
	if(server == NULL) {
		herror("ERROR: Host lookup failed");
		exit(1);
	}

	// Create a TCP socket and return a file descriptor for accessing it
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockfd == -1) {
		perror("ERROR: Open socket failed");
		exit(1);
	}

	// Create and initialize a sock_addr struct contianing info about the server to connect to
	struct sockaddr_in server_addr;
	memset( &server_addr , 0 , sizeof(server_addr));
	// Denotes an internet socket
    server_addr.sin_family = AF_INET;
    // Copies several values from the server hostent struct into this one
	memcpy( &server_addr.sin_addr.s_addr, server->h_addr, server->h_length );
    // Sets the server port to the one passed in
    server_addr.sin_port = server_port;

    // Connect to the server
    int connectResult = connect(sockfd,(struct sockaddr*)&server_addr, sizeof(server_addr));
    if(connectResult == -1) {
        perror("ERROR: Connection to server failed");
        exit(1);
    }

    int auth_result = authenticate( sockfd );
    if( auth_result == -1 ) {
        writeLog( -1, "Server authentication failed" );
        exit(1);
    } else {
        writeLog( 2, "Server connection successful" );
        writeLog( 3, "Connected to server at '%s:%d'", server_ip, server_port );
    }

    int end = 0;

    // Wait to send commands
    while( !end ) {
    	printMenu(); // Display options to allow user to see options.

    	int input = 0;
    	scanf( "%d", &input );

    	switch( input ) {
    		case sel_list_slaves:
    			system( "clear" );      // Clear works on unix like enviorments, this will throw an error on windows.
    			list_slaves( sockfd );
    			break;
    		case sel_claim_client:
    			system( "clear" );
    			claim_client( sockfd );
    			break;
    		case sel_release_client:
    			release_client( sockfd );
    			break;
    		case sel_set_debug_level:
    			set_debug_level( sockfd );
    			break;
    		case sel_kill_client:
    			kill_client( sockfd );
    			break;
    		case sel_close:
    			end = 1;
    		default:
    			break;
    	}

    	fflush( stdout );
    	system( "clear" );
    }

    // Close the connection to the server
    close( sockfd );

    return 0;
}
Example #17
0
void DanbooruTest::initTestCase()
{
	setLogFile("tests/test_log.log");
}
BestOverlapGraph::BestOverlapGraph(OverlapStore        *ovlStoreUniq,
                                   OverlapStore        *ovlStoreRept,
                                   double               AS_UTG_ERROR_RATE,
                                   double               AS_UTG_ERROR_LIMIT,
                                   const char          *prefix) {
  OVSoverlap olap;

  _best5 = new BestEdgeOverlap [FI->numFragments() + 1];
  _best3 = new BestEdgeOverlap [FI->numFragments() + 1];
  _bestC = new BestContainment [FI->numFragments() + 1];

  memset(_best5, 0, sizeof(BestEdgeOverlap) * (FI->numFragments() + 1));
  memset(_best3, 0, sizeof(BestEdgeOverlap) * (FI->numFragments() + 1));
  memset(_bestC, 0, sizeof(BestContainment) * (FI->numFragments() + 1));

  assert(AS_UTG_ERROR_RATE >= 0.0);
  assert(AS_UTG_ERROR_RATE <= AS_MAX_ERROR_RATE);

  assert(AS_CNS_ERROR_RATE >= 0.0);
  assert(AS_CNS_ERROR_RATE <= AS_MAX_ERROR_RATE);

  mismatchCutoff  = AS_OVS_encodeQuality(AS_UTG_ERROR_RATE);
  consensusCutoff = AS_OVS_encodeQuality(AS_CNS_ERROR_RATE);

  mismatchLimit   = AS_UTG_ERROR_LIMIT;

  if (load(prefix, AS_UTG_ERROR_RATE, AS_UTG_ERROR_LIMIT)) {
    logFileOrder += 2;  //  To keep indices the same on log names
    setLogFile(prefix, NULL);
    return;
  }

  //  Pass 1 through overlaps -- find the contained fragments.

  setLogFile(prefix, "bestoverlapgraph-containments");

  _bestCscore    = new uint64 [FI->numFragments() + 1];
  memset(_bestCscore,    0, sizeof(uint64) * (FI->numFragments() + 1));

  AS_OVS_resetRangeOverlapStore(ovlStoreUniq);
  while  (AS_OVS_readOverlapFromStore(ovlStoreUniq, &olap, AS_OVS_TYPE_OVL))
    scoreContainment(olap);

  if (ovlStoreRept) {
    AS_OVS_resetRangeOverlapStore(ovlStoreRept);
    while  (AS_OVS_readOverlapFromStore(ovlStoreRept, &olap, AS_OVS_TYPE_OVL))
      scoreContainment(olap);
  }

  delete [] _bestCscore;
  _bestCscore    = NULL;


  //  Report some statistics on overlaps
  {
    uint64  numContainsToSave = 0;

    for (uint32 i=0; i<FI->numFragments(); i++)
      numContainsToSave += _bestC[i].olapsLen;

    fprintf(logFile, "Need to save "F_U64" near-containment overlaps\n", numContainsToSave);
  }


  //  Pass 2 through overlaps -- find dovetails, build the overlap graph.  For each
  //  contained fragment, remember some of the almost containment overlaps.

  setLogFile(prefix, "bestoverlapgraph-dovetails");

  _best5score = new uint64 [FI->numFragments() + 1];
  _best3score = new uint64 [FI->numFragments() + 1];

  memset(_best5score, 0, sizeof(uint64) * (FI->numFragments() + 1));
  memset(_best3score, 0, sizeof(uint64) * (FI->numFragments() + 1));

  AS_OVS_resetRangeOverlapStore(ovlStoreUniq);
  while  (AS_OVS_readOverlapFromStore(ovlStoreUniq, &olap, AS_OVS_TYPE_OVL))
    scoreEdge(olap);

  if (ovlStoreRept) {
    AS_OVS_resetRangeOverlapStore(ovlStoreRept);
    while  (AS_OVS_readOverlapFromStore(ovlStoreRept, &olap, AS_OVS_TYPE_OVL))
      scoreEdge(olap);
  }

  delete [] _best5score;
  delete [] _best3score;

  _best5score = NULL;
  _best3score = NULL;

  setLogFile(prefix, NULL);


  //  Clean up our allocation.  We seem to over count the number of overlaps in the first pass,
  //  then don't add any overlaps in the second pass, leaving the count positive and the pointer
  //  NULL.  In the case where we just overcount, the pointer is valid, and the count is correct.
  //
  //  A better explanation is that we count near containment overlaps for ALL fragments in the
  //  first pass, but then only save near containment overlaps for contained fragments, leaving
  //  the dovetail fragments with a positive count and a NULL pointer.
  //
  for (uint32 i=0; i<FI->numFragments() + 1; i++)
    if (_bestC[i].olaps == NULL)
      _bestC[i].olapsLen = 0;


  //  Diagnostic.  Dump the best edges, count the number of contained
  //  reads, etc.
  {
    FILE *BC = fopen("best.contains", "w");
    FILE *BE = fopen("best.edges", "w");
    FILE *BS = fopen("best.singletons", "w");

    if ((BC) && (BE)) {
      fprintf(BC, "#fragId\tlibId\tmated\tbestCont\n");
      fprintf(BE, "#fragId\tlibId\tbest5\tbest3\n");
      fprintf(BS, "#fragId\tlibId\tmated\n");

      for (uint32 id=1; id<FI->numFragments() + 1; id++) {
        BestContainment *bestcont  = getBestContainer(id);
        BestEdgeOverlap *bestedge5 = getBestEdgeOverlap(id, false);
        BestEdgeOverlap *bestedge3 = getBestEdgeOverlap(id, true);

        if (bestcont)
          fprintf(BC, "%u\t%u\t%c\t%u\n", id, FI->libraryIID(id), (FI->mateIID(id) > 0) ? 'm' : 'f', bestcont->container);
        else if ((bestedge5->fragId() > 0) || (bestedge3->fragId() > 0))
          fprintf(BE, "%u\t%u\t%u\t%c'\t%u\t%c'\n", id, FI->libraryIID(id),
                  bestedge5->fragId(), bestedge5->frag3p() ? '3' : '5',
                  bestedge3->fragId(), bestedge3->frag3p() ? '3' : '5');
        else
          fprintf(BS, "%u\t%u\t%c\n", id, FI->libraryIID(id), (FI->mateIID(id) > 0) ? 'm' : 'f');

      }

      fclose(BC);
      fclose(BE);
      fclose(BS);
    }
  }

  save(prefix, AS_UTG_ERROR_RATE, AS_UTG_ERROR_LIMIT);
}
Example #19
0
int mrsWatsonMain(ErrorReporter errorReporter, int argc, char** argv) {
  ReturnCodes result;
  // Input/Output sources, plugin chain, and other required objects
  SampleSource inputSource = NULL;
  SampleSource outputSource = NULL;
  AudioClock audioClock;
  PluginChain pluginChain;
  CharString pluginSearchRoot = newCharString();
  boolByte shouldDisplayPluginInfo = false;
  MidiSequence midiSequence = NULL;
  MidiSource midiSource = NULL;
  unsigned long maxTimeInMs = 0;
  unsigned long maxTimeInFrames = 0;
  unsigned long tailTimeInMs = 0;
  unsigned long tailTimeInFrames = 0;
  unsigned long processingDelayInFrames;
  ProgramOptions programOptions;
  ProgramOption option;
  Plugin headPlugin;
  SampleBuffer inputSampleBuffer = NULL;
  SampleBuffer outputSampleBuffer = NULL;
  TaskTimer initTimer, totalTimer, inputTimer, outputTimer = NULL;
  LinkedList taskTimerList = NULL;
  CharString totalTimeString = NULL;
  boolByte finishedReading = false;
  SampleSource silentSampleInput;
  SampleSource silentSampleOutput;
  unsigned int i;

  initTimer = newTaskTimerWithCString(PROGRAM_NAME, "Initialization");
  totalTimer = newTaskTimerWithCString(PROGRAM_NAME, "Total Time");
  taskTimerStart(initTimer);
  taskTimerStart(totalTimer);

  initEventLogger();
  initAudioSettings();
  initAudioClock();
  audioClock = getAudioClock();
  initPluginChain();
  pluginChain = getPluginChain();
  programOptions = newMrsWatsonOptions();
  inputSource = sampleSourceFactory(NULL);

  if(!programOptionsParseArgs(programOptions, argc, argv)) {
    printf("Run with '--help' to see possible options\n");
    printf("Or run with '--help full' to see extended help for all options\n");
    return RETURN_CODE_INVALID_ARGUMENT;
  }

  // These options conflict with standard processing (more or less), so check to see if the user wanted one
  // of these and then exit right away.
  if(argc == 1) {
    printf("%s needs at least a plugin, input source, and output source to run.\n\n", PROGRAM_NAME);
    printMrsWatsonQuickstart(argv[0]);
    return RETURN_CODE_NOT_RUN;
  }
  else if(programOptions->options[OPTION_HELP]->enabled) {
    printMrsWatsonQuickstart(argv[0]);
    if(charStringIsEmpty(programOptionsGetString(programOptions, OPTION_HELP))) {
      printf("All options, where <argument> is required and [argument] is optional:\n");
      programOptionsPrintHelp(programOptions, false, DEFAULT_INDENT_SIZE);
    }
    else {
      if(charStringIsEqualToCString(programOptionsGetString(programOptions, OPTION_HELP), "full", true)) {
        programOptionsPrintHelp(programOptions, true, DEFAULT_INDENT_SIZE);
      }
      // Yeah this is a bit silly, but the performance obviously doesn't matter
      // here and I don't feel like cluttering up this already huge function
      // with more variables.
      else if(programOptionsFind(programOptions, programOptionsGetString(programOptions, OPTION_HELP))) {
        programOptionPrintHelp(programOptionsFind(programOptions, programOptionsGetString(programOptions, OPTION_HELP)),
          true, DEFAULT_INDENT_SIZE, 0);
      }
      else {
        printf("Invalid option '%s', try running --help full to see help for all options\n",
          programOptionsGetString(programOptions, OPTION_HELP)->data);
      }
    }
    return RETURN_CODE_NOT_RUN;
  }
  else if(programOptions->options[OPTION_VERSION]->enabled) {
    printVersion();
    return RETURN_CODE_NOT_RUN;
  }
  else if(programOptions->options[OPTION_COLOR_TEST]->enabled) {
    printTestPattern();
    return RETURN_CODE_NOT_RUN;
  }
  // See if we are to make an error report and make necessary changes to the
  // options for good diagnostics. Note that error reports cannot be generated
  // for any of the above options which return with RETURN_CODE_NOT_RUN.
  else if(programOptions->options[OPTION_ERROR_REPORT]->enabled) {
    errorReporterInitialize(errorReporter);
    programOptions->options[OPTION_VERBOSE]->enabled = true;
    programOptions->options[OPTION_LOG_FILE]->enabled = true;
    programOptions->options[OPTION_DISPLAY_INFO]->enabled = true;
    // Shell script with original command line arguments
    errorReporterCreateLauncher(errorReporter, argc, argv);
    // Rewrite some paths before any input or output sources have been opened.
    _remapFileToErrorReport(errorReporter, programOptions->options[OPTION_INPUT_SOURCE], true);
    _remapFileToErrorReport(errorReporter, programOptions->options[OPTION_OUTPUT_SOURCE], false);
    _remapFileToErrorReport(errorReporter, programOptions->options[OPTION_MIDI_SOURCE], true);
    _remapFileToErrorReport(errorReporter, programOptions->options[OPTION_LOG_FILE], false);
  }

  // Read in options from a configuration file, if given
  if(programOptions->options[OPTION_CONFIG_FILE]->enabled) {
    if(!programOptionsParseConfigFile(programOptions, programOptionsGetString(programOptions, OPTION_CONFIG_FILE))) {
      return RETURN_CODE_INVALID_ARGUMENT;
    }
  }

  // Parse these options first so that log messages displayed in the below
  // loop are properly displayed
  if(programOptions->options[OPTION_VERBOSE]->enabled) {
    setLogLevel(LOG_DEBUG);
  }
  else if(programOptions->options[OPTION_QUIET]->enabled) {
    setLogLevel(LOG_ERROR);
  }
  else if(programOptions->options[OPTION_LOG_LEVEL]->enabled) {
    setLogLevelFromString(programOptionsGetString(programOptions, OPTION_LOG_LEVEL));
  }
  if(programOptions->options[OPTION_COLOR_LOGGING]->enabled) {
    // If --color was given but with no string argument, then force color. Otherwise
    // colors will be provided automatically anyways.
    if(charStringIsEmpty(programOptionsGetString(programOptions, OPTION_COLOR_LOGGING))) {
      programOptionsSetCString(programOptions, OPTION_COLOR_LOGGING, "force");
    }
    setLoggingColorEnabledWithString(programOptionsGetString(programOptions, OPTION_COLOR_LOGGING));
  }
  if(programOptions->options[OPTION_LOG_FILE]->enabled) {
    setLogFile(programOptionsGetString(programOptions, OPTION_LOG_FILE));
  }

  // Parse other options and set up necessary objects
  for(i = 0; i < programOptions->numOptions; i++) {
    option = programOptions->options[i];
    if(option->enabled) {
      switch(option->index) {
        case OPTION_BLOCKSIZE:
          setBlocksize((const unsigned long)programOptionsGetNumber(programOptions, OPTION_BLOCKSIZE));
          break;
        case OPTION_CHANNELS:
          setNumChannels((const unsigned long)programOptionsGetNumber(programOptions, OPTION_CHANNELS));
          break;
        case OPTION_DISPLAY_INFO:
          shouldDisplayPluginInfo = true;
          break;
        case OPTION_INPUT_SOURCE:
          freeSampleSource(inputSource);
          inputSource = sampleSourceFactory(programOptionsGetString(programOptions, OPTION_INPUT_SOURCE));
          break;
        case OPTION_MAX_TIME:
          maxTimeInMs = (const unsigned long)programOptionsGetNumber(programOptions, OPTION_MAX_TIME);
          break;
        case OPTION_MIDI_SOURCE:
          midiSource = newMidiSource(guessMidiSourceType(programOptionsGetString(
            programOptions, OPTION_MIDI_SOURCE)),
            programOptionsGetString(programOptions, OPTION_MIDI_SOURCE));
          break;
        case OPTION_OUTPUT_SOURCE:
          outputSource = sampleSourceFactory(programOptionsGetString(programOptions, OPTION_OUTPUT_SOURCE));
          break;
        case OPTION_PLUGIN_ROOT:
          charStringCopy(pluginSearchRoot, programOptionsGetString(programOptions, OPTION_PLUGIN_ROOT));
          break;
        case OPTION_SAMPLE_RATE:
          setSampleRate(programOptionsGetNumber(programOptions, OPTION_SAMPLE_RATE));
          break;
        case OPTION_TAIL_TIME:
          tailTimeInMs = (long)programOptionsGetNumber(programOptions, OPTION_TAIL_TIME);
          break;
        case OPTION_TEMPO:
          setTempo(programOptionsGetNumber(programOptions, OPTION_TEMPO));
          break;
        case OPTION_TIME_SIGNATURE:
          if(!setTimeSignatureFromString(programOptionsGetString(programOptions, OPTION_TIME_SIGNATURE))) {
            return RETURN_CODE_INVALID_ARGUMENT;
          }
          break;
        case OPTION_ZEBRA_SIZE:
          setLoggingZebraSize((int)programOptionsGetNumber(programOptions, OPTION_ZEBRA_SIZE));
          break;
        default:
          // Ignore -- no special handling needs to be performed here
          break;
      }
    }
  }

  if(programOptions->options[OPTION_LIST_PLUGINS]->enabled) {
    listAvailablePlugins(pluginSearchRoot);
    return RETURN_CODE_NOT_RUN;
  }
  if(programOptions->options[OPTION_LIST_FILE_TYPES]->enabled) {
    sampleSourcePrintSupportedTypes();
    return RETURN_CODE_NOT_RUN;
  }

  printWelcomeMessage(argc, argv);
  if((result = setupInputSource(inputSource)) != RETURN_CODE_SUCCESS) {
    logError("Input source could not be opened, exiting");
    return result;
  }
  if((result = buildPluginChain(pluginChain, programOptionsGetString(programOptions, OPTION_PLUGIN),
    pluginSearchRoot)) != RETURN_CODE_SUCCESS) {
    logError("Plugin chain could not be constructed, exiting");
    return result;
  }
  if(midiSource != NULL) {
    result = setupMidiSource(midiSource, &midiSequence);
    if(result != RETURN_CODE_SUCCESS) {
      logError("MIDI source could not be opened, exiting");
      return result;
    }
  }

  // Copy plugins before they have been opened
  if(programOptions->options[OPTION_ERROR_REPORT]->enabled) {
    if(errorReporterShouldCopyPlugins()) {
      if(!errorReporterCopyPlugins(errorReporter, pluginChain)) {
        logWarn("Failed copying plugins to error report directory");
      }
    }
  }

  // Initialize the plugin chain after the global sample rate has been set
  result = pluginChainInitialize(pluginChain);
  if(result != RETURN_CODE_SUCCESS) {
    logError("Could not initialize plugin chain");
    return result;
  }

  // Display info for plugins in the chain before checking for valid input/output sources
  if(shouldDisplayPluginInfo) {
    pluginChainInspect(pluginChain);
  }

  // Execute any parameter changes
  if(programOptions->options[OPTION_PARAMETER]->enabled) {
    if(!pluginChainSetParameters(pluginChain, programOptionsGetList(programOptions, OPTION_PARAMETER))) {
      return RETURN_CODE_INVALID_ARGUMENT;
    }
  }

  // Setup output source here. Having an invalid output source should not cause the program
  // to exit if the user only wants to list plugins or query info about a chain.
  if((result = setupOutputSource(outputSource)) != RETURN_CODE_SUCCESS) {
    logError("Output source could not be opened, exiting");
    return result;
  }

  // Verify input/output sources. This must be done after the plugin chain is initialized
  // otherwise the head plugin type is not known, which influences whether we must abort
  // processing.
  if(programOptions->options[OPTION_ERROR_REPORT]->enabled) {
    if(charStringIsEqualToCString(inputSource->sourceName, "-", false) ||
       charStringIsEqualToCString(outputSource->sourceName, "-", false)) {
      printf("ERROR: Using stdin/stdout is incompatible with --error-report\n");
      return RETURN_CODE_NOT_RUN;
    }
    if(midiSource != NULL && charStringIsEqualToCString(midiSource->sourceName, "-", false)) {
      printf("ERROR: MIDI source from stdin is incompatible with --error-report\n");
      return RETURN_CODE_NOT_RUN;
    }
  }
  if(outputSource == NULL) {
    logInternalError("Default output sample source was null");
    return RETURN_CODE_INTERNAL_ERROR;
  }
  if(inputSource == NULL || inputSource->sampleSourceType == SAMPLE_SOURCE_TYPE_SILENCE) {
    // If the first plugin in the chain is an instrument, use the silent source as our input and
    // make sure that there is a corresponding MIDI file
    headPlugin = pluginChain->plugins[0];
    if(headPlugin->pluginType == PLUGIN_TYPE_INSTRUMENT) {
      if(midiSource == NULL) {
        // I guess some instruments (like white noise generators etc.) don't necessarily
        // need MIDI, actually this is most useful for our internal plugins and generators.
        // Anyways, this should only be a soft warning for those who know what they're doing.
        logWarn("Plugin chain contains an instrument, but no MIDI source was supplied");
        if(maxTimeInMs == 0) {
          // However, if --max-time wasn't given, then there is effectively no input source
          // and thus processing would continue forever. That won't work.
          logError("No valid input source or maximum time, don't know when to stop processing");
          return RETURN_CODE_MISSING_REQUIRED_OPTION;
        }
        else {
          // If maximum time was given and there is no other input source, then use silence
          inputSource = newSampleSourceSilence();
        }
      }
    }
    else {
      logError("Plugin chain contains only effects, but no input source was supplied");
      return RETURN_CODE_MISSING_REQUIRED_OPTION;
    }
  }

  inputSampleBuffer = newSampleBuffer(getNumChannels(), getBlocksize());
  inputTimer = newTaskTimerWithCString(PROGRAM_NAME, "Input Source");
  outputSampleBuffer = newSampleBuffer(getNumChannels(), getBlocksize());
  outputTimer = newTaskTimerWithCString(PROGRAM_NAME, "Output Source");

  // Initialization is finished, we should be able to free this memory now
  freeProgramOptions(programOptions);

  // If a maximum time was given, figure it out here
  if(maxTimeInMs > 0) {
    maxTimeInFrames = (unsigned long)(maxTimeInMs * getSampleRate()) / 1000l;
  }

  processingDelayInFrames = pluginChainGetProcessingDelay(pluginChain);
  // Get largest tail time requested by any plugin in the chain
  tailTimeInMs += pluginChainGetMaximumTailTimeInMs(pluginChain);
  tailTimeInFrames = (unsigned long)(tailTimeInMs * getSampleRate()) / 1000l + processingDelayInFrames;
  pluginChainPrepareForProcessing(pluginChain);

  // Update sample rate on the event logger
  setLoggingZebraSize((long)getSampleRate());
  logInfo("Starting processing input source");
  logDebug("Sample rate: %.0f", getSampleRate());
  logDebug("Blocksize: %d", getBlocksize());
  logDebug("Channels: %d", getNumChannels());
  logDebug("Tempo: %.2f", getTempo());
  logDebug("Processing delay frames: %lu", processingDelayInFrames);
  logDebug("Time signature: %d/%d", getTimeSignatureBeatsPerMeasure(), getTimeSignatureNoteValue());
  taskTimerStop(initTimer);

  silentSampleInput = sampleSourceFactory(NULL);
  silentSampleOutput = sampleSourceFactory(NULL);
  // Main processing loop
  while(!finishedReading) {
    taskTimerStart(inputTimer);
    finishedReading = !readInput(inputSource, silentSampleInput, inputSampleBuffer, tailTimeInFrames);

    // TODO: For streaming MIDI, we would need to read in events from source here
    if(midiSequence != NULL) {
      LinkedList midiEventsForBlock = newLinkedList();
      // MIDI source overrides the value set to finishedReading by the input source
      finishedReading = !fillMidiEventsFromRange(midiSequence, audioClock->currentFrame, getBlocksize(), midiEventsForBlock);
      linkedListForeach(midiEventsForBlock, _processMidiMetaEvent, &finishedReading);
      pluginChainProcessMidi(pluginChain, midiEventsForBlock);
      freeLinkedList(midiEventsForBlock);
    }
    taskTimerStop(inputTimer);

    if(maxTimeInFrames > 0 && audioClock->currentFrame >= maxTimeInFrames) {
      logInfo("Maximum time reached, stopping processing after this block");
      finishedReading = true;
    }

    pluginChainProcessAudio(pluginChain, inputSampleBuffer, outputSampleBuffer);

    taskTimerStart(outputTimer);
    if(finishedReading) {
      outputSampleBuffer->blocksize = inputSampleBuffer->blocksize;//The input buffer size has been adjusted.
      logDebug("Using buffer size of %d for final block", outputSampleBuffer->blocksize);
    }
    writeOutput(outputSource, silentSampleOutput, outputSampleBuffer, processingDelayInFrames);
    taskTimerStop(outputTimer);
    advanceAudioClock(audioClock, outputSampleBuffer->blocksize);
  }

  // Close file handles for input/output sources
  silentSampleInput->closeSampleSource(silentSampleInput);
  silentSampleOutput->closeSampleSource(silentSampleOutput);
  inputSource->closeSampleSource(inputSource);
  outputSource->closeSampleSource(outputSource);

  // Print out statistics about each plugin's time usage
  // TODO: On windows, the total processing time is stored in clocks and not milliseconds
  // These values must be converted using the QueryPerformanceFrequency() function
  audioClockStop(audioClock);
  taskTimerStop(totalTimer);

  if(totalTimer->totalTaskTime > 0) {
    taskTimerList = newLinkedList();
    linkedListAppend(taskTimerList, initTimer);
    linkedListAppend(taskTimerList, inputTimer);
    linkedListAppend(taskTimerList, outputTimer);
    for(i = 0; i < pluginChain->numPlugins; i++) {
      linkedListAppend(taskTimerList, pluginChain->audioTimers[i]);
      linkedListAppend(taskTimerList, pluginChain->midiTimers[i]);
    }

    totalTimeString = taskTimerHumanReadbleString(totalTimer);
    logInfo("Total processing time %s, approximate breakdown:", totalTimeString->data);
    linkedListForeach(taskTimerList, _printTaskTime, totalTimer);
  }
  else {
    // Woo-hoo!
    logInfo("Total processing time <1ms. Either something went wrong, or your computer is smokin' fast!");
  }
  freeTaskTimer(initTimer);
  freeTaskTimer(inputTimer);
  freeTaskTimer(outputTimer);
  freeTaskTimer(totalTimer);
  freeLinkedList(taskTimerList);
  freeCharString(totalTimeString);

  if(midiSequence != NULL) {
    logInfo("Read %ld MIDI events from %s",
      midiSequence->numMidiEventsProcessed,
      midiSource->sourceName->data);
  }
  else {
    logInfo("Read %ld frames from %s",
      inputSource->numSamplesProcessed / getNumChannels(),
      inputSource->sourceName->data);
  }
  logInfo("Wrote %ld frames to %s",
    outputSource->numSamplesProcessed / getNumChannels(),
    outputSource->sourceName->data);

  // Shut down and free data (will also close open files, plugins, etc)
  logInfo("Shutting down");
  freeSampleSource(inputSource);
  freeSampleSource(outputSource);
  freeSampleBuffer(inputSampleBuffer);
  freeSampleBuffer(outputSampleBuffer);
  pluginChainShutdown(pluginChain);
  freePluginChain(pluginChain);

  if(midiSource != NULL) {
    freeMidiSource(midiSource);
  }
  if(midiSequence != NULL) {
    freeMidiSequence(midiSequence);
  }

  freeAudioSettings();
  logInfo("Goodbye!");
  freeEventLogger();
  freeAudioClock(getAudioClock());

  if(errorReporter->started) {
    errorReporterClose(errorReporter);
  }
  freeErrorReporter(errorReporter);

  return RETURN_CODE_SUCCESS;
}
Example #20
0
//*******************************************************************
int CSolver:: Create(int estRows, int estCols, int estNonZeros,
					 int probsense,  char* probname, int namesize,
					 int nSerialnum,  char* licenvstring)
{
     int  i;
     char buff[100]; 

     setLogFile( (char*)probname); 

     memset( m_error, sizeof(m_error), 0 );
     m_debugLog = 0;

     m_probType    = PROBLEM_TYPE_LP;
     m_estRows     = estRows;
     m_estCols     = estCols;
     m_estNonZeros = estNonZeros;
     m_nObjSense   = probsense;
     m_nNameSize   = namesize;

	 m_nColCount   = 0;
	 m_nRowCount   = 0;

     // create arrays given problem size estimates
     // matrix
     m_pRowNdx    = new int[estNonZeros];
     m_pColNdx    = new int[estNonZeros];
     m_pCoef      = new double[estNonZeros];

     m_nRowItems  = 0;
     m_nColItems  = 0;
     m_nCoefItems = 0;

     // rim
     m_pObj       = new double[estCols];
     m_pRhs       = new double[estRows];
     m_pRhsSense  = new char[estRows];

     m_pCtype     = new char[estCols];  // column type
     m_pRstat     = new int[estRows];
     m_pCstat     = new int[estCols];

     m_nObjItems  = 0;
     m_nRhsItems  = 0;
     m_nRhsSense  = 0;

     // column bounds
     m_pBdl      = new double[estCols];
     m_pBdu      = new double[estCols];

     m_nBdItems   = 0;

     if (m_pBdl == NULL || m_pBdu == NULL ) return -1;

     for( i=0; i< estCols; i++ ) {
	      m_pBdl[i] = 0.0;
	      m_pBdu[i] = INFBOUND;
     }

     //---misc
     // build problem name string

     if( probname != NULL ) {
	 // user supplied a problem name on construction, so use that name
	 m_pszProbname = new char[strlen(probname)+1];

	 strcpy(m_pszProbname,probname);
     }
     else {
	     // no name given for problem
	     m_pszProbname = new char[strlen("NONAME")+1];
	     strcpy(m_pszProbname,"NONAME");
     }


     m_lp      = NULL;
     m_env     = NULL;
     m_obj     = 0;
     m_x       = NULL;
     m_pi      = NULL;
     m_slack   = NULL;
     m_dj      = NULL;

     m_nPosInCstore =0;
     m_cstore=NULL;
     m_nPosInCname  =0;
     m_cname=NULL;

     m_nPosInRstore =0;
     m_rstore=NULL;
     m_nPosInRname  =0;
     m_rname=NULL;

     m_RowMap.Create(estRows);
	 m_ColMap.Create(estCols);


     CreateNameSpace();

	 // check for memory allocation error
     if( m_pRowNdx == NULL  ||
	 m_pColNdx == NULL  ||
	 m_pCoef   == NULL  ||
	 m_pObj    == NULL  ||
	 m_pRhs    == NULL  ||
	 m_pRhsSense ==NULL ||
	 m_pBdl    == NULL  ||
	 m_pBdu    == NULL  ||
	 m_cstore  == NULL  ||
	 m_cname   == NULL  ||
	 m_rstore  == NULL  ||
	 m_rname   == NULL  ) {
	 Message("Not enough memory!");
		 return -1;  // failure error
	 }
	 sprintf(buff,"CPLEX Serial Number = %d", nSerialnum);
     
	 Message(buff);

//!     if ( nSerialnum == 0  )  
//!        // no serial number assume development license
//!    else
//!        // serial number provide assume runtime license
     m_env = CPXopenCPLEXruntime(&m_status, nSerialnum, licenvstring);

     if (m_env == NULL){
		  CPXgeterrorstring( m_env, m_status, m_error );
		  if (nSerialnum == 0 )
	          Message( "CPXopenCPLEXdevelop returned NULL !");
		  else
			  Message( "CPXopenCPLEXruntime returned NULL");
		  SetError("Failed to get a CPLEX environment");
          return -1;
     }

     CPXgetchannels(m_env, &m_cpxresults, &m_cpxwarning, &m_cpxerror, &m_cpxlog);

     char cpxbuff[80];

	 sprintf(cpxbuff, "%s.%s", probname, "cpx");

	 m_cpxFile = CPXfopen(cpxbuff,"w");

	 if (m_cpxFile == NULL ) {
         m_log.write("opening cplexlog.log failed");
	 }

	 CPXaddfuncdest(m_env, m_cpxresults, &m_cbData, channelsfunc);
	 CPXaddfuncdest(m_env, m_cpxwarning, &m_cbData, channelsfunc);
	 CPXaddfuncdest(m_env, m_cpxerror,   &m_cbData, channelsfunc);

     if ( CPXsetlogfile(m_env, m_cpxFile) != 0 ) {
          m_log.write("failed to set channels file");
      }

	 m_log.getTimeStamp(buff);

     m_bCreated    = 1;

     CPXmsg(m_cpxlog, "%s : %s\n\n","*** Begin Log ***", buff );

     return 0;
}
Example #21
0
bool Process::run(JT::ObjectNode **returnedObjectNode)
{
    if (returnedObjectNode)
        *returnedObjectNode = 0;

    if (!m_project_name.size() || !m_phase.size()) {
        fprintf(stderr, "project name  or phase is empty when executing command: %s : %s\n",
                m_project_name.c_str(), m_phase.c_str());
        return false;
    }

    bool return_val = true;

    LogFileResetter resetter(*this);
    if (m_log_file < 0 && Configuration::isDir(m_configuration.buildShellMetaDir())) {
        Configuration::ensurePath(m_configuration.scriptExecutionLogDir());
        std::string log_file_str = m_configuration.scriptExecutionLogDir() +  "/" + m_project_name + "_" + m_phase + ".log";
        setLogFile(log_file_str, false);
        resetter.resetLog = true;
    }

    std::string temp_file;

    if (!flushProjectNodeToTemporaryFile(m_project_name, m_project_node, temp_file))
        return false;
    std::string primary_script = m_phase + "_" + m_project_name;
    std::string fallback_script = m_fallback.size() ? m_phase + "_" + m_fallback : "";

    auto scripts = m_configuration.findScript(primary_script, fallback_script);

    if (m_script_has_to_exist && scripts.size() == 0) {
        fprintf(stderr, "Could not find mandatory script for: \"%s\" with fallback \"%s\"\n",
                primary_script.c_str(), fallback_script.c_str());
        return false;
    }

    bool temp_file_removed = false;

    std::string arguments =  m_project_name + " " + temp_file;
    for (auto it = scripts.begin(); it != scripts.end(); ++it) {
        int exit_code = runScript(m_environement_script, (*it), arguments,  m_log_file);
        if (exit_code) {
            fprintf(stderr, "Script %s for project %s failed in execution\n", it->c_str(), m_project_name.c_str());
            return_val = false;
            break;
        }
        if (access(temp_file.c_str(), F_OK)) {
            temp_file_removed = true;
            fprintf(stderr, "The script removed the temporary input file, assuming failur\n");
            return_val = false;
            break;
        }
        if (returnedObjectNode) {
            TreeBuilder tree_builder(temp_file);
            tree_builder.load();
            JT::ObjectNode *root = tree_builder.rootNode();
            if (root) {
                if (root->booleanAt("arguments.propogate_to_next_script"))
                    continue;
                *returnedObjectNode = tree_builder.takeRootNode();
            } else  {
                fprintf(stderr, "Failed to demarshal the temporary file returned from the script %s\n", (*it).c_str());
                return_val = false;
            }
        }
        break;
    }
    if (!temp_file_removed) {
        unlink(temp_file.c_str());
    }

    return return_val;
}