Exemple #1
0
void PlotControlWidget::initiliazeLayoutPreferencesFromDefault()
{
    if (mLayoutModel) {
        mLayoutModel->setPlotStyle(PlotStyle::defaultPlotStyle());
        initializeState();
    }
}
ccPointPropertiesDlg::ccPointPropertiesDlg(QWidget* parent)
	: ccPointPickingGenericInterface(parent)
	, Ui::PointPropertiesDlg()
	, m_pickingMode(POINT_INFO)
{
	setupUi(this);
	setWindowFlags(Qt::FramelessWindowHint |Qt::Tool);

	connect(closeButton,				SIGNAL(clicked()), this, SLOT(onClose()));
	connect(pointPropertiesButton,		SIGNAL(clicked()), this, SLOT(activatePointPropertiesDisplay()));
	connect(pointPointDistanceButton,	SIGNAL(clicked()), this, SLOT(activateDistanceDisplay()));
	connect(pointsAngleButton,			SIGNAL(clicked()), this, SLOT(activateAngleDisplay()));
	connect(rectZoneToolButton,			SIGNAL(clicked()), this, SLOT(activate2DZonePicking()));
	connect(saveLabelButton,			SIGNAL(clicked()), this, SLOT(exportCurrentLabel()));
	connect(razButton,					SIGNAL(clicked()), this, SLOT(initializeState()));

	//for points picking
	m_label = new cc2DLabel();
	m_label->setSelected(true);

	//for 2D zone picking
	m_rect2DLabel = new cc2DViewportLabel();
	m_rect2DLabel->setVisible(false);	//=invalid
	m_rect2DLabel->setSelected(true);	//=closed
}
EvaluationState* newEvaluationState(const AstronomyParameters* ap)
{
    EvaluationState* es;

    es = mwCallocA(1, sizeof(EvaluationState));
    initializeState(ap, es);

    return es;
}
void ClusterFilterControllerWidget::treatNumberOfConsecErrorsChanging()
{
    if (mFilter) {
        mFilter->setNumberOfConsecErrors(ui->numberOfConsecErrorsSpinBox->value());
        disconnectAll();
        initializeState();
        connectAll();
        mModel->updateOutputData();
    }
    ui->numberOfConsecErrorsSpinBox->clearFocus();
}
void ClusterFilterControllerWidget::treatWindowWidthChanging()
{
    if (mFilter) {
        mFilter->setWindowWidth(ui->windowWidthSpinBox->value());
        disconnectAll();
        initializeState();
        connectAll();
        mModel->updateOutputData();
    }
    ui->windowWidthSpinBox->clearFocus();
}
void ClusterFilterControllerWidget::setFilter(std::shared_ptr<DataConverter> filter)
{
    if ((mFilter = std::dynamic_pointer_cast<ClusterFilter>(filter)) == nullptr) {
        qDebug() << "wrong initializtion of MarginFilterControllerWidget";
        return;
    }
    disconnectAll();
    initializeState();
    connectAll();

}
Exemple #7
0
void Request::handleRequest(boost::shared_ptr<libtorrent::socket_type>& socket, const libtorrent::rc4_handler& cipher) {
  if (!packet_ || packet_->expired()) {
    socket->close();
    onRequestComplete();
    return;
  }
  
  if (!!socket_) {
    /* we are currently handling exactly the same request for another peer */
    socket->close(); /* note that we are closing the second connection only */
    return;
  }

  socket_ = socket;
  cipher_ = cipher;
  channelReady_ = false;

  if (state_ == StateInitializing) {
    state_ = initializeState(socket);
  }

  if (state_ == StateArpUnresolved) {
    respond(BinaryBuffer());
    closeSocket();
    return;
  }

  if (state_ == StateArpResolved) {
    BinaryBuffer response = arpTable_.query(packet_->payload, externalEndpoint_);
    if (!response.empty()) {
      printf("Responding to an ARP request.\n");
      respond(response);
    }
    closeSocket();
    return;
  }

  if (state_ == StateComplete) {
    onRequestComplete();
    return;
  }
}
void WindowFilterControllerWidget::setFilter(std::shared_ptr<DataConverter> filter)
{
    if ((mFilter = std::dynamic_pointer_cast<WindowFilter>(filter)) == nullptr) {
        qWarning() << "Failed to initialize MarginFilterControllerWidget";
        return;
    }
    disconnect(ui->beginTimeLineEdit, SIGNAL(editingFinished()),
            this, SLOT(treatBeginTimeChanging()));
    disconnect(ui->endTimeLineEdit, SIGNAL(editingFinished()),
            this, SLOT(treatEndTimeChanging()));
    disconnect(ui->windowWidthSpinBox, SIGNAL(valueChanged(int)),
            this, SLOT(treatWindowWidthChanging(int)));
    initializeState();
    connect(ui->windowWidthSpinBox, SIGNAL(valueChanged(int)),
            this, SLOT(treatWindowWidthChanging(int)));
    connect(ui->beginTimeLineEdit, SIGNAL(editingFinished()),
            this, SLOT(treatBeginTimeChanging()));
    connect(ui->endTimeLineEdit, SIGNAL(editingFinished()),
            this, SLOT(treatEndTimeChanging()));
}
void Foreman::initialize() {
  if (cpu_id_ >= 0) {
    // We can pin the foreman thread to a CPU if specified.
    ThreadUtil::BindToCPU(cpu_id_);
  }
  DEBUG_ASSERT(query_dag_ != nullptr);

  initializeState();

  // Collect all the workorders from all the relational operators in the DAG.
  const dag_node_index dag_size = query_dag_->size();
  for (dag_node_index index = 0; index < dag_size; ++index) {
    if (checkAllBlockingDependenciesMet(index)) {
      query_dag_->getNodePayloadMutable(index)->informAllBlockingDependenciesMet();
      processOperator(index, false);
    }
  }

  // Dispatch the WorkOrders generated so far.
  dispatchWorkerMessages(0, 0);
}
Exemple #10
0
int main(int argc, char **argv) {

  time_t starttime=time(0);
  struct scalpelState state;

  if (ldiv(SIZE_OF_BUFFER,SCALPEL_BLOCK_SIZE).rem != 0) {
    fprintf (stderr, SCALPEL_SIZEOFBUFFER_PANIC_STRING);
    exit (-1);
  }
  
#ifndef __GLIBC__
  setProgramName(argv[0]);
#endif

  fprintf (stdout,SCALPEL_BANNER_STRING);

  initializeState(argv,&state);

  processCommandLineArgs(argc,argv,&state);

  convertFileNames(&state);

  if (state.modeVerbose) {
    fprintf (stdout,"Output directory: \"%s\"\n", state.outputdirectory);
    fprintf (stdout,"Configuration file: \"%s\"\n", state.conffile);
    fprintf (stdout,"Coverage maps directory: \"%s\"\n", state.coveragedirectory);
  }

  // read configuration file
  if (readSearchSpecFile(&state)) {
    // error in configuration file, msg has already been output
    exit(-1);
  }

  setttywidth();

  argv += optind;
  if (*argv != NULL || state.useInputFileList) {
    // prepare audit file and make sure output directory is empty.
    if(openAuditFile(&state)){
      fprintf(stderr, "Aborting.\n\n");
      exit(-1);
    }
    digAllFiles(argc,argv,&state);
    closeFile(state.auditFile);
  } else {      
    usage();
    fprintf(stdout,"\nERROR: No image files specified.\n\n");
  }

#ifdef __WIN32
  fprintf (stdout,"\nScalpel is done, files carved = %I64u, elapsed = %ld seconds.\n", 
	   state.fileswritten, 
	   (int)time(0) - starttime);
#else
  fprintf (stdout,"\nScalpel is done, files carved = %llu, elapsed = %ld seconds.\n", 
	   state.fileswritten, 
	   (int)time(0) - starttime);
#endif

  return 0;
}
Exemple #11
0
// the exposed libscalpel API
// NOTE: This function is deprecated and will be removed. Use the
// libscalpel_* functions instead.
// TODO make the driver in scalpel_exec.c use this (minor refactoring needed)
// TODO add support for the remaining options avail from cmd-line
// returns SCALPEL_OK on no error, can throw runtime_error exception on errors
int scalpel_carveSingleInput(ScalpelInputReader * const reader, const char * const confFilePath,
    const char * const outDir, const unsigned char generateFooterDb,
    const unsigned char handleEmbedded, const unsigned char organizeSubdirs,
    const unsigned char previewMode,
    const unsigned char carveWithMissingFooters,
    const unsigned char noSearchOverlap) throw (std::runtime_error) {

    if (!reader || ! confFilePath || ! outDir) {
        //invalid args
        throw std::runtime_error("Invalid empty arguments");
    }

    if (!reader->dataSource || !reader->id) {
        throw std::runtime_error("Invalid empty input reader arguments");
    }

    //check fns
    if (!reader->open || !reader->read || !reader->seeko || !reader->tello
        || !reader->close || !reader->getError || !reader->getSize) {
            throw std::runtime_error("Reader callbacks not setup");
    }

    struct scalpelState state;

    std::string processorName ("scalpel_carveSingleInput()");
    char * args[5];
    args[0] = const_cast<char*> ( processorName.c_str());
    args[1] = reader->id;
    args[2] = const_cast<char*> (confFilePath);
    args[3] = const_cast<char*> (outDir);
    args[4] = 0;


    initializeState(args, &state);

    //setup input
    state.inReader = reader;

    //setup options
    const size_t outDirLen = strlen(outDir);
    strncpy(state.outputdirectory, outDir, outDirLen);
    state.outputdirectory[outDirLen] = 0;
    const size_t confFilePathLen = strlen(confFilePath);
    strncpy(state.conffile, confFilePath, confFilePathLen);
    state.conffile[confFilePathLen] = 0;
    state.generateHeaderFooterDatabase = generateFooterDb;
    state.handleEmbedded = handleEmbedded;
    state.organizeSubdirectories = organizeSubdirs;
    state.previewMode = previewMode;
    state.carveWithMissingFooters = carveWithMissingFooters;
    state.noSearchOverlap = noSearchOverlap;

    convertFileNames(&state);

    // read configuration file
    int err;
    if ((err = readSearchSpecFile(&state))) {
        // problem with config file
        handleError(&state, err); //can throw
        freeState(&state);
        std::stringstream ss;
        ss << "Error reading spec file, error code: " << err;
        throw std::runtime_error(ss.str());
    }

    // prepare audit file and make sure output directory is empty.
    if ((err = openAuditFile(&state))) {
        handleError(&state, err); //can throw
        freeState(&state);
        std::stringstream ss;
        ss << "Error opening audit file, error code: " << err;
        throw std::runtime_error(ss.str());
    }

    // Initialize the backing store of buffer to read-in, process image data.
    init_store();

    // Initialize threading model for cpu or gpu search.
    init_threading_model(&state);

    if ((err = digImageFile(&state))) {
        handleError(&state, err); //can throw
        closeAuditFile(state.auditFile);
        destroyStore();
        freeState(&state);
        std::stringstream ss;
        ss << "Error digging file, error code: " << err;
        throw std::runtime_error(ss.str());
    }

    if ((err = carveImageFile(&state))) {
        handleError(&state, err); //can throw
        closeAuditFile(state.auditFile);
        destroy_threading_model(&state);
        destroyStore();
        freeState(&state);
        std::stringstream ss;
        ss << "Error carving file, error code: " << err;
        throw std::runtime_error(ss.str());
    }

    closeAuditFile(state.auditFile);
    destroy_threading_model(&state);
    destroyStore();
    freeState(&state);

    return SCALPEL_OK;
}
Exemple #12
0
int main(int argc, char *argv[])
{
	char						*firmwareFileName;
	FILE						*fpFirmwareFile;
	int							inquiryType;
	int							firstRecordType;
	int							result;
	int							fileSize;
	int							isSpkg = 0;
	struct stat					statBuf;
	IcsImageHeader_Record_t		recordBuffer;
	uint8_t						cssBuf[CSS_HEADER_SIZE + 10];

	struct option longopts[] = 
	{
		{ "showVersion", no_argument, &inquiryType, SHOWVERSION },
		{ "showType",    no_argument, &inquiryType, SHOWTYPE    },
		{ "help",        no_argument, &inquiryType, HELP        },
		{ 0,             0,           0           , 0           }
	};

	/* parse options for inquiry type */
	if ((result = getopt_long(argc, argv, "", longopts, NULL)))	// assignment, not ==
		Usage();

	if (inquiryType == HELP)
		Usage_full();

	if (argc != 3)
		Usage();

	/* set up endian-ness */

	initializeState();

	/* stat file to get size and allocate buffers */

	firmwareFileName = argv[2];

	if (stat(firmwareFileName, &statBuf) < 0) {
		fprintf(stderr, "Error taking stat of file {%s}: %s\n",
			firmwareFileName, strerror(errno));
		exit(1);
	}

	fileSize = (int)statBuf.st_size;
	bufSize = fileSize + 1024; /* pad by 1K to be safe */
	if ((cmpBuffer = malloc(bufSize)) == NULL) {
		fprintf(stderr, "Error allocating memory for firmware buffer\n");
		goto fail;
	}
	if ((appBuffer = malloc(bufSize * 3)) == NULL) {
		fprintf(stderr, "Error allocating memory for inflated firmware buffer\n");
		goto fail;
	}

	memset(cmpBuffer, 0, bufSize);
	memset(appBuffer, 0, bufSize * 3);

	/* open file */
 
	if ((fpFirmwareFile = fopen(firmwareFileName, "rb")) == NULL)
	{
		fprintf(stderr, "Error opening file {%s} for input: %s\n",
			firmwareFileName, strerror(errno));
		goto fail;
	}

	if (0 == fread(&cssBuf, CSS_HEADER_SIZE, 1, fpFirmwareFile))
	{
		fprintf(stderr, "Error reading file {%s}: %s\n",
			firmwareFileName, strerror(errno));
		goto fail;
	}

	isSpkg = checkCssHeader(cssBuf);

	/* get first record, check if ICS image file */

	fseek(fpFirmwareFile, isSpkg ? CSS_HEADER_SIZE : 0, SEEK_SET);

	if (0 == fread(&firstRecordType, 4, 1, fpFirmwareFile))
	{
		fprintf(stderr, "Error reading file {%s}: %s\n",
			firmwareFileName, strerror(errno));
		goto fail;
	}

	fseek(fpFirmwareFile, isSpkg ? CSS_HEADER_SIZE : 0, SEEK_SET);

	if (ICS_IMAGE_HEADER_RECORD_TYPE_INFO != toHostEndian32(firstRecordType))
	{
		fprintf(stderr, "This is not a valid firmware image file\n");
		goto fail;
	}

	/* read in header, display what is asked for */

	if (ERR_OK != getRecord(fpFirmwareFile, &recordBuffer))
		goto fail;

	switch (inquiryType)
	{
		case SHOWVERSION:
			displayVersion(recordBuffer.payload.info.version);
			break;
		case SHOWTYPE:
			/*
			 * For the type, we really want to look for the embedded strings first.
			 * Call removeHeader, which will remove the ICS header from the package
			 * file and place it in the compressed buffer. Then call
			 * displayEmbeddedProdAndBsp which inflates and then searches. If the search
			 * fails, it is a pre-3.1.0.1 release, so feed the codes from the ICS header
			 * to displayType.
			 */
			result = removeHeader(argv[2], cmpBuffer);
			if (!displayEmbeddedProdAndBsp()) /* if this fails, try old way */
				displayType(toHostEndian32(recordBuffer.payload.info.productCode),
			    	        toHostEndian32(recordBuffer.payload.info.bspCode));
			break;
		default:
			fprintf(stderr, "Unknown inquiry type\n");
			goto fail;
	}

	fclose(fpFirmwareFile);
fail:
	if (cmpBuffer != NULL)
		free(cmpBuffer);
	if (appBuffer != NULL)
		free(appBuffer);
	exit(0);
}
Exemple #13
0
int main(int argc, char *argv[]) {
typedef char * string;

    struct sockaddr_in cliAddr, remoteServAddr; //Socker addresses for the client and remote
    unsigned int remote_length = sizeof(remoteServAddr); //Length of remote address struct
    int sd; //The socket that we will use
    u_char receive_buffer[3]; //The buffer that receives acks. 512 bytes long
    struct timeval default_timeout; //The default timeout we are using for the select()
    default_timeout.tv_sec = 2; //2 secs
    default_timeout.tv_usec = 500000; //0.5 secs
    fd_set read_fds;  // temp file descriptor list for select()

    //Initialize the state of the client
    SwpSeqno receivedAcks[500]; //(Non-optimal) implementation of the ACK list
    static SwpState state;
    initializeState(&state, receivedAcks);


    //Check command line args.
    if(argc<6) {
	printf("usage : %s <serve_ip_address> <error_rate> <random_seed> <send_file> <send_log> \n", argv[0]);
	exit(1);
    }
    //Print error rate
    printf("error rate : %f\n",atof(argv[2]));

    /* Note: you must initialize the network library first before calling
       sendto_().  The arguments are the <error_rate> and <random_seed> */
    init_net_lib(atof(argv[2]), atoi(argv[3]));

    /* Test printing to the client Log */
    /*int temp[] = {1,2,3,5};
    int size_of_temp = 4;
    toLog(1, argv[5], "Send", state.hdr.SeqNum, temp, size_of_temp, &state);*/

    /* get server IP address (input must be IP address, not DNS name) */
    printf("%s: sending data to '%s' \n", argv[0], argv[1]);

    //Set up the address of the remote server.
    bzero(&remoteServAddr, sizeof(remoteServAddr)); //zero out the address
    remoteServAddr.sin_family = AF_INET; //address family
    remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT); //Use the port we set up

    //Convert the char string into an INET address structure
    int retVal;
    retVal = inet_pton(AF_INET, argv[1], &remoteServAddr.sin_addr);
    if(retVal == -1){
        printf("Invalid address family for IP address\n");
    }

    //Same deal with our client address
    cliAddr.sin_family = AF_INET;
    cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    cliAddr.sin_port = htons(0);

    /* socket creation */
    sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(sd<0) {
	printf("%s: cannot open socket \n",argv[0]);
	exit(1);
    }

    /*
    Open up our send file to get it ready to packet-ize and send
    */
    FILE *fsend;
    fsend = fopen(argv[4],"r"); //Open the filename we entered
    if(fsend == NULL){
        printf("Please use an existing file to send\n");
        printf("usage : %s <serve_ip_address> <error_rate> <random_seed> <send_file> <send_log> \n", argv[0]);
        exit(1);
    }
    
    //Prep for the send loop
    FD_ZERO(&read_fds); //clear the select set
    FD_SET(sd, &read_fds); //add socket to the listening list
    int nbytes;
    char doneReadingFile = 0; //Flag to tell us if we are done reading the file
    SwpSeqno lastSeqNum = -1; //What is the last sequence number?
    Msg frame;
    char isSelectRunning = 0;
    struct timeval new_timeout; //The default timeout we are using for the select()
    new_timeout.tv_sec = 2; //2 secs
    new_timeout.tv_usec = 500000; //0.5 secs
    struct timeval void_timeout;
    void_timeout.tv_sec = 2147483647;
    void_timeout.tv_usec = 2147483647;
    struct recvQ_slot *rslot;
    struct timeval timeofday;
    /*
    Start the loop for sliding window.
    Stop conditions are that the whole file has been read and the LAR == LFS
    */
    int count = 0;
    do{

        //size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
        //printf("size of reading%ld\n",sizeof(Msg)-3*sizeof(char));
        //Read a frame's worht of the file.
        if((nbytes = fread(&frame.m[3],sizeof(char),sizeof(frame.m)-3*sizeof(u_char),
                            fsend))== -1){
            printf("Error Reading File, Try again...\n");
            // break;
        }
        //If the file is done being read
        else if (nbytes == 0){
            doneReadingFile = 1;
            lastSeqNum = state.hdr.SeqNum;
        }
        //If there was something to read!
        else{
            //printf("positions 4 5 6 %c %c %c\n",frame.m[3], frame.m[4],frame.m[5]);
            if(sendNewFrame(&state, &frame, isSelectRunning, sd,&read_fds, 
                            &default_timeout,&remoteServAddr,sizeof(remoteServAddr)) < 0){
               printf("Error on packet send\n");
            }
            // if(sendto_(sd, frame.m, sizeof(frame.m),0, (struct sockaddr *) &remoteServAddr,
            //     sizeof(remoteServAddr)) < 0)
            // {
            //     printf("EROROROEOs\n");
            // }
            int num_least;
            if (FD_ISSET(sd, &read_fds)){
                printf("received packet!\n");
                if ((nbytes = recv(sd, &receive_buffer, sizeof(receive_buffer), 0)) <= 0) {
                    // got error or connection closed by client
                    if (nbytes == 0) {
                    // connection closed
                        printf("selectserver: socket %d hung up\n", sd);
                    } else {
                        perror("recv");
                    }
                } else 
                {//Got an ACK! Update everyone's timeouts, get rid of the ACK sequence #'s timeout 
                    printf("got %d\n", receive_buffer[1]);
                    SwpSeqno ack = receive_buffer[1];
                    if(ack == state.LAR +1){
                        state.sendQ[ack%SWS].timeout = void_timeout;
                        struct timeval *least = &state.sendQ[0].timeout;
                        struct timeval *temp;
                        int i;
                        if(gettimeofday(&timeofday,NULL)){
                            printf("Get timeofday error\n");
                        }
                        
                        for(i = 0;i < SWS;i++){
                            state.sendQ[i].timeout.tv_sec = timeofday.tv_sec - state.sendQ[i].timeout.tv_sec;
                            state.sendQ[i].timeout.tv_usec = timeofday.tv_usec - state.sendQ[i].timeout.tv_usec;
                            temp = &state.sendQ[i].timeout;
                            if((least->tv_sec * 1000000 + least->tv_usec) > 
                                (temp->tv_sec * 1000000 + temp->tv_usec)){
                                least->tv_sec = temp->tv_sec;
                                least->tv_usec = temp->tv_usec;
                                num_least = i;
                            }

                        }
                        printf("%d", num_least);
                        FD_ZERO(&read_fds); //clear the select set
                        FD_SET(sd, &read_fds); //add socket to the listening list
                        if (select(sd+1, &read_fds, NULL, NULL, least) == -1) {
                            perror("select");
                            exit(4);
                        }
                        //Move the 
                        ++state.newSend;
                        ++state.LAR;
                        ++state.LFS;
                        state.sendQ[ack%RWS].acked = 0;
                        while(state.sendQ[(state.LFS+1)%RWS].acked){
                            ++state.newSend;
                            ++state.LAR;
                            ++state.LFS;
                            state.sendQ[ack%RWS].acked = 0;   
                        }
                    }
                    else if(ack > state.LFS && ack < state.LAR){
                        state.sendQ[ack%SWS].timeout = void_timeout;
                        struct timeval *least = &state.sendQ[0].timeout;
                        struct timeval *temp;
                        int i;
                        for(i = 0;i < SWS;i++){
                            temp = &state.sendQ[0].timeout;
                            if((least->tv_sec * 1000000 + least->tv_usec) > 
                                (temp->tv_sec * 1000000 + temp->tv_usec)){
                                least->tv_sec = temp->tv_sec;
                                least->tv_usec = temp->tv_usec;
                                num_least = i;
                            }
                        }
                        FD_ZERO(&read_fds); //clear the select set
                        FD_SET(sd, &read_fds); //add socket to the listening list
                        if (select(sd+1, &read_fds, NULL, NULL, least) == -1) {
                            perror("select");
                            exit(4);
                        }
                        state.sendQ[ack%RWS].acked = 1;
                    }
                }
            }
            else{
                printf("Timed out. Resend\n");
                SwpSeqno done;
                int i;
                struct timeval *temp;
                struct timeval *least = &state.sendQ[0].timeout;
                //Find which packet must be resent.
                for(i = 0;i < SWS;i++){
                    temp = &state.sendQ[0].timeout;
                    if((temp->tv_sec * 1000000 + temp->tv_usec) >= 0)
                    {
                        done = state.sendQ[i].msg.m[0];
                        gettimeofday(&state.sendQ[i].timeout, NULL);
                        //Ressend the frame;
                        if(sendto_(sd, state.sendQ[i].msg.m, sizeof(state.sendQ[i].msg.m),0, 
                            (struct sockaddr *) &remoteServAddr, sizeof(remoteServAddr)) < 0){
                            printf("EROROROEOs\n");
                        }
                    }
                }

                //Redo select
                for(i = 0;i < SWS;i++){
                    temp = &state.sendQ[0].timeout;
                    if((least->tv_sec * 1000000 + least->tv_usec) > 
                        (temp->tv_sec * 1000000 + temp->tv_usec)){
                        least->tv_sec = temp->tv_sec;
                        least->tv_usec = temp->tv_usec;
                        num_least = i;
                    }
                }
                FD_ZERO(&read_fds); //clear the select set
                FD_SET(sd, &read_fds); //add socket to the listening list
                new_timeout.tv_sec = least->tv_sec; //2 secs
                //printf("%d\n", least->tv_sec);
                new_timeout.tv_usec = least->tv_usec; 
                if (select(sd+1, &read_fds, NULL, NULL, &new_timeout) == -1) {
                    perror("select");
                    exit(4);
                }


                //sendto_(sd, msgs[iter], strlen(msg),0, (struct sockaddr *) &remoteServAddr,
                //sizeof(remoteServAddr));
            }
        }
        
        count++;

    }while(!doneReadingFile && state.LAR != state.LFS);
    fclose(fsend);


/*
    int sendto_(int sockfd, const void *msg, int len, unsigned int flags,
                const struct sockaddr *to, socklen_t tolen);
*/
/*
    FD_ZERO(&read_fds);
    FD_SET(sd, &read_fds);
    int nbytes;
    //sd; //Keep track of biggest file descriptor

    //for(;;){
    char msg[] = "send this";
    char msg2[] = "send that";
    string msgs[4];
    msgs[0] = "0send this";
    msgs[1] = "1send that";
    msgs[2] = "2cat in ";
    msgs[3] = "3hat";
    int iter = 0;
    while(iter < 4){
        sendto_(sd, msgs[iter], strlen(msg),0, (struct sockaddr *) &remoteServAddr,
            sizeof(remoteServAddr));

        if (select(sd+1, &read_fds, NULL, NULL, &default_timeout) == -1) {
            perror("select");
            exit(4);
        }

        if (FD_ISSET(sd, &read_fds)){
            printf("received packet!\n");
            if ((nbytes = recv(sd, receive_buffer, sizeof(receive_buffer), 0)) <= 0) {
                // got error or connection closed by client
                if (nbytes == 0) {
                // connection closed
                    printf("selectserver: socket %d hung up\n", sd);
                } else {
                    perror("recv");
                }
            } else 
            {
                printf("%s\n", receive_buffer);
                iter++;
            }
        }
        else{
            printf("Timed out. Resend\n");
            //sendto_(sd, msgs[iter], strlen(msg),0, (struct sockaddr *) &remoteServAddr,
            //sizeof(remoteServAddr));
        }
    }
            
*/
        


    //}


    return 0;
}
Exemple #14
0
int libscalpel_initialize(scalpelState ** state, char * confFilePath, 
                          char * outDir, const scalpelState & options)
{
    std::string funcname("libscalpel_initialize");

    if (state == NULL)
        throw std::runtime_error(funcname + ": state argument must not be NULL.");

    if (*state != NULL)
        throw std::runtime_error(funcname + ": state has already been allocated.");

    if (outDir == NULL || strlen(outDir) == 0)
        throw std::runtime_error(funcname + ": no output directory provided.");

    if (confFilePath == NULL || strlen(confFilePath) == 0)
        throw std::runtime_error(funcname + ": no configuration file path provided.");

    scalpelState * pState = new scalpelState(options);

    char * argv[3];
    argv[0] = confFilePath;
    argv[1] = outDir;
    argv[2] = NULL;

    initializeState(&argv[0], pState);

    const size_t outDirLen = strlen(outDir);
    strncpy(pState->outputdirectory, outDir, outDirLen + 1);
    pState->outputdirectory[outDirLen + 1] = 0;
    const size_t confFilePathLen = strlen(confFilePath);
    strncpy(pState->conffile, confFilePath, confFilePathLen + 1);
    pState->conffile[confFilePathLen + 1] = 0;

    convertFileNames(pState);

    int err = 0;

    // prepare audit file and make sure output directory is empty.
    if ((err = openAuditFile(pState))) {
        handleError(pState, err); //can throw
        std::stringstream ss;
        ss << ": Error opening audit file, error code: " << err;
        throw std::runtime_error(funcname + ss.str());
    }

    // read configuration file
    if ((err = readSearchSpecFile(pState))) {
        // problem with config file
        handleError(pState, err); //can throw
        std::stringstream ss;
        ss << ": Error reading spec file, error code: " << err;
        throw std::runtime_error(funcname + ss.str());
    }

    // Initialize the backing store of buffer to read-in, process image data.
    init_store();

    // Initialize threading model for cpu or gpu search.
    init_threading_model(pState);

    *state = pState;

    return SCALPEL_OK;
}
Exemple #15
0
void PlotControlWidget::setLayoutModel(PlotLayoutModel *layoutModel)
{
    mLayoutModel = layoutModel;
    initializeState();
}
 static void initialize(T& filter) {
     auto l = filter.retrieve_lock();
     initializeState(filter.state);
     filter.covariance.setIdentity();
 }
Exemple #17
0
int main() {
    int i;
    int player;
    int seed = 1000;
    int numPlayers = 2;
    int cards[10] = {adventurer, council_room, feast, gardens, mine,
                     remodel, smithy, village, baron, great_hall};
    struct gameState state;
    struct gameState originalState;

    // Initialize gameState
    if (initializeState(numPlayers, cards, seed, &state) != 0)
    {
        printf("Error: Could not initialize state.\n");
        return -1;
    }

    // Preserve the original game state to compare result of shuffle()
    memcpy(&originalState, &state, sizeof(struct gameState));

    printf ("Testing shuffle():\n");

    player = 0;
    printf("Shuffling Player %d:\n", player);

    if (shuffle(player, &state) < 0)
    {
        printf("\tERROR: shuffe() failed.\n");
        return -1;
    }

    // Check first that each player's deck count is unchanged)
    int p;
    for (p = 0; p < numPlayers; p++)
    {
        if (state.handCount[p] != originalState.handCount[p])
        {
            printf("\tERROR: handCount not the same\n");
            return -1;
        }
    }

    // Check order of cards for each player 
    for (p = 0; p < numPlayers; p++)
    {
        printf("Checking order of player %d's deck...\n", p);

        i = 0;
        while ( (i < state.deckCount[p]) &&
                (state.deck[p][i] == originalState.deck[p][i]) )
        {
            printf("\tshuffled card %d: %d\n", i, state.deck[p][i]);
            printf("\toriginal card %d: %d\n", i, originalState.deck[p][i]);
            i++;
        }
        printf("\n");
        
        // Check if order of cards in shuffled deck is the same
        if (p == player && i >= state.deckCount[p])
        {
            printf("ERROR: Order of shuffled deck is the same.\n");
            return -1;
        }
        else if (p == player && i < state.deckCount[p])
        {
            printf("Player %d's is different! Great success!\n", player);
        }

        // Check if order of cards in unshuffled deck is the same
        if (p != player && i < state.deckCount[p])
        {
            printf("ERROR: Order of non-shuffled deck is different.\n");
            return -1;
        }
    }
    
    // Check that shuffled deck has same set of cards
    qsort((void*)(state.deck[0]), state.deckCount[player], sizeof(int), compare);
    qsort((void*)(originalState.deck[0]), state.deckCount[player], sizeof(int), compare);

    if (memcmp(&state, &originalState, sizeof(struct gameState)) != 0)
    {
        printf("\tERROR: memcmp failed.\n");
        return -1;
    }

    printf("All tests passed!\n");
    return 0;
}
Exemple #18
0
int PV_Arguments::initialize_base() {
   initializeState();
   numArgs = 0;
   args = NULL;
   return PV_SUCCESS;
}