Exemplo n.º 1
0
int main(int argc, char **argv)
{
    int retval( EXIT_FAILURE );
    Environment.add( "WIPFC" );
    if( Environment.value( "WIPFC" ).empty() ) {
        printBanner();
        std::cout << "The 'WIPFC' environment variable needs to be set. ";
        std::cout << "It should contain the name of the directory containing .nls and entity.txt" << std::endl;
        return retval;
    }
    Environment.add( "IPFCARTWORK" );
    Environment.add( "IPFCIMBED" );
    Environment.add( "TMP" );
    Compiler c;
    try {
        processCommandLine(argc, argv, c);
        if( c.banner() ) {
            printBanner();
        }
        retval = c.compile();
    }
    catch( FatalError& e ) {
        c.printError( e.code );
    }
    catch( FatalIOError& e ) {
        c.printError( e.code, e.fname );
    }
    return retval;
}
Exemplo n.º 2
0
/*
 * The login page. 
 * If error evaluates to true, show the user that the login failed
 */
void loginPage(int error){
    //Start of the page
    printHeader();
    printNavbar();
    startBody();
    divClass("centered");
    printBanner();
    
    //begin sign in display
    printf("<h1>Please sign in below to view the temperature recordings.</h1>\n");
    divClass("frame"); divClass("inFrame");
    
    if (error) //If Login Failed
        printf("<font color=\"#990000\">There was an error, try again.</font>");
    
    printf("<form action=\"\" method=\"get\" onSubmit=\"window.location.reload()\">\n" );
    input("text", "user", "Username");
    br();
    input("password" ,"pass", "Password");
    br();br();

    printf ("<input type=\"submit\" value=\"Sign In!\" class=\"btn\">\n");
    button("./temp-cgi/login.cgi", "float-right", "Sign Up!");
    printf("</form>\n");
    
    //End login form and fill out the rest of the page
    endDiv(); endDiv();
    endDiv();
    endBody();
    printFooter();
}
Exemplo n.º 3
0
void main( int argc, char *argv[] ) {
    Parameters          param;
    ExeFile             exeFile;
    bool                ret;

    ret = true;
    defaultParam( &param );
    exeFile.file = NULL;
    exeFile.tabEnt = NULL;

    printBanner();
    if( argc > 1 ) {
        ret = loadParam( &param, argc, argv );
    } else {
        printHelp();
        ret = false;
    }

    if( ret )   ret = openExeFile( &exeFile, &param );
    if( ret )   ret = readExeHeaders( &exeFile );
    if( ret )   {
                printDosHeader( &exeFile, &param );
                printPeHeader( &exeFile, &param );
                ret = findResourceObject( &exeFile );
    }
    if( ret )   ret = loadAllResources( &exeFile );
    if( ret )   {
                printResObject( &exeFile, &param );
                printTableContents( exeFile.tabEnt, &exeFile,
                                    &param, exeFile.resObj.physical_offset,
                                    0 );
    }
    freeAllResources( &exeFile );
}
Exemplo n.º 4
0
GammaComboEngine::GammaComboEngine(TString name, int argc, char* argv[])
{
    // time the program
    t.Start();

    // print the copyright banner
    printBanner();

    // parse the command line options
    arg = new OptParser();
    arg->bookAllOptions();
    arg->parseArguments(argc, argv);

    // configure names
    execname = argv[0];
    if (arg->filenameaddition!="") name += "_"+arg->filenameaddition;
    m_fnamebuilder = new FileNameBuilder(arg, name);

    // make batch scripts if appropriate and exit
    m_batchscriptwriter = new BatchScriptWriter(argc, argv);

    // run ROOT in interactive mode, if requested (-i)
    if ( arg->interactive ) theApp = new TApplication("App", &argc, argv);
    else gROOT->SetBatch(false);

    // initialize members
    plot = 0;
}
int main(int argc, char *argv[])
{
    //Force printf to print text to terminal
    setvbuf(stdout, NULL, _IONBF, 0);
    AnsiCls();
    AnsiSetColor(ANSI_ATTR_OFF,ANSI_BLACK,ANSI_GREEN);
    printBanner();


    //Main application code
    RobotApp(argc,argv);

    return 0;
}
Exemplo n.º 6
0
int main(int argc, char **argv) {
    int i, ret;
    const char *fileName;
    const char *sumFile;
	int got_stdin = 0;
    
    struct stat x; /* Not really used */    
    
    if(argc < 2 || !strncmp("--help", argv[1], 6)) {
        printUsage();
        return 1;
    }
    
    if(!strncmp("-v", argv[1], 2) || !strncmp("--version", argv[1], 9)) {
        printBanner();
        return 0;
    }
    
    if(!strncmp("-c", argv[1], 2)) {
        sumFile = argv[2];
        argc -= 2;
        argv +=2;
        ret = checkSHA256(sumFile);
    
    } else {
        for(i = 1; i < argc; i++) {
            fileName = argv[i];
			if(!strncmp("-", fileName, 1) || !strncmp("/dev/stdin", fileName, 10)) {
				if(got_stdin) {
					fprintf(stderr, "WARNING: stdin twice in command line, skipping...\n");
                    fflush(stderr);
					continue;
				} else {
					got_stdin = 1;
				}
			} else {
	            if(stat(fileName, &x) < 0) {
	                fprintf(stderr, "ERROR: file cannot be opened: %s : %s\n", fileName, strerror(errno));
	                fflush(stderr);
	                continue;
	            }
			}
            ret = printSHA256(fileName);
        }
       
    }
    return ret; 
}
Exemplo n.º 7
0
void ffmpeg_version() {
	printBanner();
	// output build and version numbers
	fprintf(stderr, "libav versions:\n");
	fprintf(stderr, "  libavutil version:   %s\n", AV_STRINGIFY(LIBAVUTIL_VERSION));
	fprintf(stderr, "  libavutil build:     %d\n", LIBAVUTIL_BUILD);
	fprintf(stderr, "  libavcodec version:  %s\n", AV_STRINGIFY(LIBAVCODEC_VERSION));
	fprintf(stdout, "  libavcodec build:    %d\n", LIBAVCODEC_BUILD);
	fprintf(stderr, "  libavformat version: %s\n", AV_STRINGIFY(LIBAVFORMAT_VERSION));
	fprintf(stderr, "  libavformat build:   %d\n", LIBAVFORMAT_BUILD);
	
	fprintf(stderr, "This tool is version " PROGRAM_VERSION ",  built on " __DATE__ " " __TIME__);
	#ifdef __GNUC__
	fprintf(stderr, ", with gcc: " __VERSION__ "\n");
	#else
	fprintf(stderr, ", using a non-gcc compiler\n");
	#endif
}
Exemplo n.º 8
0
int main(int argc, const char** argv) {
  // Initialization
  if (argc < 3) {
    printBanner();
    return -1;
  }

  Passenger *passengers = NULL, *max_passenger = NULL;
  Flight *flights = NULL, *max_flight = NULL;
  int passengers_size = 0, flights_size = 0;

  readData(argv[1], &passengers, &passengers_size);

  // Error handling
  if (passengers == NULL) {
    printf("Incorrect passenger file format.\n");
    return -1;
  }
  if (passengers_size == 0) {
    printf("Passenger file must contain at least one record.\n");
    freePassengers(passengers);
    return -1;
  }

  // Core logic
  max_passenger = passengerWithMaxItems(passengers, passengers_size);
  flights = mapFlights(passengers, passengers_size, &flights_size);
  max_flight = flightWithMaxWeight(flights, flights_size);

  // Output
  printResults(argv[2], max_passenger, max_flight);

  // Finalization
  freeFlights(flights, flights_size);
  freePassengers(passengers, passengers_size);
  return 0;
}
Exemplo n.º 9
0
/**
	* @brief main, to list test or execute them
	*/
int main( int argc, char* argv[] )
{
    TestRunner aTestRunner(&gTestRoot);
    std::string testPath; // default is root
    aTestRunner.SetInteractiveMode( true ); // default behaviour is all test including interactive ones

    // Setup a nice formatter for log
    RefPtr<BALFacilities::BTDeviceChannel> channel = new BALFacilities::BTDeviceChannel;
    RefPtr<BALFacilities::BTTextLogFormatter> textLogFormatter = new BALFacilities::BTTextLogFormatter;
    channel->setFormatter(textLogFormatter.get());
#ifndef NDEBUG
    BALFacilities::logger.addChannel(channel.get());
#endif

    printf("Origyn test runner:\n");

    TestNode* aTestNode=NULL;
    bool bExecute = true; // if false, just display.
    for(int i=1; i<argc; i++)
    {
      if( std::string("-h") == argv[i] )
      {
        printBanner( argv );
        TestManager::deleteInstance();
        return 1;
      }
      else if ( std::string("-l") == argv[i] )
      {
        bExecute = false;
      }
      else if ( std::string("-a") == argv[i] )
      {
        aTestRunner.SetInteractiveMode( false );
      }
      else if ( std::string("-p") == argv[i] )
      {
        TestManager::GetInstance().setPath(argv[i+1]);
        i++;
      }
      else if( aTestRunner.FindNode( argv[i], &aTestNode ) )
      {
        ; // do nothing
      }
      else
      {
        printf("Unknown argument %s\n", argv[i]);
        printBanner(argv);
        TestManager::deleteInstance();
        return 2;
      }
    }

    if( bExecute ) {
        aTestRunner.ExecuteTestTree(aTestNode);

        printf("RESULT OK %d FAILED %d\n",
          aTestRunner.GetTestManager().GetTestResult().mTheOkTotal,
          aTestRunner.GetTestManager().GetTestResult().mTheFailureTotal);

    } else {
        aTestRunner.DisplayTestTree(aTestNode);
        TestManager::deleteInstance();
        return 1;
    }

    bool bWasSuccessfull = aTestRunner.GetTestManager().GetTestResult().mTheFailureTotal == 0;
    TestManager::deleteInstance();
    return bWasSuccessfull ? 0 : 1;
}
Exemplo n.º 10
0
/*
ipfc 1.0 flags are:
    /INF -- generate an *.inf file
    /S ---- suppress search table generation
    /X ---- generate cross-reference list
    /Wn --- warning level n
    /COUNTRY=nnn
    /CODEPAGE=nnn
    /LANGUAGE=XYZse
ipfc 2.0 flags are:
    -i ------- generate an *.inf file
    -s ------- suppress search table generation
    -x ------- generate cross-reference list
    -Wn ------ set warning level
    -d:nnn --- set 3 digit country code
    -c:nnnn -- set 4 digit code page
    -l:xyz  -- set 3 letter language identifier
    -X:? ----- help on option '?'

We support the version 2 flags
*/
static void processCommandLine(int argc, char **argv, Compiler& c)
{
    if (argc < 2)
        usage();
    int inIndex( 0 );
    int outIndex( 0 );
    bool info( false );
    for( int count = 1; count < argc; ++count ) {
#ifdef __UNIX__
        if( argv[count][0] == '-' ) {
#else
        if( argv[count][0] == '-' || argv[count][0] == '/' ) {
#endif
            switch( argv[count][1] ) {
                case 'C':
                case 'c':
                case 'd':
                    std::cout << "Country code and code page selection are not supported." << std::endl;
                    std::cout << "Use the 'l' option to select a localization file instead." << std::endl;
                    if (argv[count][2] == '?')
                        info = true;
                    break;
                case 'I':
                case 'i':
                    c.setOutputType( Compiler::INF );
                    break;
                case 'L':
                case 'l':
                    if (argv[count][2] == '?') {
                        std::cout << "xx_YY is the root name of a localization file" << std::endl;
                        std::cout << "with the full name xx_YY.nls\nSee en_US.nls for an example." << std::endl;
                        info = true;
                    }
                    else
                        c.setLocalization( argv[++count] );
                    break;
                case 'O':
                case 'o':
                    outIndex = ++count;
                    break;
                case 'Q':
                case 'q':
                    c.noBanner();
                    break;
                case 'S':
                case 's':
                    c.noSearch();
                    break;
                case 'w':
                case 'W':
                    if (argv[count][2] == '?') {
                        std::cout << "-wN where N is one of 1, 2, or 3" << std::endl;
                        info = true;
                    }
                    else
                        c.setWarningLevel( std::atoi( argv[count] + 2 ));
                    break;
                case 'X':
                case 'x':
                    c.setXRef( true );
                    break;
                default:
                    usage();
                    break;
            }
        }
        else if( !inIndex )
            inIndex = count;
        else
            std::cout << "Warning: extra filename '" << argv[count] << "' will be ignored" << std::endl;
    }
    if( inIndex ) {
        std::string fullpath( canonicalPath( argv[ inIndex ] ) );
        c.setInputFile( fullpath );
        if( !outIndex ) {
            std::string outFile( fullpath );
            outFile.erase( outFile.rfind( '.' ) );
            if( c.outputType() == Compiler::INF )
                outFile += ".inf";
            else
                outFile += ".hlp";
            c.setOutputFile( outFile );
        }
    }
    else {
        std::cout << "Fatal Error: You must specify an input file" << std::endl;
        std::exit( EXIT_FAILURE );
    }
    if( outIndex ) {
        std::string fullpath( canonicalPath( argv[ outIndex ] ) );
        c.setOutputFile( fullpath );
    }
    if( info )
        std::exit( EXIT_SUCCESS );
}
/*****************************************************************************/
static void usage()
{
    printBanner();
    std::cout << "Usage:" << std::endl;
    std::cout << "wipfc [-switches] [-options] infile [outfile]" << std::endl;
    std::cout << std::endl;
    std::cout << "Switches" << std::endl;
    std::cout << "-i  generate outfile.inf instead of outfile.hlp" << std::endl;
    std::cout << "-s  do not generate full text search tables" << std::endl;
    std::cout << "-x  generate and display cross-reference list" << std::endl;
    std::cout <<  std::endl;
    std::cout << "Options\n" << std::endl;
    std::cout << "-l xx_YY localization code (default: en_US)" << std::endl;
    std::cout << "-o name  set the output file path, name and extension" << std::endl;
    std::cout << "-q       operate quietly" << std::endl;
    std::cout << "-wn      1 digit warning level  (default: 3)" << std::endl;
    std::cout << "-X?      display help on option X" << std::endl;
    std::exit( EXIT_FAILURE );
}
Exemplo n.º 11
0
bool TestRunner::run(const std::vector<std::string>& args)
{
	std::string testCase;
	int numberOfTests = 0;
	bool success = true;
	bool all     = false;
	bool wait    = false;
	bool printed = false;

	for (int i = 1; i < args.size(); i++) 
	{
		const std::string& arg = args[i];
		if (arg == "-wait") 
		{
			wait = true;
			continue;
		}
		else if (arg == "-all")
		{
			all = true;
			continue;
		}
		else if (arg == "-print")
		{
			for (Mappings::iterator it = _mappings.begin(); it != _mappings.end(); ++it) 
			{
				print(it->first, it->second, 0);
			}
			printed = true;
			continue;
		}

		if (!all)
		{
			testCase = arg;

			if (testCase == "")
			{
				printBanner();
				return false;
			}

			Test* testToRun = 0;
			for (Mappings::iterator it = _mappings.begin(); !testToRun && it != _mappings.end(); ++it) 
			{
				testToRun = find(testCase, it->second, it->first);
			}
			if (testToRun)
			{
				if (!run(testToRun)) success = false;
			}
			numberOfTests++;

			if (!testToRun) 
			{
				_ostr << "Test " << testCase << " not found." << std::endl;
				return false;
			}
		}
	}

	if (all)
	{
		for (Mappings::iterator it = _mappings.begin(); it != _mappings.end(); ++it) 
		{
			if (!run(it->second)) success = false;
			numberOfTests++;
		}
	}
	
	if (numberOfTests == 0 && !printed) 
	{
		printBanner();
		return false;
	}

	if (wait) 
	{
		_ostr << "<RETURN> to continue" << std::endl;
		std::cin.get();
	}

	return success;
}
Exemplo n.º 12
0
/**
 * Application entry point. Configures the peripherals and starts the echo 
 * server.
 * 
 * For a description of parameters, please refer to the file description.
 * 
 * \return 0 if successful, -1 in case of any error.
 */
int	main(int argc, char *argv[])
{
	/* The client parameters specified by the user. */
	static ClientParams clientParams;
	/* The client statistics. */
	static ClientStats clientStats;

	/* The socket for sending/receiving the echo. */
	int echoSocket;
	/* Address of the echo server. */
	struct sockaddr_in echoServer;
	/* Address received by the echo client. */
	struct sockaddr_in echoClient;
	/* Length of the address received by echo client. */
	uint32_t clientLength = sizeof(struct sockaddr_in);

	/* Time stamp before sending the echo request. */
	struct timeval timeBeforeSend;
	/* Time stamp after receiving the echo response. */
	struct timeval timeAfterReceive;

	/* ID of the current fork. */
	uint32_t forkNr = 0;
	/* Macro for logging debug messages to the console. */
#define LOGMSG(format,args...) printf("[%d] " format "\n", forkNr, ##args)

	printBanner();
	
	/* Parse program options. */
	if (!parseUserInput(argc, argv, &clientParams))
	{
		printUsage();
		return -1;
	}
	if (clientParams.showHelp)
	{
		printUsage();
		return 0;
	}
	if (clientParams.showLicense)
	{
		printLicense();
		return 0;
	}

	/* Create the requested number of forks. */
	if (clientParams.numForks)
	{
		pid_t pid;
		do
		{
			if ((pid = fork()) == 0)
			{
				break;
			}
			forkNr++;
			clientParams.numForks--;
		}
		while (clientParams.numForks);
	}

	/* Create the echo request and response buffers. */
	uint8_t *echoRequest;
	uint8_t *echoResponse = malloc(clientParams.echoLength);
	if (!echoResponse)
	{
		LOGMSG("*** Error allocating echo response buffer.");
		return -1;
	}

	/* Create the UDP socket. */
	echoSocket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (echoSocket < 0)
	{
		LOGMSG("*** Error creating echo socket.");
		return -1;
	}

	/* Create the echo server address. */
	memset(&echoServer, 0, sizeof(echoServer));
	echoServer.sin_family      = AF_INET;
	echoServer.sin_addr.s_addr = clientParams.serverAddr;
	echoServer.sin_port        = htons(7);

	/* Prepare the stats. */
	clientStats.numErrors   = 0;
	clientStats.maxTime     = 0;
	clientStats.minTime     = 0xFFFFFFFF;
	clientStats.averageTime = 0;
	clientStats.elapsedTime = malloc(sizeof(uint32_t) * clientParams.numIterations);
	if (!clientStats.elapsedTime)
	{
		LOGMSG("*** Error allocating memory.");
		return -1;
	}

	/* Loop through the number of selected iterations. */
	uint32_t iter; for (iter = 0; iter < clientParams.numIterations; iter++)
	{
		LOGMSG("Iteration %d/%d.", iter + 1, clientParams.numIterations);

		/* Prepare the echo request message. */
		echoRequest = getEchoRequest(clientParams.echoLength);
		clientStats.elapsedTime[iter] = 0;

		/* Send the data to the echo server. */
		LOGMSG("Sending %d characters to %s...",
				clientParams.echoLength, clientParams.serverAddrString);

		gettimeofday(&timeBeforeSend, NULL);

		int32_t requestLength = sendto(echoSocket, echoRequest,
				clientParams.echoLength, 0, (struct sockaddr *)&echoServer,
				sizeof(echoServer));

		if (requestLength != clientParams.echoLength)
		{
			LOGMSG("*** Error sending echo request.");
			clientStats.numErrors++;
			continue;
		}

		/* Set timeout for echo reception. */
		if (sigsetjmp(receiveTimeout, 1))
		{
			LOGMSG("*** Timeout while waiting for echo.");
			clientStats.numErrors++;
			continue;
		}

		signal(SIGALRM, receiveTimeoutHandler);
		alarm(ECHO_RECEIVE_TIMEOUT);

		/* Wait for the echo response. */
		int32_t responseLength = recvfrom(echoSocket, echoResponse,
				clientParams.echoLength, 0,	(struct sockaddr *)&echoClient,
				&clientLength);

		/* Clear the timeout alarm and remember the time. */
		alarm(0);
		signal(SIGALRM, SIG_DFL);
		gettimeofday(&timeAfterReceive, NULL);

		/* Check the echo response. */
		if (responseLength == -1)
		{
			LOGMSG("*** Echo receive error: %s", strerror(errno));
			continue;
		}
		if (responseLength != clientParams.echoLength)
		{
			LOGMSG("*** Echo size mismatch: received %d bytes, expected %d.",
					responseLength, clientParams.echoLength);
			clientStats.numErrors++;
			continue;
		}
		if (echoServer.sin_addr.s_addr != echoClient.sin_addr.s_addr)
		{
			LOGMSG("*** Received unexpected echo from %s, expected %s.",
					inet_ntoa(echoClient.sin_addr), inet_ntoa(echoServer.sin_addr));
			clientStats.numErrors++;
			continue;
		}
		if (memcmp(echoRequest, echoResponse, responseLength) != 0)
		{
			LOGMSG("*** Echo data mismatch.");
			clientStats.numErrors++;
			continue;
		}

		/* Remember the echo duration. */
		clientStats.elapsedTime[iter] = getElapsedTime(&timeBeforeSend,
				&timeAfterReceive);
		LOGMSG("Received echo after %u milliseconds.",
				clientStats.elapsedTime[iter]);

		/* Calculate the statistics. */
		clientStats.averageTime += clientStats.elapsedTime[iter];
		if (clientStats.elapsedTime[iter] > clientStats.maxTime)
		{
			clientStats.maxTime = clientStats.elapsedTime[iter];
		}
		if (clientStats.elapsedTime[iter] < clientStats.minTime)
		{
			clientStats.minTime = clientStats.elapsedTime[iter];
		}
	}

	/* Calculate the statistics. */
	if (clientParams.numIterations > clientStats.numErrors)
	{
		clientStats.averageTime = clientStats.averageTime /
				(clientParams.numIterations - clientStats.numErrors);
	}
	else
	{
		clientStats.averageTime = clientStats.maxTime;
	}

	/* Print the statistics. */
	printf("\n");
	LOGMSG("Finished with %d errors.", clientStats.numErrors);
	LOGMSG("Echo length = %d bytes: Avg = %d ms, Min = %d ms, Max = %d ms.",
			clientParams.echoLength, clientStats.averageTime, clientStats.minTime,
			clientStats.maxTime);
	printf("\n");

	return 0;
}
Exemplo n.º 13
0
/*Command line entry point of the program*/
int main (int argc, char* argv[]){
    
    /*getopt() variables */
    int   opt;
	char* optarg_dup = NULL;
    
    /*Command line options*/
	uchar cflg=0,gflg=0,kflg=0,lflg=0,mflg=0,oflg=0, sflg=0;
	uchar pflg=0,tflg=0,vflg=0,xflg=0,zflg=0;
    InputParams* inputParams = NULL;

    /*Working variables */
	int            i,m;
	int            nbPriors;
    int            nbNodes;
	int            nbClass;
	int            nbLabeled;
	int            nbUnlabeled;
	int			   nbSimParams;
	int            actualWlen;
	int            start_cpu,stop_cpu;
	real           tmp;
	uchar*         absorbing     = NULL;
	char*          labels        = NULL;
	char*          featLabels    = NULL;
	char*          targets       = NULL;
	char*		   preds         = NULL;
	int**          classes       = NULL;
	real**         N             = NULL;
	real*          gram          = NULL;
    real**         latF          = NULL;
    real**         latB          = NULL;
	real**		   kernel		 = NULL;
	SparseMatrix*  spmat         = NULL;
	SparseMatrix*  dataset       = NULL;
	DataStat*      graphStat     = NULL;
	DataStat*      featuresStat  = NULL;
	DWInfo*        dwInfo        = NULL;
	OptiLen*       optiLen       = NULL;
	PerfMeasures*  unlabeledPerf = NULL;
	LSVMDataInfo*  dataInfo      = NULL;
	
	/*Print the program banner*/
	printBanner();

    /*Scan the command line*/
	inputParams = malloc(sizeof(InputParams));
	init_InputParams(inputParams);
	while ((opt = getopt(argc,argv,"c:g:l:xms:k:o:p:rt:v:z:h")) != EOF){
        switch(opt){
	        case 'c':
	            cflg++;
				inputParams->nbFolds = atoi(optarg);
	            break;
            case 'g':
                gflg++;
				inputParams->graphFname = (char*)malloc(FNAME_LEN*sizeof(char));
				strncpy(inputParams->graphFname,optarg,FNAME_LEN);
                break;
            case 'k':
				kflg++;
				inputParams->gramFname = (char*)malloc(FNAME_LEN*sizeof(char));
				strncpy(inputParams->gramFname,optarg,FNAME_LEN);
                break;
			case 's':
                sflg++;
                optarg_dup  = (char*)__strdup(optarg);
				nbSimParams = getNbTokens(optarg,",");
				inputParams->simParams = vec_alloc(nbSimParams+1);
				tokenizeReals(optarg_dup,",",inputParams->simParams);
				break;
            case 'l':
                lflg++;
                inputParams->wlen = atoi(optarg);
                break;
			case 'm':
				mflg++;
				break;
            case 'o':
                oflg++;
				inputParams->outFname = (char*)malloc(FNAME_LEN*sizeof(char));
				strncpy(inputParams->outFname,optarg,FNAME_LEN);
				inputParams->outPRED  = (char*)malloc(FNAME_LEN*sizeof(char));
				inputParams->outLEN   = (char*)malloc(FNAME_LEN*sizeof(char));
                addExtension(inputParams->outFname,"pred",inputParams->outPRED);
				addExtension(inputParams->outFname,"len",inputParams->outLEN);
                break;
            case 'p':
                pflg++;
                optarg_dup = (char*)__strdup(optarg);
				nbPriors   = getNbTokens(optarg,"#");
                inputParams->priors = vec_alloc(nbPriors+1);
				tokenizeReals(optarg_dup,"#",inputParams->priors);
                break;
			case 't':
				tflg++;
				inputParams->tarFname = (char*)malloc(FNAME_LEN*sizeof(char));
				strncpy(inputParams->tarFname,optarg,FNAME_LEN);
				break;
            case 'v':
                vflg++;
                inputParams->verbose = atoi(optarg);
                break;
			case 'x':
				xflg++;
				inputParams->crossWalks = 1;
				break;
			case 'z':
				zflg++;
				inputParams->cvSeed = atoi(optarg);
				break;
            case 'h':
                printHelp();
                exit(EXIT_FAILURE);
                break;
        }
    }
    
    /*Check mandatory arguments*/
    if(!gflg || !lflg || (!oflg && !mflg)){
        fprintf(stderr,"Mandatory argument(s) missing\n");
        printHelp();
        exit(EXIT_FAILURE);
    }

	if( (kflg && !sflg) || (!kflg && sflg)){
		fprintf(stderr, "Error with 'k' and 's' parameters\n");
		printHelp();
		exit(EXIT_FAILURE);
	}

	/*Check that the walk length is greater than 2*/
	if(inputParams->wlen < 2){
		fprintf(stderr,"The walkLen must be >= 2\n");
		exit(EXIT_FAILURE);
	}

	/*Check that there are the right number of similarity parameters*/
	if (kflg && sflg){
		if(inputParams->simParams){
			switch((int)inputParams->simParams[1]){
				case 1 :
					if((int)inputParams->simParams[0] != 1){
						fprintf(stderr,"The similarity type 1 must have no parameters\n");
						exit(EXIT_FAILURE);	
					}
					break;
				case 2 :
					if((int)inputParams->simParams[0] != 2){
						fprintf(stderr,"The similarity type 2 must have exactly 1 parameter\n");
						exit(EXIT_FAILURE);	
					}
					break;
				case 3 :
					if((int)inputParams->simParams[0] != 4){
						fprintf(stderr,"The similarity type 3 must have exactly 3 parameters\n");
						exit(EXIT_FAILURE);	
					}
					break;
				case 4 :
					if((int)inputParams->simParams[0] != 2){
						fprintf(stderr,"The similarity type 4 must have exactly 1 parameter\n");
						exit(EXIT_FAILURE);	
					}
					break;
				default :
					fprintf(stderr,"Unrecognized similarity type\n");
					exit(EXIT_FAILURE);	
			}
		}
	}

    /*Get the number of nodes in the graph*/
    nbNodes = readNbNodes(inputParams->graphFname);
    
	/*Get the number of distinct classes*/
	nbClass = readNbClass(inputParams->graphFname);

	/*Get info from the LIBSVM data*/
	if (kflg){
		dataInfo = malloc(sizeof(LSVMDataInfo));
		getLSVMDataInfo(inputParams->gramFname,dataInfo);
		dataset = spmat_alloc(dataInfo->nbLines,dataInfo->nbFeatures,0);
		init_SparseMat(dataset);
		featuresStat = DataStat_alloc(dataInfo->nbClass);
		featLabels = char_vec_alloc(nbNodes);
	}
	
	/*Check if the number of nodes does not exceed the limitation*/
	if(nbNodes > MAX_NODES){
		fprintf(stderr,"This version is limited to maximum %i nodes\n",MAX_NODES);
		exit(EXIT_FAILURE);
	}

	/*Check that the number of classes is lower than 128*/
	if(nbClass > 127){
		fprintf(stderr,"The number of classes must be <= 127\n");
		exit(EXIT_FAILURE);		
	}

	/*Check that the number of folds is between 2 and nbNodes*/
	if(cflg){
		if(inputParams->nbFolds == 1 || inputParams->nbFolds > nbNodes){
			fprintf(stderr,"The number of folds must be > 1 and <= number of nodes\n");
			exit(EXIT_FAILURE);
		}
	}

    /*Allocate data structure*/
    latF             = mat_alloc(inputParams->wlen+1,nbNodes);
    latB             = mat_alloc(inputParams->wlen+1,nbNodes);
	kernel			 = mat_alloc(nbNodes, nbNodes);
	classes          = (int**)malloc(sizeof(int*)*(nbClass+1));
	labels           = char_vec_alloc(nbNodes);
	absorbing        = uchar_vec_alloc(nbNodes);
	if(kflg) gram    = vec_alloc((nbNodes*(nbNodes+1))/2);
	dwInfo           = malloc(sizeof(DWInfo));
	dwInfo->mass_abs = vec_alloc(nbClass);
	spmat            = spmat_alloc(nbNodes,nbNodes,1);
	graphStat        = DataStat_alloc(nbClass+1);
	optiLen          = malloc(sizeof(OptiLen));
	
    /*Initialize the sparse transition matrix and the dataset if required*/
	init_SparseMat(spmat);

    /*Read the adjacency matrix*/
    readMat(inputParams->graphFname,spmat,labels,graphStat,inputParams->verbose);
    isSymmetric(spmat);

	/*Get the indices of the nodes in each class */
	getClasses(labels,nbNodes,classes,nbClass);

	/*Get the number of labeled nodes*/
	nbUnlabeled = classes[0][0];
	nbLabeled   = nbNodes - nbUnlabeled;

	/*If provided, check that the priors match the number of classes*/
	if(pflg){
		if(nbClass != nbPriors){
			printf("The number of priors does not match with the number of classes\n");
			exit(EXIT_FAILURE);			
		}
		/*Check that the priors sum up to 1*/
		else{
			tmp=0.0;
			for(i=1;i<=inputParams->priors[0];i++){
				tmp += inputParams->priors[i];
			}
			if(ABS(tmp-1.0) > PROB_EPS){
				textcolor(BRIGHT,RED,BLACK);
	            printf("WARNING: The class priors do not sum up to 1\n");
				textcolor(RESET,WHITE,BLACK);
			}
		}
	}
	/*If no priors provided, use empirical priors */
	else{
		inputParams->priors = vec_alloc(nbClass+1);
		inputParams->priors[0] = (real)nbClass;
		tmp = 0.0;
		for(i=1;i<=inputParams->priors[0];i++)
			tmp += graphStat->classCount[i];
		for(i=1;i<=inputParams->priors[0];i++)
			inputParams->priors[i] = (real)graphStat->classCount[i]/tmp;
	}

	/*If provided read the LIBSVM feature matrix*/
	if(kflg){
		m = readLSVMData(inputParams->gramFname,dataInfo,dataset,featLabels,featuresStat,inputParams->verbose);
		if (dataInfo->nbLines != nbNodes){
			fprintf(stderr,"Number of line on the LIBSVM (%i) file doesn't match the number of nodes (%i)\n", dataInfo->nbLines, nbNodes);
			exit(EXIT_FAILURE);
		}
		
		/* Multiply a kernel matrix based on the dataset*/
		/* TO DO : define a parameters to lower the importance of the features*/
		buildKernel2(spmat, dataset, 0.1, inputParams);
		/*Multiply adjacency matrix*/
	}

	
    
    /*Print statistics about the graph, classes, and run-mode*/
    if (inputParams->verbose > 0)
		printInputInfo(spmat,graphStat,nbClass,inputParams);               
    
	/*Minimum Covering Length mode*/
	if (mflg){
		computeMCL(spmat,absorbing,labels,classes,nbClass,latF,latB,inputParams);
		/*Exit after displaying the statistics*/
		exit(EXIT_SUCCESS);		
	}

	 /*Start the CPU chronometer*/
    start_cpu = clock();

	/*If required tune the maximum walk length by cross-validation*/
	if(cflg){
		crossValidateLength(spmat,absorbing,labels,classes,nbClass,NULL,latF,latB,inputParams,optiLen);
		actualWlen = optiLen->len;
	}
	/*Otherwise use the prescribed length*/
	else
		actualWlen = inputParams->wlen;

	/************************ALGORITHM STARTS HERE****************************/

	if(inputParams->verbose >= 1){
		textcolor(BRIGHT,RED,BLACK);
		printf("Performing discriminative walks up to length %i on full data\n",actualWlen);
		textcolor(RESET,WHITE,BLACK);
	}

	/*Allocate data structure*/
    N     = mat_alloc(nbUnlabeled,nbClass);
	preds = char_vec_alloc(nbUnlabeled);
    init_mat(N,nbUnlabeled,nbClass);

	/*Launch the D-walks*/
	dwalk(spmat,absorbing,classes,nbClass,N,latF,latB,actualWlen,inputParams->crossWalks,dwInfo,inputParams->verbose);

	/************************ALGORITHM STOPS HERE****************************/

    /*Stop the CPU chronometer*/
    stop_cpu = clock();
    
	/*Compute the predictions as the argmax on classes for each unlabeled node*/
	computePredictions(N,preds,inputParams->priors,nbUnlabeled,nbClass);

	/*Write the model predictions*/
	writePredictions_unlabeled(inputParams->outPRED,preds,N,nbClass,classes[0]);

	/*Write the class betweeness */


	/*If a target file is provided compare predictions and targets*/
	if(tflg){
		unlabeledPerf = PerfMeasures_alloc(nbClass+1);
		computeUnlabeledPerf(preds,classes[0],nbUnlabeled,nbClass,inputParams,unlabeledPerf,inputParams->verbose);
		free_PerfMeasures(unlabeledPerf,nbClass+1);
	}
    /*Print informations*/
    if (inputParams->verbose >= 1){
		for(i=0;i<nbClass;i++)
			printf("Exploration rate in class %2i : %1.2f %%\n",i+1,100*dwInfo->mass_abs[i]);
		printf("CPU Time (sec)               : %1.4f\n",((double)(stop_cpu - start_cpu)/CLOCKS_PER_SEC));
		printLineDelim();	
    }

	/*Optionally release memory here*/
	#ifdef FREE_MEMORY_AT_END
		free_classes(classes,nbClass+1);
		free_InputParams(inputParams);
		free_DataStat(graphStat);
		free_DWInfo(dwInfo);
		free(absorbing);
		free(labels);
		free_mat(N,nbUnlabeled);
		free_mat(latF,inputParams->wlen+1);
		free_mat(latB,inputParams->wlen+1);
		free_SparseMatrix(spmat);
		free(optiLen);
		free(preds);
		if(kflg) free(gram);
	#endif

    /*Exit successfully :-)*/
    exit(EXIT_SUCCESS);
}
Exemplo n.º 14
0
void SchemeThread::run()
{
  double qtime, utime;
  XSchemeNode* node;

  if (!init())
      return;
  if (!isQuiet())
    printBanner();
  pausing=false;
  while (! threadShouldExit())
    {
      while ( true ) 
	{
          //	  schemeNodes.lockArray();
	  node=schemeNodes.getFirst();
          //	  schemeNodes.unlockArray();
	  if ( node == NULL )
	    {
	      break;
	    }
	  // if scoremode is true then qtime will be in seconds else
	  // milliseconds.
	  qtime=node->time;
	  utime = Time::getMillisecondCounterHiRes() ;
	  // this should probably test if the difference between qtime
	  // and utime is less that 1ms, if not then it probably
	  // shouldn't sleep (?)
	  if ( qtime > utime )
	    {
	      // if scoremode is true then qtime will be in seconds
	      // so this will not happen (which is what we want)
	      wait(1);
	    }
	  else
	    {
              //	      schemeNodes.lockArray();
	      schemeNodes.remove(0, false);
              //	      schemeNodes.unlockArray();
	      // NOTE: the node to process has now been popped from the
	      // queue.  i did this while trying to debug the random
	      // crashing. im not sure if this is the right thing to do or
	      // not since this means that flushing the queue, etc will have
	      // no effect on this node. Search for the word POP to see the
	      // places this affects...
	      //lock.enter();
	      bool keep=node->applyNode(this, 0.0);
	      //lock.exit();
	      if (keep)
		{
                  //		  schemeNodes.lockArray();
		  schemeNodes.addSorted(comparator,node);
		  //          schemeNodes.remove(0, false);
                  //		  schemeNodes.unlockArray();
		}
	      else
		{
		  delete node;
		}
	    }
	  node=NULL;
	}
      // queue is now empty. 
      if (sprouted && isScoreMode())
	closeScore();
      sprouted=false;
      scoretime=0.0;
      //      setScoreMode(ScoreTypes::Empty); only done in closeScore
#ifdef GRACE
      wait(-1);
#else
      read();
#endif
    }
  // leaving killed process....
}
Exemplo n.º 15
0
int main( int argc, char ** argv )
{
    //create qt application
    Application a( argc,( char **) argv );
    loadLocalizations( a, "src/lintouch-runtime/locale", "runtime_" );

    a.connect( &a, SIGNAL( lastWindowClosed() ), SLOT( quit() ) );

    printBanner( argv[0] );

    if( lt_ui_initialize() == -1 ) {
        qWarning( "Unable to initialize Lintouch Panel Library" );
        return -1;
    }
    atexit( lt_ui_terminate );

    if( lt_cp_initialize() == -1 ) {
        qWarning( "Unable to initialize "
                  "Lintouch Communication Protocol Library" );
        return -1;
    }
    atexit( lt_cp_terminate );

    //parse commandline args and remember them so they can be later passed
    // 0 - false, 1 - true, 2 - unspecified = project dependent
    // host/port/project related
    bool startServer = 1;
    QString host_or_project;
    int hostPortSelection = 2;
    int projectSelection = 2;
    // view/panel selection related
    int viewSelection = 2;
    int panelSelection = 2;
    bool servicePanelShortcut = true;
    // windows size related
    bool fullscreen = true;
    bool showFullScreenShortcut = true;
    // view related
    QString view;
    // port related
    int port = 5555;
    bool portGiven = false;
    // debug
    QString debug_fn;   // empty means no-debug

    for( int i = 1; i < argc; i ++ ) {
        if( ( QString( "-h" ) == argv[ i ] ) ||
                ( QString( "--help" ) == argv[ i ] ) ) {
            printUsage( argv[0] );
            exit( 1 );
        }

        if( ( QString( "-p" ) == argv[ i ] ) ||
                ( QString( "--port" ) == argv[ i ] ) ) {
            if ( ++i >= argc ) {
                qWarning ( "ERROR: No port specified" );
                printUsage( argv[ 0 ] );
                exit( 1 );
            }
            port = atoi( argv[ i ] );
            portGiven = true;
            continue;
        }

        if( ( QString( "-v" ) == argv[ i ] ) ||
                ( QString( "--view" ) == argv[ i ] ) ) {
            if ( ++i >= argc ) {
                qWarning ( "ERROR: No view specified" );
                printUsage( argv[ 0 ] );
                exit( 1 );
            }
            view = argv[ i ];
            continue;
        }

        if( ( QString( "-f" ) == argv[ i ] ) ||
                ( QString( "--fullscreen" ) == argv[ i ] ) ) {
            fullscreen = true;
            continue;
        }

        if( ( QString( "-n" ) == argv[ i ] ) ||
                ( QString( "--normal" ) == argv[ i ] ) ) {
            fullscreen = false;
            continue;
        }

        if( QString( "--debug" ) == argv[ i ] ) {
            if ( ++i >= argc ) {
                qWarning ( "ERROR: No filename specified" );
                printUsage( argv[ 0 ] );
                exit( 1 );
            }
            debug_fn = argv[ i ];
            continue;
        }

        if( ( QString( "--enable-host-port-selection" ) == argv[ i ] ) ) {
            hostPortSelection = 1;
            continue;
        }
        if( ( QString( "--disable-host-port-selection" ) == argv[ i ] ) ) {
            hostPortSelection = 0;
            continue;
        }
        if( ( QString( "--enable-project-selection" ) == argv[ i ] ) ) {
            projectSelection = 1;
            continue;
        }
        if( ( QString( "--disable-project-selection" ) == argv[ i ] ) ) {
            projectSelection = 0;
            continue;
        }
        if( ( QString( "--enable-view-switching" ) == argv[ i ] ) ) {
            viewSelection = 1;
            continue;
        }
        if( ( QString( "--disable-view-switching" ) == argv[ i ] ) ) {
            viewSelection = 0;
            continue;
        }
        if( ( QString( "--enable-panel-switching" ) == argv[ i ] ) ) {
            panelSelection = 1;
            continue;
        }
        if( ( QString( "--disable-panel-switching" ) == argv[ i ] ) ) {
            panelSelection = 0;
            continue;
        }
        if( ( QString( "--enable-service-panel-shortcut" ) == argv[ i ] ) ) {
            servicePanelShortcut = true;
            continue;
        }
        if( ( QString( "--disable-service-panel-shortcut" ) == argv[ i ] ) ) {
            servicePanelShortcut = false;
            continue;
        }
        if( ( QString( "--enable-fullscreen-shortcut" ) == argv[ i ] ) ) {
            showFullScreenShortcut = true;
            continue;
        }
        if( ( QString( "--disable-fullscreen-shortcut" ) == argv[ i ] ) ) {
            showFullScreenShortcut = false;
            continue;
        }

        if( QString( argv[ i ] ).startsWith( "-" ) ) {
            qWarning( "ERROR: Invalid argument specified: %s",
                    argv[ i ] );
            printUsage( argv[ 0 ] );
            exit( 1 );
        }

        host_or_project = argv[ i ];
    }

    // validate commandline args

    // problematic combinations
    if( hostPortSelection == 1 && projectSelection == 1 ) {
        qWarning( "ERROR: --enable-host-port-selection and "
                "--enable-project-selection"
                " can not be specified at the same time" );
        printUsage( argv[ 0 ] );
        exit( 1 );
    }
    if( hostPortSelection == 0 && projectSelection == 0 ) {
        qWarning( "ERROR: --disable-host-port-selection and "
                "--disable-project-selection"
                " can not be specified at the same time" );
        printUsage( argv[ 0 ] );
        exit( 1 );
    }

    // no special --enable given, try to determine mode according to given
    // host_or_project
    if( hostPortSelection == 2 && projectSelection == 2 ) {
        if( host_or_project.isEmpty() || QFile::exists( host_or_project ) ) {
            projectSelection = 1;
        } else {
            hostPortSelection = 1;
        }
    }

    // handle non-specified arguments and their defaults
    if( hostPortSelection == 0 ) {
        switch( projectSelection ) {
            case 1:
            case 2:
                startServer = true;
                projectSelection = 1;
                break;
        }
    } else if( hostPortSelection == 1 ) {
        switch( projectSelection ) {
            case 0:
            case 2:
                startServer = false;
                projectSelection = 0;
                break;
        }
    } else if( hostPortSelection == 2 ) {
        switch( projectSelection ) {
            case 0:
                startServer = false;
                hostPortSelection = 1;
                break;
            case 1:
            case 2:
                startServer = true;
                projectSelection = 1;
                hostPortSelection = 0;
                break;
        }
    }

    // when no port has been specified and we are supposed to start local
    // server, we'll use an unused port
    // generated for us by ServerController
    if( startServer && ! portGiven ) port = 0;

    // print summary
    if( !host_or_project.isEmpty() ) {
        if( startServer ) {
            host_or_project = QFileInfo( host_or_project ).absFilePath();
            qWarning( QString( "Starting server %1:%2 with project %3" )
                    .arg( "localhost" ).arg( port ).arg( host_or_project ) );
        } else {
            qWarning( QString( "Using server %1:%2" )
                    .arg( host_or_project ).arg( port ) );
        }
    }
    if( !view.isEmpty() ) {
        qWarning( QString( "Using view %1" ).arg( view ) );
    }

    LoggerPtr l;
    if( debug_fn.isEmpty() ) {
        l = LoggerPtr( new lt::Logger );
    } else {
        l = LoggerPtr( new lt::FileLogger(debug_fn, "",
                    lt::FileLogger::LEVEL_DEBUG) );
    }

    // create main window
    MainWindow mw( startServer, fullscreen, l, NULL );

    // pass in commmand line defaults
    if( startServer ) {
        mw.setProjectNPort( host_or_project, port, host_or_project.isEmpty() );
    } else {
        mw.setHostNPort( host_or_project, port, host_or_project.isEmpty() );
    }
    mw.setViewSelectorEnabled( viewSelection );
    mw.setPanelSelectorEnabled( panelSelection );
    mw.setView( view );
    mw.setServicePanelShortcutEnabled( servicePanelShortcut );
    mw.setShowFullScreenEnabled( showFullScreenShortcut );

    // and go ahead with startup
    a.setMainWidget( &mw );

    if( fullscreen ) {
        mw.showFullScreen();
    } else {
        mw.show();
    }

    return a.exec();
}
Exemplo n.º 16
0
void printUsage() {
    printBanner();
    printf("\n");
    printf("Usage: %s file1 file2\n", PROGRAM_NAME);
    printf("       %s -c sumfile\n", PROGRAM_NAME);
}
Exemplo n.º 17
0
void main(){
	////////////////Data fields //////////////////////////////////////////////
	/*******************Data loaded from files*/
	const int CAP = 150; // Capacity of each month's file.
	//store user date entries, loaded from each month's file
	int dayArr[CAP];
	int cataCodeArr[CAP];
	double amountArr[CAP];
	// loaded from the same file as user data entries, at beginning of file
	double monthBudget;

	// store each day's spending, for display on calendar, loaded from another file
	const int DAY366 = 366; 
	double dailySpendInYear[DAY366]; 

	/*********************Data created at run time*/
	const string DATA_FILE_NAME[] = {"JanuaryData.txt", "FebruaryData.txt", "MarchData.txt", "AprilData.txt",
		"MayData.txt", "JuneData.txt", "JulyData.txt", "AuguestData.txt", "SeptemberData.txt", "OctoberData.txt",
		"NovemberData.txt", "DecemberData.txt" };

	//controller 
	bool exit = false;
	int choice;

	//intermedia 
	int currentMonth, currentDay;
	int entryDate, entryCode;
	double entryAmount;
	double budget = 0, currentBalance = 0, currentTotalSpend = 0;
	int numOfEntries;
	int firstDayOfMonthYearIndex;

	const int MAX_DAYS_IN_MONTH = 31;
	double dailySumArr[MAX_DAYS_IN_MONTH];
	const int NUM_OF_CATAGORY = 4;
	double catagorySumArr[NUM_OF_CATAGORY];


	//////////////////Title & Banner////////////////////////////////////////
	system("title Where Did Your Dollar Go? by Hanfei Xu");

	const int MAX_LENGTH = 90;
	string banner[] = {
		"CIT120 Final Project",
		"Daily Spending Tracker",
		"by Hanfei Xu",
		""
	};
	printBanner(banner, MAX_LENGTH);
	
	///////////////////UI //////////////////////////////////////////////////

	printCenterLine("Welcom to your money tracker \n", MAX_LENGTH);
	printCenterLine("May I know what month this is (Input numberice month #) ?", MAX_LENGTH);
	printCenterLine("Only April (4) has data right now.", MAX_LENGTH);
	for (int i = 0; i < 12; ++i){
		if (i % 6 == 0)
			cout << "\n\t";
		cout << i + 1 << " " << MONTH_NAME[i] << ", ";		
	}
	cout << "\n";
	currentMonth = getIntRange(1, 12);

	initDailySum(dailySumArr, MAX_DAYS_IN_MONTH);
	
	fstream monthData;
	monthData.open(DATA_FILE_NAME[currentMonth - 1], ios::in);
	if (!monthData){ // if user try to start a new month

		//create new month data file
		monthData.close();
		monthData.open(DATA_FILE_NAME[currentMonth - 1], ios::out);
		//set budget
		cout << "\nYou started a NEW month. Please set your budget (you can change that later): ";
		budget = getDbGreater(0);
		currentBalance = budget;
		numOfEntries = 0;
		monthData.close();
	}
	else { // if user stays in old month
		//load budget, entries,from file
		numOfEntries = loadMonthData(monthData, budget, dayArr, cataCodeArr, amountArr, CAP);
		monthData.close();

		//calculate daily spending, totalspending, balance
		calcDailySum(dayArr, amountArr, numOfEntries, dailySumArr, MAX_DAYS_IN_MONTH);
		currentTotalSpend = calcTotalSpending(dailySumArr, MAX_DAYS_IN_MONTH);
		currentBalance = budget - currentTotalSpend;

		// Print monthly overview
		printMonthlyCalendar(currentMonth, dailySumArr);
		cout << "\n"
			<< "Budget: " << budget << "\n"
			<< "Balance: " << currentBalance << "\n\n";
		
	}

	while (exit == false){
		dispMainMenu();
		choice = getIntRange(1, 6);

		switch (choice)
		{
		case 1: getNewEntry(currentMonth, entryDate, entryCode, entryAmount);
				addEntry(dayArr, cataCodeArr, amountArr, numOfEntries, CAP, entryDate, entryCode, entryAmount);
				// refresh running data
				initDailySum(dailySumArr, MAX_DAYS_IN_MONTH);
				calcDailySum(dayArr, amountArr, numOfEntries, dailySumArr, MAX_DAYS_IN_MONTH);
				currentTotalSpend = calcTotalSpending(dailySumArr, MAX_DAYS_IN_MONTH);
				currentBalance = budget - currentTotalSpend;
				break;

		case 2: changeBudget(budget, getNewBugdet()); 
				currentBalance = budget - currentTotalSpend; 
				break;

		case 3: printMonthlyCalendar(currentMonth, dailySumArr); 
				cout << "\n"
					<< "Budget: " << budget << "\n"
					<< "Balance: " << currentBalance << "\n\n";
				break;

		case 4: printMonthlyCalendar(currentMonth, dailySumArr);
				cout << "\n"
				<< "Budget: " << budget << "\n"
				<< "Balance: " << currentBalance << "\n\n";
				initCataSum(catagorySumArr, NUM_OF_CATAGORY);
				calcCataSum(cataCodeArr, amountArr, numOfEntries, catagorySumArr, NUM_OF_CATAGORY);
				printHistogramH(catagorySumArr, NUM_OF_CATAGORY, 10,"$", "Type");
				printHistogramH(dailySumArr, NUM_OF_DAYS_MONTH[currentMonth - 1], 5 ,"$", "Date");
				break;
		case 5: cout << "\n Under Construction \n";  break;
		case 6: 
				fstream file;
				file.open(DATA_FILE_NAME[currentMonth - 1], ios::out);
				writeMonthData(file, budget, dayArr, cataCodeArr, amountArr, numOfEntries);
				file.close();
			    exit = true;
				break;
		
		}
		
		cout << "\nPress ENTER to continue";
		cin.get();
		system("cls");
	}
	
}