int main() {
	/* Loop counter */
	int i;
	int *arg = malloc(sizeof(*arg));

	/* Initialize the app */
	initializeData();

	int n=10;
	/* Create the soldier threads */
	
	int clan;
	for(i = 0; i < n; i++) {
		/* Create the thread */
		arg=i;
		clan=rand()%2;
		if(clan)
			pthread_create(&tid[i],&attr,Lancs,arg);
		else
			pthread_create(&tid[i],&attr,Yorks,arg);
	}

	for(i = 0; i < n; i++) {
		pthread_join(tid[i], NULL);
	}

	return 0;
}
示例#2
0
int setDataInTableByString(HashTable *table, char *str, u_int64_t value, Error *error) {
  void **arrayCell = _getPtrListFromTableByString(table,str);
  LinkedList *list = *arrayCell;
  Data *data = NULL;
  if (NULL == list) {
    *arrayCell = initializeList(error);
    list = *arrayCell;
    if (NULL == list) {
      return 1; }
  }

  data = getDataFromTableByString(table,str);

  if (NULL == data) {
    data = initializeData(str,value,error);
    if (NULL == data) {
      return 1; }
    insertDataIntoList(list,data,error);
    if (0 != error->error) {
      return 1; }
  } else {
      data->value = value;
  }

#ifdef DEBUG
  printf(BOLD_GREEN"In "HEADER "HashTable"STANDART" (%p) set data (%p) by '%s' (hash=%"PRIu64"): %"PRIu64"\n",table,data,str,data->hash,data->value);
#endif

  return 0;
}
示例#3
0
/*!
  \brief Deletes any details currently stored in the Smart Poster
  and re-initializes them by parsing the contents of the payload.
  */
void NdefNfcSpRecord::parseRecords()
{
    initializeData();
    QNdefMessage message = QNdefMessage::fromByteArray(payload());
    qDebug() << "Sp Record Count: " << message.count();

    foreach (const QNdefRecord &record, message) {
        qDebug() << "Sp Record type: " << QString(record.type());
        qDebug() << "Sp Type name: " << record.typeNameFormat();

        // URI
        if (record.isRecordType<QNdefNfcUriRecord>()) {
            if (recordUri) { delete recordUri; recordUri = NULL; }
            recordUri = new QNdefNfcUriRecord(record);
            qDebug() << "Sp URI: " << recordUri->uri().toString();
        }
        // Title
        else if (record.isRecordType<QNdefNfcTextRecord>()) {
            QNdefNfcTextRecord* recordTitle = new QNdefNfcTextRecord(record);
            addTitle(*recordTitle);
            if (!recordTitleList.isEmpty()) {
                qDebug() << "Sp Title: " << recordTitleList.last().text();
            }
        }
        // Image
        else if (record.typeNameFormat() == QNdefRecord::Mime &&
                   record.type().startsWith("image/")) {
            if (recordImage) { delete recordImage; recordImage = NULL; }
            recordImage = new NdefNfcMimeImageRecord(record);
            qDebug() << "Sp Image: " << recordImage->format();
        }
        // Action
        else if (record.typeNameFormat() == QNdefRecord::NfcRtd &&
                 QString(record.type()) == "act") {
            if (recordAction) { delete recordAction; recordAction = NULL; }
            recordAction = new NdefNfcActRecord(record);
            qDebug() << "Sp Action: " << action();
        }
        // Size
        else if (record.typeNameFormat() == QNdefRecord::NfcRtd &&
                 QString(record.type()) == "s") {
            if (recordSize) { delete recordSize; recordSize = NULL; }
            recordSize = new NdefNfcSizeRecord(record);
            qDebug() << "Sp Size: " << size();
        }
        // Type
        else if (record.typeNameFormat() == QNdefRecord::NfcRtd &&
                 QString(record.type()) == "t") {
            if (recordType) { delete recordType; recordType = NULL; }
            recordType = new NdefNfcTypeRecord(record);
            qDebug() << "Sp Type: " << type();
        }
        else
        {
            // This class handles all records defined in the Smart Poster
            // specification, so this case should never happen for a valid
            // Smart Poster record in the current version.
            qDebug() << "Sp: Don't know how to handle this record";
        }
    }
示例#4
0
文件: texture.cpp 项目: redxdev/Wake
    Texture::Texture()
    {
        data = nullptr;
        width = 0;
        height = 0;
        comp = 0;

        initializeData();
    }
示例#5
0
文件: texture.cpp 项目: redxdev/Wake
    Texture::Texture(const Texture& other)
    {
        data = (unsigned char*) malloc(sizeof(unsigned char) * other.width * other.height * other.comp);
        memcpy(data, other.data, sizeof(unsigned char) * other.width * other.height * other.comp);
        width = other.width;
        height = other.height;
        comp = other.comp;

        initializeData();
    }
示例#6
0
文件: texture.cpp 项目: redxdev/Wake
    Texture::Texture(unsigned char* data, int width, int height, int comp, const std::string& path)
    {
        this->data = data;
        this->width = width;
        this->height = height;
        this->comp = comp;
        this->path = path;

        initializeData();
    }
示例#7
0
void runAutoTest(int argc, char **argv)
{
    printf("[%s] (automated testing w/ readback)\n", sSDKsample);

    if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") ) {
        cutilDeviceInit(argc, argv);
    } else {
        cudaSetDevice( cutGetMaxGflopsDeviceId() );
    }

    loadDefaultImage( argv[0] );

    if (argc > 1) {
        char *filename;
        if (cutGetCmdLineArgumentstr(argc, (const char **)argv, "file", &filename)) {
            initializeData(filename);
        }
    } else {
        loadDefaultImage( argv[0]);
    }

    g_CheckRender       = new CheckBackBuffer(imWidth, imHeight, sizeof(Pixel), false);
    g_CheckRender->setExecPath(argv[0]);

    Pixel *d_result;
    cutilSafeCall( cudaMalloc( (void **)&d_result, imWidth*imHeight*sizeof(Pixel)) );

    while (g_SobelDisplayMode <= 2) 
    {
        printf("AutoTest: %s <%s>\n", sSDKsample, filterMode[g_SobelDisplayMode]);

        sobelFilter(d_result, imWidth, imHeight, g_SobelDisplayMode, imageScale );

        cutilSafeCall( cudaThreadSynchronize() );

        cudaMemcpy(g_CheckRender->imageData(), d_result, imWidth*imHeight*sizeof(Pixel), cudaMemcpyDeviceToHost);

        g_CheckRender->savePGM(sOriginal[g_Index], false, NULL);

        if (!g_CheckRender->PGMvsPGM(sOriginal[g_Index], sReference[g_Index], MAX_EPSILON_ERROR, 0.15f)) {
            g_TotalErrors++;
        }
        g_Index++;
        g_SobelDisplayMode = (SobelDisplayMode)g_Index;
    }

    cutilSafeCall( cudaFree( d_result ) );
    delete g_CheckRender;

    if (!g_TotalErrors) 
        printf("TEST PASSED!\n");
    else 
        printf("TEST FAILED!\n");
}
        api::DirectionData DirectionReader::getDirectionData()
        {
            myOutDirectionData = initializeData();
            updateTimeForOffset();
            parsePlacement();
            parseValues();

            // need to make sure all the MarkData item times match the DirectionData time
            fixTimes();
            return returnData();
        }
void main(){
	float lambda = 0.95, gamma = 100;
	float t_final[m];

	initializeData();
	
	Estimate(lambda,gamma, t_final);
	
	printf("\n Theta: a0, b0 \n");
	printArray(t_final, m);
}
void loadDefaultImage( int argc, char ** argv ) {

    printf("Loading input image: lena.pgm\n");
    const char* image_filename = "lena.pgm";
    char* image_path = cutFindFilePath(image_filename, argv[0] );
    if (image_path == NULL) {
       printf( "FunctionPointers unable to find and load image file <%s>.\nExiting...\n", image_filename);
       shrQAFinishExit(argc, (const char **)argv, QA_FAILED);
    }
    initializeData( image_path, argc, argv );
    cutFree( image_path );
}
void loadDefaultImage( int argc, char ** argv ) {

    printf("Reading image: lena.pgm\n");
    const char* image_filename = "lena.pgm";
    char* image_path = cutFindFilePath(image_filename, argv[0] );
    if (image_path == 0) {
       printf( "Reading image failed.\n");
       exit(EXIT_FAILURE);
    }
    initializeData( image_path, argc, argv );
    cutFree( image_path );
}
示例#12
0
SceneInfoDialog::SceneInfoDialog( wxWindow* parent, int id, wxString title, wxPoint pos, wxSize size, int style ) : wxDialog( parent, id, title, pos, size, style )
{
	wxBoxSizer* mainSizer;
	mainSizer = new wxBoxSizer( wxVERTICAL );
	
	wxStaticBoxSizer* sceneInfoStaticSizer;
	sceneInfoStaticSizer = new wxStaticBoxSizer( new wxStaticBox( this, -1, wxT("Scene Info:") ), wxVERTICAL );
	
	wxGridSizer* mainGirdSizer;
	mainGirdSizer = new wxGridSizer( 2, 2, 0, 0 );
	
	objectCountStaticText = new wxStaticText( this, ID_DEFAULT, wxT("object count:"), wxDefaultPosition, wxDefaultSize, 0 );
	mainGirdSizer->Add( objectCountStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
	
	objectCountTextCtrl = new wxTextCtrl( this, ID_DEFAULT, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_READONLY );
	mainGirdSizer->Add( objectCountTextCtrl, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	vertexCountStaticText = new wxStaticText( this, ID_DEFAULT, wxT("vertex count:"), wxDefaultPosition, wxDefaultSize, 0 );
	mainGirdSizer->Add( vertexCountStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
	
	vertexCountTextCtrl = new wxTextCtrl( this, ID_DEFAULT, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_READONLY );
	mainGirdSizer->Add( vertexCountTextCtrl, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	countStaticText = new wxStaticText( this, ID_DEFAULT, wxT("edge count:"), wxDefaultPosition, wxDefaultSize, 0 );
	mainGirdSizer->Add( countStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
	
	edgeCountTextCtrl = new wxTextCtrl( this, ID_DEFAULT, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_READONLY );
	mainGirdSizer->Add( edgeCountTextCtrl, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	faceCountStaticText = new wxStaticText( this, ID_DEFAULT, wxT("face count:"), wxDefaultPosition, wxDefaultSize, 0 );
	mainGirdSizer->Add( faceCountStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
	
	faceCountTextCtrl = new wxTextCtrl( this, ID_DEFAULT, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_READONLY );
	mainGirdSizer->Add( faceCountTextCtrl, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	sceneInfoStaticSizer->Add( mainGirdSizer, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5 );
	
	mainSizer->Add( sceneInfoStaticSizer, 1, wxEXPAND|wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5 );
	
	wxBoxSizer* buttonSizer;
	buttonSizer = new wxBoxSizer( wxHORIZONTAL );
	
	closeButton = new wxButton( this, onCloseButtonPressSceneInfo, wxT("Close"), wxDefaultPosition, wxDefaultSize, 0 );
	buttonSizer->Add( closeButton, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	mainSizer->Add( buttonSizer, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
	
	this->SetSizer( mainSizer );
	this->Layout();
	Fit();
	initializeData();
}
示例#13
0
Q* create_queue()
{
	initializeData();
	Q* q = Q::create();
	assert_IllegalOp(q != NULL);	
	assert_IllegalOp(q->in_valid_range());
	
	++Q::current_count;
	
	q->start_offset = Q::get_start_offset(q);
	q->length = 0;
	
	return q;
}
示例#14
0
void loadDefaultImage(char* loc_exec) 
{
    printf("Reading image: lena.pgm\n"); 
	const char* image_filename = "lena.pgm"; 
    char* image_path = cutFindFilePath(image_filename, loc_exec); 
	
    if (image_path == 0) { 
       printf( "Reading image: lena.pgm failed.\n");
       exit(EXIT_FAILURE);
    }
	
    initializeData(image_path); 
    cutFree(image_path); 
}
示例#15
0
void MemBufferEntry::initializeData(MemOpsType::iterator mit)
{
  mit--; // skip itself

  MemBufferEntry *prevEntry = *mit;
  if (prevEntry->getChunkIndex() == getChunkIndex()) {
    // Copy from previous version
    I(prevEntry!=this);
    I(*(prevEntry->getVersionRef()) < *ver);
    initializeData(prevEntry);
  }else{
    // Copy from memory
    chunkCopy(getAddr(), getRealAddr(), chunkDataMask);
  }
}
示例#16
0
/* Modified utility function taken from CUDA samples */
void loadDefaultImage(char *loc_exec)
{

    printf("Reading image... \n");
    const char *image_filename = "lena.pgm";
    char *image_path = sdkFindFilePath(image_filename, loc_exec);

    if (image_path == NULL)
    {
        printf("Failed to read image file: <%s>\n", image_filename);
        exit(EXIT_FAILURE);
    }

    initializeData(image_path);
    free(image_path);
}
示例#17
0
// make the copy buffer if needed. 
// then copy the current data to the copy buffer and return the start of the copy.
//
MLSample* MLSignal::getCopy()
{
	if (!mCopy)
	{
		mCopy = allocateData(mSize);
		if (mCopy)
		{
			mCopyAligned = initializeData(mCopy, mSize);
		}
		else
		{
			std::cerr << "MLSignal::getCopy: out of memory!\n";
		}
	}
	std::copy(mDataAligned, mDataAligned + mSize, mCopyAligned);
	return mCopyAligned;
}
示例#18
0
MLSignal& MLSignal::operator= (const MLSignal& other)
{
	if (this != &other) // protect against self-assignment
	{
		if (mSize != other.mSize)
		{
			// 1: allocate new memory and copy the elements
			mSize = other.mSize;
			MLSample * newData = allocateData(mSize);
			MLSample * newDataAligned = initializeData(newData, mSize);
			std::copy(other.mDataAligned, other.mDataAligned + mSize, newDataAligned);

			// 2: deallocate old memory
			delete[] mData;
			
			// 3: assign the new memory to the object
			mData = newData;
			mDataAligned = newDataAligned;
			mConstantMask = other.mConstantMask;
			mWidth = other.mWidth;
			mHeight = other.mHeight;
			mDepth = other.mDepth;
			mHeightBits = other.mHeightBits;
			mWidthBits = other.mWidthBits;
			mDepthBits = other.mDepthBits;
			mRate = other.mRate;
		}
		else 
		{
			// keep existing data buffer.
			// copy other elements
			std::copy(other.mDataAligned, other.mDataAligned + this->mSize, mDataAligned);
			
			// copy other info
			mConstantMask = other.mConstantMask;
			mWidth = other.mWidth;
			mHeight = other.mHeight;
			mDepth = other.mDepth;
			mHeightBits = other.mHeightBits;
			mWidthBits = other.mWidthBits;
			mDepthBits = other.mDepthBits;
			mRate = other.mRate;
		}
	}
	return *this;
}
示例#19
0
MLSignal::MLSignal(const MLSignal& other) :
	mData(0),
	mDataAligned(0),
	mCopy(0),
	mCopyAligned(0)
{
	mSize = other.mSize;
	mData = allocateData(mSize);
	mDataAligned = initializeData(mData, mSize);
	mConstantMask = other.mConstantMask;
	mWidth = other.mWidth;
	mHeight = other.mHeight;
	mDepth = other.mDepth;
	mHeightBits = other.mHeightBits;
	mWidthBits = other.mWidthBits;
	mDepthBits = other.mDepthBits;
	mRate = other.mRate;
	std::copy(other.mDataAligned, other.mDataAligned + mSize, mDataAligned);
}
示例#20
0
MLSample* MLSignal::setDims (int width, int height, int depth)
{
	mDataAligned = 0;	
	// delete old
	if (mData)
	{
		delete[] mData;
	}

	mWidth = width;
	mHeight = height;
	mDepth = depth;
	mWidthBits = bitsToContain(width);
	mHeightBits = bitsToContain(height);
	mDepthBits = bitsToContain(depth);
	mSize = 1 << mWidthBits << mHeightBits << mDepthBits;
	mData = allocateData(mSize);	
	mDataAligned = initializeData(mData, mSize);	
	mConstantMask = mSize - 1;
	return mDataAligned;
}
示例#21
0
文件: Assignment.c 项目: castelom/OS
int main(void){
   
 /* Creating pipe */
    if(pipe(fd) < 0)
    {
        perror("pipe error"); /* Using perror() for the first time. */
        exit(1);
    }

    /* Just for interest, print out the fd values. */
    printf("pipe() was successful, fds are %d, %d\n", fd[0], fd[1]);
    // start threads and initialize semaphoros.
    initializeData();      
    sem_post(&full);
    pthread_create(&t_A,&attr,runnerThreadA, NULL); /*create the thread*/
    pthread_create(&t_B,&attr,runnerThreadB, NULL); /*create the thread*/
    
    //Wait threads and finish
    pthread_join(t_A,(void **)NULL);
    pthread_join(t_B,(void **)NULL);
    printf("Finish\n");

}
void runAutoTest(int argc, char **argv)
{
    printf("[%s] (automated testing w/ readback)\n", sSDKsample);

    if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") ) 
    {
       int device = cutilDeviceInit(argc, argv);
       if (device < 0) {
            printf("No CUDA Capable devices found, exiting...\n");
            shrQAFinishExit(argc, (const char **)argv, QA_WAIVED);
       }
	   checkDeviceMeetComputeSpec( argc, argv );
    } else {
       int dev = findCapableDevice(argc, argv);
       if( dev != -1 ) 
          cudaSetDevice( dev );
       else {
          cutilDeviceReset();
		  shrQAFinishExit2(g_bQAReadback, *pArgc, (const char **)pArgv, QA_PASSED);
       }
    }

    loadDefaultImage( argc, argv );

    if (argc > 1) {
        char *filename;
        if (cutGetCmdLineArgumentstr(argc, (const char **)argv, "file", &filename)) {
            initializeData(filename, argc, argv);
        }
    } else {
        loadDefaultImage( argc, argv );
    }

    g_CheckRender       = new CheckBackBuffer(imWidth, imHeight, sizeof(Pixel), false);
    g_CheckRender->setExecPath(argv[0]);

    Pixel *d_result;
    cutilSafeCall( cudaMalloc( (void **)&d_result, imWidth*imHeight*sizeof(Pixel)) );

    while (g_SobelDisplayMode <= 2) 
    {
        printf("AutoTest: %s <%s>\n", sSDKsample, filterMode[g_SobelDisplayMode]);

        sobelFilter(d_result, imWidth, imHeight, g_SobelDisplayMode, imageScale, blockOp, pointOp );

        cutilSafeCall( cutilDeviceSynchronize() );

        cudaMemcpy(g_CheckRender->imageData(), d_result, imWidth*imHeight*sizeof(Pixel), cudaMemcpyDeviceToHost);

        g_CheckRender->savePGM(sOriginal[g_Index], false, NULL);

        if (!g_CheckRender->PGMvsPGM(sOriginal[g_Index], sReference[g_Index], MAX_EPSILON_ERROR, 0.15f)) {
            g_TotalErrors++;
        }
        g_Index++;
        g_SobelDisplayMode = (SobelDisplayMode)g_Index;
    }

    cutilSafeCall( cudaFree( d_result ) );
    delete g_CheckRender;

    shrQAFinishExit(argc, (const char **)argv, (!g_TotalErrors ? QA_PASSED : QA_FAILED) );
}
示例#23
0
// inner part of dive
int 
CbcHeuristicDive::solution(double & solutionValue, int & numberNodes,
			   int & numberCuts, OsiRowCut ** cuts,
			   CbcSubProblem ** & nodes,
			   double * newSolution)
{
#ifdef DIVE_DEBUG
    int nRoundInfeasible = 0;
    int nRoundFeasible = 0;
#endif
    int reasonToStop = 0;
    double time1 = CoinCpuTime();
    int numberSimplexIterations = 0;
    int maxSimplexIterations = (model_->getNodeCount()) ? maxSimplexIterations_
                               : maxSimplexIterationsAtRoot_;
    // but can't be exactly coin_int_max
    maxSimplexIterations = CoinMin(maxSimplexIterations,COIN_INT_MAX>>3);
    OsiSolverInterface * solver = cloneBut(6); // was model_->solver()->clone();
# ifdef COIN_HAS_CLP
    OsiClpSolverInterface * clpSolver
    = dynamic_cast<OsiClpSolverInterface *> (solver);
    if (clpSolver) {
      ClpSimplex * clpSimplex = clpSolver->getModelPtr();
      int oneSolveIts = clpSimplex->maximumIterations();
      oneSolveIts = CoinMin(1000+2*(clpSimplex->numberRows()+clpSimplex->numberColumns()),oneSolveIts);
      clpSimplex->setMaximumIterations(oneSolveIts);
      if (!nodes) {
        // say give up easily
        clpSimplex->setMoreSpecialOptions(clpSimplex->moreSpecialOptions() | 64);
      } else {
	// get ray
	int specialOptions = clpSimplex->specialOptions();
	specialOptions &= ~0x3100000;
	specialOptions |= 32;
        clpSimplex->setSpecialOptions(specialOptions);
        clpSolver->setSpecialOptions(clpSolver->specialOptions() | 1048576);
	if ((model_->moreSpecialOptions()&16777216)!=0) {
	  // cutoff is constraint
	  clpSolver->setDblParam(OsiDualObjectiveLimit, COIN_DBL_MAX);
	}
      }
    }
# endif
    const double * lower = solver->getColLower();
    const double * upper = solver->getColUpper();
    const double * rowLower = solver->getRowLower();
    const double * rowUpper = solver->getRowUpper();
    const double * solution = solver->getColSolution();
    const double * objective = solver->getObjCoefficients();
    double integerTolerance = model_->getDblParam(CbcModel::CbcIntegerTolerance);
    double primalTolerance;
    solver->getDblParam(OsiPrimalTolerance, primalTolerance);

    int numberRows = matrix_.getNumRows();
    assert (numberRows <= solver->getNumRows());
    int numberIntegers = model_->numberIntegers();
    const int * integerVariable = model_->integerVariable();
    double direction = solver->getObjSense(); // 1 for min, -1 for max
    double newSolutionValue = direction * solver->getObjValue();
    int returnCode = 0;
    // Column copy
    const double * element = matrix_.getElements();
    const int * row = matrix_.getIndices();
    const CoinBigIndex * columnStart = matrix_.getVectorStarts();
    const int * columnLength = matrix_.getVectorLengths();
#ifdef DIVE_FIX_BINARY_VARIABLES
    // Row copy
    const double * elementByRow = matrixByRow_.getElements();
    const int * column = matrixByRow_.getIndices();
    const CoinBigIndex * rowStart = matrixByRow_.getVectorStarts();
    const int * rowLength = matrixByRow_.getVectorLengths();
#endif

    // Get solution array for heuristic solution
    int numberColumns = solver->getNumCols();
    memcpy(newSolution, solution, numberColumns*sizeof(double));

    // vectors to store the latest variables fixed at their bounds
    int* columnFixed = new int [numberIntegers];
    double* originalBound = new double [numberIntegers+2*numberColumns];
    double * lowerBefore = originalBound+numberIntegers;
    double * upperBefore = lowerBefore+numberColumns;
    memcpy(lowerBefore,lower,numberColumns*sizeof(double));
    memcpy(upperBefore,upper,numberColumns*sizeof(double));
    double * lastDjs=newSolution+numberColumns;
    bool * fixedAtLowerBound = new bool [numberIntegers];
    PseudoReducedCost * candidate = new PseudoReducedCost [numberIntegers];
    double * random = new double [numberIntegers];

    int maxNumberAtBoundToFix = static_cast<int> (floor(percentageToFix_ * numberIntegers));
    assert (!maxNumberAtBoundToFix||!nodes);

    // count how many fractional variables
    int numberFractionalVariables = 0;
    for (int i = 0; i < numberIntegers; i++) {
        random[i] = randomNumberGenerator_.randomDouble() + 0.3;
        int iColumn = integerVariable[i];
        double value = newSolution[iColumn];
        if (fabs(floor(value + 0.5) - value) > integerTolerance) {
            numberFractionalVariables++;
        }
    }

    const double* reducedCost = NULL;
    // See if not NLP
    if (model_->solverCharacteristics()->reducedCostsAccurate())
        reducedCost = solver->getReducedCost();

    int iteration = 0;
    while (numberFractionalVariables) {
        iteration++;

        // initialize any data
        initializeData();

        // select a fractional variable to bound
        int bestColumn = -1;
        int bestRound; // -1 rounds down, +1 rounds up
        bool canRound = selectVariableToBranch(solver, newSolution,
                                               bestColumn, bestRound);
        // if the solution is not trivially roundable, we don't try to round;
        // if the solution is trivially roundable, we try to round. However,
        // if the rounded solution is worse than the current incumbent,
        // then we don't round and proceed normally. In this case, the
        // bestColumn will be a trivially roundable variable
        if (canRound) {
            // check if by rounding all fractional variables
            // we get a solution with an objective value
            // better than the current best integer solution
            double delta = 0.0;
            for (int i = 0; i < numberIntegers; i++) {
                int iColumn = integerVariable[i];
                double value = newSolution[iColumn];
                if (fabs(floor(value + 0.5) - value) > integerTolerance) {
                    assert(downLocks_[i] == 0 || upLocks_[i] == 0);
                    double obj = objective[iColumn];
                    if (downLocks_[i] == 0 && upLocks_[i] == 0) {
                        if (direction * obj >= 0.0)
                            delta += (floor(value) - value) * obj;
                        else
                            delta += (ceil(value) - value) * obj;
                    } else if (downLocks_[i] == 0)
                        delta += (floor(value) - value) * obj;
                    else
                        delta += (ceil(value) - value) * obj;
                }
            }
            if (direction*(solver->getObjValue() + delta) < solutionValue) {
#ifdef DIVE_DEBUG
                nRoundFeasible++;
#endif
		if (!nodes||bestColumn<0) {
		  // Round all the fractional variables
		  for (int i = 0; i < numberIntegers; i++) {
                    int iColumn = integerVariable[i];
                    double value = newSolution[iColumn];
                    if (fabs(floor(value + 0.5) - value) > integerTolerance) {
		      assert(downLocks_[i] == 0 || upLocks_[i] == 0);
		      if (downLocks_[i] == 0 && upLocks_[i] == 0) {
			if (direction * objective[iColumn] >= 0.0)
			  newSolution[iColumn] = floor(value);
			else
			  newSolution[iColumn] = ceil(value);
		      } else if (downLocks_[i] == 0)
			newSolution[iColumn] = floor(value);
		      else
			newSolution[iColumn] = ceil(value);
                    }
		  }
		  break;
		} else {
		  // can't round if going to use in branching
		  int i;
		  for (i = 0; i < numberIntegers; i++) {
		    int iColumn = integerVariable[i];
		    double value = newSolution[bestColumn];
		    if (fabs(floor(value + 0.5) - value) > integerTolerance) {
		      if (iColumn==bestColumn) {
			assert(downLocks_[i] == 0 || upLocks_[i] == 0);
			double obj = objective[bestColumn];
			if (downLocks_[i] == 0 && upLocks_[i] == 0) {
			  if (direction * obj >= 0.0)
                            bestRound=-1;
			  else
                            bestRound=1;
			} else if (downLocks_[i] == 0)
			  bestRound=-1;
			else
			  bestRound=1;
			break;
		      }
		    }
		  }
		}
	    }
#ifdef DIVE_DEBUG
            else
                nRoundInfeasible++;
#endif
        }

        // do reduced cost fixing
#ifdef DIVE_DEBUG
        int numberFixed = reducedCostFix(solver);
        std::cout << "numberReducedCostFixed = " << numberFixed << std::endl;
#else
        reducedCostFix(solver);
#endif

        int numberAtBoundFixed = 0;
#ifdef DIVE_FIX_BINARY_VARIABLES
        // fix binary variables based on pseudo reduced cost
        if (binVarIndex_.size()) {
            int cnt = 0;
            int n = static_cast<int>(binVarIndex_.size());
            for (int j = 0; j < n; j++) {
                int iColumn1 = binVarIndex_[j];
                double value = newSolution[iColumn1];
                if (fabs(value) <= integerTolerance &&
                        lower[iColumn1] != upper[iColumn1]) {
                    double maxPseudoReducedCost = 0.0;
#ifdef DIVE_DEBUG
                    std::cout << "iColumn1 = " << iColumn1 << ", value = " << value << std::endl;
#endif
                    int iRow = vbRowIndex_[j];
                    double chosenValue = 0.0;
                    for (int k = rowStart[iRow]; k < rowStart[iRow] + rowLength[iRow]; k++) {
                        int iColumn2 = column[k];
#ifdef DIVE_DEBUG
                        std::cout << "iColumn2 = " << iColumn2 << std::endl;
#endif
                        if (iColumn1 != iColumn2) {
                            double pseudoReducedCost = fabs(reducedCost[iColumn2] *
                                                            elementByRow[k]);
#ifdef DIVE_DEBUG
                            int k2;
                            for (k2 = rowStart[iRow]; k2 < rowStart[iRow] + rowLength[iRow]; k2++) {
                                if (column[k2] == iColumn1)
                                    break;
                            }
                            std::cout << "reducedCost[" << iColumn2 << "] = "
                                      << reducedCost[iColumn2]
                                      << ", elementByRow[" << iColumn2 << "] = " << elementByRow[k]
                                      << ", elementByRow[" << iColumn1 << "] = " << elementByRow[k2]
                                      << ", pseudoRedCost = " << pseudoReducedCost
                                      << std::endl;
#endif
                            if (pseudoReducedCost > maxPseudoReducedCost)
                                maxPseudoReducedCost = pseudoReducedCost;
                        } else {
                            // save value
                            chosenValue = fabs(elementByRow[k]);
                        }
                    }
                    assert (chosenValue);
                    maxPseudoReducedCost /= chosenValue;
#ifdef DIVE_DEBUG
                    std::cout << ", maxPseudoRedCost = " << maxPseudoReducedCost << std::endl;
#endif
                    candidate[cnt].var = iColumn1;
                    candidate[cnt++].pseudoRedCost = maxPseudoReducedCost;
                }
            }
#ifdef DIVE_DEBUG
            std::cout << "candidates for rounding = " << cnt << std::endl;
#endif
            std::sort(candidate, candidate + cnt, compareBinaryVars);
            for (int i = 0; i < cnt; i++) {
                int iColumn = candidate[i].var;
                if (numberAtBoundFixed < maxNumberAtBoundToFix) {
                    columnFixed[numberAtBoundFixed] = iColumn;
                    originalBound[numberAtBoundFixed] = upper[iColumn];
                    fixedAtLowerBound[numberAtBoundFixed] = true;
                    solver->setColUpper(iColumn, lower[iColumn]);
                    numberAtBoundFixed++;
                    if (numberAtBoundFixed == maxNumberAtBoundToFix)
                        break;
                }
            }
        }
#endif

        // fix other integer variables that are at their bounds
        int cnt = 0;
#ifdef GAP
        double gap = 1.0e30;
#endif
        if (reducedCost && true) {
#ifndef JJF_ONE
            cnt = fixOtherVariables(solver, solution, candidate, random);
#else
#ifdef GAP
            double cutoff = model_->getCutoff() ;
            if (cutoff < 1.0e20 && false) {
                double direction = solver->getObjSense() ;
                gap = cutoff - solver->getObjValue() * direction ;
                gap *= 0.1; // Fix more if plausible
                double tolerance;
                solver->getDblParam(OsiDualTolerance, tolerance) ;
                if (gap <= 0.0)
                    gap = tolerance;
                gap += 100.0 * tolerance;
            }
            int nOverGap = 0;
#endif
            int numberFree = 0;
            int numberFixed = 0;
            for (int i = 0; i < numberIntegers; i++) {
                int iColumn = integerVariable[i];
                if (upper[iColumn] > lower[iColumn]) {
                    numberFree++;
                    double value = newSolution[iColumn];
                    if (fabs(floor(value + 0.5) - value) <= integerTolerance) {
                        candidate[cnt].var = iColumn;
                        candidate[cnt++].pseudoRedCost =
                            fabs(reducedCost[iColumn] * random[i]);
#ifdef GAP
                        if (fabs(reducedCost[iColumn]) > gap)
                            nOverGap++;
#endif
                    }
                } else {
                    numberFixed++;
                }
            }
#ifdef GAP
            int nLeft = maxNumberAtBoundToFix - numberAtBoundFixed;
#ifdef CLP_INVESTIGATE4
            printf("cutoff %g obj %g nover %d - %d free, %d fixed\n",
                   cutoff, solver->getObjValue(), nOverGap, numberFree, numberFixed);
#endif
            if (nOverGap > nLeft && true) {
                nOverGap = CoinMin(nOverGap, nLeft + maxNumberAtBoundToFix / 2);
                maxNumberAtBoundToFix += nOverGap - nLeft;
            }
#else
#ifdef CLP_INVESTIGATE4
            printf("cutoff %g obj %g - %d free, %d fixed\n",
                   model_->getCutoff(), solver->getObjValue(), numberFree, numberFixed);
#endif
#endif
#endif
        } else {
            for (int i = 0; i < numberIntegers; i++) {
                int iColumn = integerVariable[i];
                if (upper[iColumn] > lower[iColumn]) {
                    double value = newSolution[iColumn];
                    if (fabs(floor(value + 0.5) - value) <= integerTolerance) {
                        candidate[cnt].var = iColumn;
                        candidate[cnt++].pseudoRedCost = numberIntegers - i;
                    }
                }
            }
        }
        std::sort(candidate, candidate + cnt, compareBinaryVars);
        for (int i = 0; i < cnt; i++) {
            int iColumn = candidate[i].var;
            if (upper[iColumn] > lower[iColumn]) {
                double value = newSolution[iColumn];
                if (fabs(floor(value + 0.5) - value) <= integerTolerance &&
                        numberAtBoundFixed < maxNumberAtBoundToFix) {
                    // fix the variable at one of its bounds
                    if (fabs(lower[iColumn] - value) <= integerTolerance) {
                        columnFixed[numberAtBoundFixed] = iColumn;
                        originalBound[numberAtBoundFixed] = upper[iColumn];
                        fixedAtLowerBound[numberAtBoundFixed] = true;
                        solver->setColUpper(iColumn, lower[iColumn]);
                        numberAtBoundFixed++;
                    } else if (fabs(upper[iColumn] - value) <= integerTolerance) {
                        columnFixed[numberAtBoundFixed] = iColumn;
                        originalBound[numberAtBoundFixed] = lower[iColumn];
                        fixedAtLowerBound[numberAtBoundFixed] = false;
                        solver->setColLower(iColumn, upper[iColumn]);
                        numberAtBoundFixed++;
                    }
                    if (numberAtBoundFixed == maxNumberAtBoundToFix)
                        break;
                }
            }
        }
#ifdef DIVE_DEBUG
        std::cout << "numberAtBoundFixed = " << numberAtBoundFixed << std::endl;
#endif

        double originalBoundBestColumn;
        double bestColumnValue;
	int whichWay;
        if (bestColumn >= 0) {
	    bestColumnValue = newSolution[bestColumn];
            if (bestRound < 0) {
                originalBoundBestColumn = upper[bestColumn];
                solver->setColUpper(bestColumn, floor(bestColumnValue));
		whichWay=0;
            } else {
                originalBoundBestColumn = lower[bestColumn];
                solver->setColLower(bestColumn, ceil(bestColumnValue));
		whichWay=1;
            }
        } else {
            break;
        }
        int originalBestRound = bestRound;
        int saveModelOptions = model_->specialOptions();
	
        while (1) {

            model_->setSpecialOptions(saveModelOptions | 2048);
            solver->resolve();
            model_->setSpecialOptions(saveModelOptions);
            if (!solver->isAbandoned()&&!solver->isIterationLimitReached()) {
                numberSimplexIterations += solver->getIterationCount();
            } else {
                numberSimplexIterations = maxSimplexIterations + 1;
		reasonToStop += 100;
                break;
            }

            if (!solver->isProvenOptimal()) {
	        if (nodes) {
		  if (solver->isProvenPrimalInfeasible()) {
		    if (maxSimplexIterationsAtRoot_!=COIN_INT_MAX) {
		      // stop now
		      printf("stopping on first infeasibility\n");
		      break;
		    } else if (cuts) {
		      // can do conflict cut
		      printf("could do intermediate conflict cut\n");
		      bool localCut;
		      OsiRowCut * cut = model_->conflictCut(solver,localCut);
		      if (cut) {
			if (!localCut) {
			  model_->makePartialCut(cut,solver);
			  cuts[numberCuts++]=cut;
			} else {
			  delete cut;
			}
		      }
		    }
		  } else {
		    reasonToStop += 10;
		    break;
		  }
		}
                if (numberAtBoundFixed > 0) {
                    // Remove the bound fix for variables that were at bounds
                    for (int i = 0; i < numberAtBoundFixed; i++) {
                        int iColFixed = columnFixed[i];
                        if (fixedAtLowerBound[i])
                            solver->setColUpper(iColFixed, originalBound[i]);
                        else
                            solver->setColLower(iColFixed, originalBound[i]);
                    }
                    numberAtBoundFixed = 0;
                } else if (bestRound == originalBestRound) {
                    bestRound *= (-1);
		    whichWay |=2;
                    if (bestRound < 0) {
                        solver->setColLower(bestColumn, originalBoundBestColumn);
                        solver->setColUpper(bestColumn, floor(bestColumnValue));
                    } else {
                        solver->setColLower(bestColumn, ceil(bestColumnValue));
                        solver->setColUpper(bestColumn, originalBoundBestColumn);
                    }
                } else
                    break;
            } else
                break;
        }

        if (!solver->isProvenOptimal() ||
                direction*solver->getObjValue() >= solutionValue) {
            reasonToStop += 1;
        } else if (iteration > maxIterations_) {
            reasonToStop += 2;
        } else if (CoinCpuTime() - time1 > maxTime_) {
            reasonToStop += 3;
        } else if (numberSimplexIterations > maxSimplexIterations) {
            reasonToStop += 4;
            // also switch off
#ifdef CLP_INVESTIGATE
            printf("switching off diving as too many iterations %d, %d allowed\n",
                   numberSimplexIterations, maxSimplexIterations);
#endif
            when_ = 0;
        } else if (solver->getIterationCount() > 1000 && iteration > 3 && !nodes) {
            reasonToStop += 5;
            // also switch off
#ifdef CLP_INVESTIGATE
            printf("switching off diving one iteration took %d iterations (total %d)\n",
                   solver->getIterationCount(), numberSimplexIterations);
#endif
            when_ = 0;
        }

        memcpy(newSolution, solution, numberColumns*sizeof(double));
        numberFractionalVariables = 0;
	double sumFractionalVariables=0.0;
        for (int i = 0; i < numberIntegers; i++) {
            int iColumn = integerVariable[i];
            double value = newSolution[iColumn];
	    double away = fabs(floor(value + 0.5) - value);
            if (away > integerTolerance) {
                numberFractionalVariables++;
		sumFractionalVariables += away;
            }
        }
	if (nodes) {
	  // save information
	  //branchValues[numberNodes]=bestColumnValue;
	  //statuses[numberNodes]=whichWay+(bestColumn<<2);
	  //bases[numberNodes]=solver->getWarmStart();
	  ClpSimplex * simplex = clpSolver->getModelPtr();
	  CbcSubProblem * sub =
	    new CbcSubProblem(clpSolver,lowerBefore,upperBefore,
			  simplex->statusArray(),numberNodes);
	  nodes[numberNodes]=sub;
	  // other stuff
	  sub->branchValue_=bestColumnValue;
	  sub->problemStatus_=whichWay;
	  sub->branchVariable_=bestColumn;
	  sub->objectiveValue_ = simplex->objectiveValue();
	  sub->sumInfeasibilities_ = sumFractionalVariables;
	  sub->numberInfeasibilities_ = numberFractionalVariables;
	  printf("DiveNode %d column %d way %d bvalue %g obj %g\n",
		 numberNodes,sub->branchVariable_,sub->problemStatus_,
		 sub->branchValue_,sub->objectiveValue_);
	  numberNodes++;
	  if (solver->isProvenOptimal()) {
	    memcpy(lastDjs,solver->getReducedCost(),numberColumns*sizeof(double));
	    memcpy(lowerBefore,lower,numberColumns*sizeof(double));
	    memcpy(upperBefore,upper,numberColumns*sizeof(double));
	  }
	}
	if (!numberFractionalVariables||reasonToStop)
	  break;
    }
    if (nodes) {
      printf("Exiting dive for reason %d\n",reasonToStop);
      if (reasonToStop>1) {
	printf("problems in diving\n");
	int whichWay=nodes[numberNodes-1]->problemStatus_;
	CbcSubProblem * sub;
	if ((whichWay&2)==0) {
	  // leave both ways
	  sub = new CbcSubProblem(*nodes[numberNodes-1]);
	  nodes[numberNodes++]=sub;
	} else {
	  sub = nodes[numberNodes-1];
	}
	if ((whichWay&1)==0)
	  sub->problemStatus_=whichWay|1;
	else
	  sub->problemStatus_=whichWay&~1;
      }
      if (!numberNodes) {
	// was good at start! - create fake
	clpSolver->resolve();
	ClpSimplex * simplex = clpSolver->getModelPtr();
	CbcSubProblem * sub =
	  new CbcSubProblem(clpSolver,lowerBefore,upperBefore,
			    simplex->statusArray(),numberNodes);
	nodes[numberNodes]=sub;
	// other stuff
	sub->branchValue_=0.0;
	sub->problemStatus_=0;
	sub->branchVariable_=-1;
	sub->objectiveValue_ = simplex->objectiveValue();
	sub->sumInfeasibilities_ = 0.0;
	sub->numberInfeasibilities_ = 0;
	printf("DiveNode %d column %d way %d bvalue %g obj %g\n",
	       numberNodes,sub->branchVariable_,sub->problemStatus_,
	       sub->branchValue_,sub->objectiveValue_);
	numberNodes++;
	assert (solver->isProvenOptimal());
      }
      nodes[numberNodes-1]->problemStatus_ |= 256*reasonToStop;
      // use djs as well
      if (solver->isProvenPrimalInfeasible()&&cuts) {
	// can do conflict cut and re-order
	printf("could do final conflict cut\n");
	bool localCut;
	OsiRowCut * cut = model_->conflictCut(solver,localCut);
	if (cut) {
	  printf("cut - need to use conflict and previous djs\n");
	  if (!localCut) {
	    model_->makePartialCut(cut,solver);
	    cuts[numberCuts++]=cut;
	  } else {
	    delete cut;
	  }
	} else {
	  printf("bad conflict - just use previous djs\n");
	}
      }
    }
    
    // re-compute new solution value
    double objOffset = 0.0;
    solver->getDblParam(OsiObjOffset, objOffset);
    newSolutionValue = -objOffset;
    for (int i = 0 ; i < numberColumns ; i++ )
      newSolutionValue += objective[i] * newSolution[i];
    newSolutionValue *= direction;
    //printf("new solution value %g %g\n",newSolutionValue,solutionValue);
    if (newSolutionValue < solutionValue && !reasonToStop) {
      double * rowActivity = new double[numberRows];
      memset(rowActivity, 0, numberRows*sizeof(double));
      // paranoid check
      memset(rowActivity, 0, numberRows*sizeof(double));
      for (int i = 0; i < numberColumns; i++) {
	int j;
	double value = newSolution[i];
	if (value) {
	  for (j = columnStart[i];
	       j < columnStart[i] + columnLength[i]; j++) {
	    int iRow = row[j];
	    rowActivity[iRow] += value * element[j];
	  }
	}
      }
      // check was approximately feasible
      bool feasible = true;
      for (int i = 0; i < numberRows; i++) {
	if (rowActivity[i] < rowLower[i]) {
	  if (rowActivity[i] < rowLower[i] - 1000.0*primalTolerance)
	    feasible = false;
	} else if (rowActivity[i] > rowUpper[i]) {
	  if (rowActivity[i] > rowUpper[i] + 1000.0*primalTolerance)
	    feasible = false;
	}
      }
      for (int i = 0; i < numberIntegers; i++) {
	int iColumn = integerVariable[i];
	double value = newSolution[iColumn];
	if (fabs(floor(value + 0.5) - value) > integerTolerance) {
	  feasible = false;
	  break;
	}
      }
      if (feasible) {
	// new solution
	solutionValue = newSolutionValue;
	//printf("** Solution of %g found by CbcHeuristicDive\n",newSolutionValue);
	//if (cuts)
	//clpSolver->getModelPtr()->writeMps("good8.mps", 2);
	returnCode = 1;
      } else {
	// Can easily happen
	//printf("Debug CbcHeuristicDive giving bad solution\n");
      }
      delete [] rowActivity;
    }

#ifdef DIVE_DEBUG
    std::cout << "nRoundInfeasible = " << nRoundInfeasible
              << ", nRoundFeasible = " << nRoundFeasible
              << ", returnCode = " << returnCode
              << ", reasonToStop = " << reasonToStop
              << ", simplexIts = " << numberSimplexIterations
              << ", iterations = " << iteration << std::endl;
#endif

    delete [] columnFixed;
    delete [] originalBound;
    delete [] fixedAtLowerBound;
    delete [] candidate;
    delete [] random;
    delete [] downArray_;
    downArray_ = NULL;
    delete [] upArray_;
    upArray_ = NULL;
    delete solver;
    return returnCode;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void InitialReconstructionInitializer::execute()
{

  SinogramPtr sinogram = getSinogram();
  TomoInputsPtr input = getTomoInputs();
  GeometryPtr geometry = getGeometry();
  AdvancedParametersPtr advParams = getAdvParams();

  Real_t sum = 0, max;

#ifndef FORWARD_PROJECT_MODE
  input->delta_xz = sinogram->delta_r * input->delta_xz;
  input->delta_xy = input->delta_xz;
  //Find the maximum absolute tilt angle
  max = absMaxArray(sinogram->angles);

  //The max is going to be used to reconstruct a large area
//However if its close to 90 this would result in a very large value - so truncate
  if(max > MBIR::Constants::k_MaxAngleStretch)
  { max = MBIR::Constants::k_MaxAngleStretch; }

  // Convert Max to radians
  max = max * M_PI / 180.0;
  input->LengthZ *= advParams->Z_STRETCH;
  input->LengthZ /= (input->interpolateFactor * sinogram->delta_r);
  //interpolation_factor;
  input->LengthZ = floor(input->LengthZ + 0.5) * input->interpolateFactor * sinogram->delta_r; //interpolation_factor;

  geometry->LengthX = ((sinogram->N_r * sinogram->delta_r));
  geometry->N_x = floor(geometry->LengthX / input->delta_xz); //Number of voxels in x direction

  if(1 == input->extendObject)
  {
    std::cout << "KNOWN BUG FIX NEEDED HERE IF MAX = 90 degrees" << std::endl;
    geometry->LengthX = advParams->X_SHRINK_FACTOR * ((sinogram->N_r * sinogram->delta_r) / cos(max)) + input->LengthZ * tan(max);
    geometry->LengthX /= (input->interpolateFactor * sinogram->delta_r);
    geometry->LengthX = floor(geometry->LengthX + 0.5) * input->interpolateFactor * sinogram->delta_r;
  }


#else
  geometry->LengthX = ((sinogram->N_r * sinogram->delta_r));
#endif//Forward projector mode end if
//  Geometry->LengthY = (Geometry->EndSlice- Geometry->StartSlice)*Geometry->delta_xy;
  geometry->LengthY = (input->yEnd - input->yStart + 1) * sinogram->delta_t;

  geometry->N_x = floor(geometry->LengthX / input->delta_xz); //Number of voxels in x direction
  geometry->N_z = floor(input->LengthZ / input->delta_xz); //Number of voxels in z direction
  geometry->N_y = floor(geometry->LengthY / input->delta_xy); //Number of measurements in y direction

  std::stringstream ss;

  ss << "Geometry->LengthX=" << geometry->LengthX << " nm"  << std::endl;
  ss << "Geometry->LengthY=" << geometry->LengthY << " nm"  << std::endl;
  ss << "Geometry->LengthZ=" << input->LengthZ << " nm"  << std::endl;

  ss << "Geometry->Nz=" <<  geometry->N_z << std::endl;
  ss << "Geometry->Nx=" <<  geometry->N_x << std::endl;
  ss << "Geometry->Ny=" <<  geometry->N_y << std::endl;

  size_t dims[3] =
  { geometry->N_z, geometry->N_x, geometry->N_y };
  geometry->Object = RealVolumeType::New(dims, "Geometry.Object");

  // geometry->Object = (DATA_TYPE ***)get_3D(geometry->N_z, geometry->N_x, geometry->N_y, sizeof(DATA_TYPE));//Allocate space for the 3-D object
//Coordinates of the left corner of the x-z object
  geometry->x0 = -geometry->LengthX / 2;
  geometry->z0 = -input->LengthZ / 2;
  // Geometry->y0 = -(sinogram->N_t * sinogram->delta_t)/2 + Geometry->StartSlice*Geometry->delta_xy;
  geometry->y0 = -(geometry->LengthY) / 2;

  ss << "Geometry->X0=" << geometry->x0 << std::endl;
  ss << "Geometry->Y0=" << geometry->y0 << std::endl;
  ss << "Geometry->Z0=" << geometry->z0 << std::endl;

  if(getVeryVerbose())
  {
    std::cout << ss.str() << std::endl;
  }
  // Now we actually initialize the data to something. If a subclass is involved
  // then the subclasses version of initializeData() will be used instead
  initializeData();

  //Doing a check sum to verify with matlab
  for (uint16_t y = 0; y < geometry->N_y; y++)
  {
    sum = 0;
    for (uint16_t x = 0; x < geometry->N_x; x++)
    {
      for (uint16_t z = 0; z < geometry->N_z; z++)
      {
//        sum += geometry->Object->d[k][j][i];
        sum += geometry->Object->getValue(z, x, y);
      }
    }
    ss << "Geometry check sum Y:" << y << " Value:" << sum << std::endl;
  }
  //End of check sum
  if (getVeryVerbose())
  {
    std::cout << ss.str() << std::endl;
  }
  setErrorCondition(0);
  setErrorMessage("");
  ss.str("");
  ss << getNameOfClass() << " Complete";
  notify(ss.str(), 0, UpdateProgressMessage);
}
示例#25
0
void KrecipesView::wizard( bool force )
{
	KConfigGroup config = KGlobal::config()->group( "Wizard" );
	bool setupDone = config.readEntry( "SystemSetup", false );

	QString setupVersion = config.readEntry( "Version", "0.3" );  // By default assume it's 0.3. This parameter didn't exist in that version yet.

	if ( !setupDone || ( setupVersion.toDouble() < 0.5 ) || force )  // The config structure changed in version 0.4 to have DBType and Config Structure version
	{

		bool setupUser, initData, doUSDAImport, adminEnabled;
		QString adminUser, adminPass, user, pass, host, client, dbName;
		int port;
		bool isRemote;

		QPointer<SetupAssistant> setupAssistant = new SetupAssistant( this );
		if ( setupAssistant->exec() == QDialog::Accepted )
		{
			config.sync();
			config = KGlobal::config()->group( "DBType" );
			dbType = config.readEntry( "Type", "SQLite" );

			kDebug() << "Setting up" ;
			setupAssistant->getOptions( setupUser, initData, doUSDAImport );
			kDebug()<<" setupUser :"******" initData :"<<initData<<" doUSDAImport :"<<doUSDAImport;
			// Setup user if necessary
			if ( ( dbType == "MySQL" || dbType == "PostgreSQL" ) && setupUser )  // Don't setup user if checkbox of existing user... was set
			{
				kDebug() << "Setting up user";
				setupAssistant->getAdminInfo( adminEnabled, adminUser, adminPass, dbType );
				setupAssistant->getServerInfo( isRemote, host, client, dbName, user, pass, port );

				if ( !adminEnabled )  // Use root without password
				{
					kDebug() << "Using default admin";
					if ( dbType == "MySQL" )
						adminUser = "******";
					else if ( dbType == "PostgreSQL" )
						adminUser = "******";
					adminPass.clear();
				}
				if ( !isRemote )  // Use localhost
				{
					kDebug() << "Using localhost";
					host = "localhost";
					client = "localhost";
				}

				setupUserPermissions( host, client, dbName, user, pass, adminUser, adminPass, port );
			}

			// Initialize database with data if requested
			if ( initData ) {
				kDebug();
				setupAssistant->getServerInfo( isRemote, host, client, dbName, user, pass, port );
				initializeData( host, dbName, user, pass, port ); // Populate data as normal user
			}

			if ( doUSDAImport ) {
				kDebug()<<" import USDA";
				// Open the DB first
				setupAssistant->getServerInfo( isRemote, host, client, dbName, user, pass, port ); //only used if needed by backend
				kDebug()<<" dbName :"<<dbName<<" user :"******" pass :"******" port :"<<port;
				RecipeDB *db = RecipeDB::createDatabase( dbType, host, user, pass, dbName, port, dbName );
				kDebug()<<" database created :"<<db;
				// Import the data
				if ( db ) {
					kDebug()<<" try to connect";
					db->connect();

					if ( db->ok() ) {
						ProgressInterface pi(this);
						pi.listenOn(db);
						db->importUSDADatabase();
					}
					kDebug()<<" close";
					//close the database whether ok() or not
					delete db;
				}
			}

			//we can do a faster usda import if this is done after it
			if ( initData ) {
				kDebug()<<" initData :"<<initData;
				RecipeDB *db = RecipeDB::createDatabase( dbType, host, user, pass, dbName, port, dbName );
				if ( db ) {
					kDebug()<<" dbName :"<<dbName<<" user :"******" pass :"******" port :"<<port;
					db->connect();

					if ( db->ok() ) {
						kDebug()<<" import sample";
						db->importSamples();
					}

					//close the database whether ok() or not
					kDebug()<<" close db";
					delete db;
				}
			}

		}
		delete setupAssistant;
	}
}
示例#26
0
//#############################################################################
MibSHeuristic::MibSHeuristic(MibSModel * model)
{

  initializeData(model);

}
示例#27
0
NewPlaneDialog::NewPlaneDialog( wxWindow* parent, int id, wxString title, wxPoint pos, wxSize size, int style ) : wxDialog( parent, id, title, pos, size, style )
{
	wxBoxSizer* mainSizer;
	mainSizer = new wxBoxSizer( wxVERTICAL );
	
	wxStaticBoxSizer* newPlaneStaticSizer;
	newPlaneStaticSizer = new wxStaticBoxSizer( new wxStaticBox( this, -1, wxT("New Plane:") ), wxVERTICAL );
	
	wxGridSizer* mainGirdSizer;
	mainGirdSizer = new wxGridSizer( 2, 2, 0, 0 );
	
	xStaticText = new wxStaticText( this, ID_DEFAULT, wxT("x:"), wxDefaultPosition, wxDefaultSize, 0 );
	mainGirdSizer->Add( xStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
	
	xTextCtrl = new wxTextCtrl( this, ID_DEFAULT, wxT(""), wxDefaultPosition, wxDefaultSize, 0 ,wxTextValidator(wxFILTER_NUMERIC,NULL));
	mainGirdSizer->Add( xTextCtrl, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	yStaticText = new wxStaticText( this, ID_DEFAULT, wxT("y:"), wxDefaultPosition, wxDefaultSize, 0 );
	mainGirdSizer->Add( yStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
	
	yTextCtrl = new wxTextCtrl( this, ID_DEFAULT, wxT(""), wxDefaultPosition, wxDefaultSize, 0 ,wxTextValidator(wxFILTER_NUMERIC,NULL));
	mainGirdSizer->Add( yTextCtrl, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	zStaticText = new wxStaticText( this, ID_DEFAULT, wxT("z:"), wxDefaultPosition, wxDefaultSize, 0 );
	mainGirdSizer->Add( zStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
	
	zTextCtrl = new wxTextCtrl( this, ID_DEFAULT, wxT(""), wxDefaultPosition, wxDefaultSize, 0 ,wxTextValidator(wxFILTER_NUMERIC,NULL));
	mainGirdSizer->Add( zTextCtrl, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	lengthStaticText = new wxStaticText( this, ID_DEFAULT, wxT("length:"), wxDefaultPosition, wxDefaultSize, 0 );
	mainGirdSizer->Add( lengthStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
	
	lengthTextCtrl = new wxTextCtrl( this, ID_DEFAULT, wxT(""), wxDefaultPosition, wxDefaultSize, 0 ,wxTextValidator(wxFILTER_NUMERIC,NULL));
	mainGirdSizer->Add( lengthTextCtrl, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	widthStaticText = new wxStaticText( this, ID_DEFAULT, wxT("width:"), wxDefaultPosition, wxDefaultSize, 0 );
	mainGirdSizer->Add( widthStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
	
	widthTextCtrl = new wxTextCtrl( this, ID_DEFAULT, wxT(""), wxDefaultPosition, wxDefaultSize, 0 ,wxTextValidator(wxFILTER_NUMERIC,NULL));
	mainGirdSizer->Add( widthTextCtrl, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	segmentLStaticText = new wxStaticText( this, ID_DEFAULT, wxT("segment length:"), wxDefaultPosition, wxDefaultSize, 0 );
	mainGirdSizer->Add( segmentLStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
	
	segmentLTextCtrl = new wxTextCtrl( this, ID_DEFAULT, wxT(""), wxDefaultPosition, wxDefaultSize, 0 ,wxTextValidator(wxFILTER_NUMERIC,NULL));
	mainGirdSizer->Add( segmentLTextCtrl, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	segmentWStaticText = new wxStaticText( this, ID_DEFAULT, wxT("segment width:"), wxDefaultPosition, wxDefaultSize, 0 );
	mainGirdSizer->Add( segmentWStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
	
	segmentWTextCtrl = new wxTextCtrl( this, ID_DEFAULT, wxT(""), wxDefaultPosition, wxDefaultSize, 0 ,wxTextValidator(wxFILTER_NUMERIC,NULL));
	mainGirdSizer->Add( segmentWTextCtrl, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	axisStaticText = new wxStaticText( this, ID_DEFAULT, wxT("axis:"), wxDefaultPosition, wxDefaultSize, 0 );
	mainGirdSizer->Add( axisStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
	
	wxString axisChoiceChoices[] = { wxT("x"), wxT("y"), wxT("z") };
	int axisChoiceNChoices = sizeof( axisChoiceChoices ) / sizeof( wxString );
	axisChoice = new wxChoice( this, ID_DEFAULT, wxDefaultPosition, wxDefaultSize, axisChoiceNChoices, axisChoiceChoices, 0 );
	mainGirdSizer->Add( axisChoice, 0, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	newPlaneStaticSizer->Add( mainGirdSizer, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	mainSizer->Add( newPlaneStaticSizer, 1, wxEXPAND|wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5 );
	
	wxBoxSizer* buttonSizer;
	buttonSizer = new wxBoxSizer( wxHORIZONTAL );
	
	OKButton = new wxButton( this, onOKButtonPressPlane, wxT("OK"), wxDefaultPosition, wxDefaultSize, 0 );
	buttonSizer->Add( OKButton, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	cancelButton = new wxButton( this, onCancelButtonPressPlane, wxT("Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
	buttonSizer->Add( cancelButton, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
	
	mainSizer->Add( buttonSizer, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
	
	this->SetSizer( mainSizer );
	this->Layout();
	Fit();
	initializeData();
}
int main(int argc, char** argv) 
{
	pArgc = &argc;
	pArgv = argv;

	shrQAStart(argc, argv);

    if (argc > 1) {
        if (cutCheckCmdLineFlag(argc, (const char **)argv, "help")) {
            printHelp();
        }
        if (cutCheckCmdLineFlag(argc, (const char **)argv, "qatest") ||
            cutCheckCmdLineFlag(argc, (const char **)argv, "noprompt"))
        {
            g_bQAReadback = true;
            fpsLimit = frameCheckNumber;
        }
        if (cutCheckCmdLineFlag(argc, (const char **)argv, "glverify"))
		{
            g_bOpenGLQA = true;
            fpsLimit = frameCheckNumber;
        }
        if (cutCheckCmdLineFlag(argc, (const char **)argv, "fbo")) {
            g_bFBODisplay = true;
            fpsLimit = frameCheckNumber;
        }
    }
	

    if (g_bQAReadback) 
    {
        runAutoTest(argc, argv);
    } 
    else 
    {
        if ( cutCheckCmdLineFlag(argc, (const char **)argv, "device")) {
             printf("   This SDK does not explicitly support -device=n when running with OpenGL.\n");
             printf("   When specifying -device=n (n=0,1,2,....) the sample must not use OpenGL.\n");
             printf("   See details below to run without OpenGL:\n\n");
             printf(" > %s -device=n -qatest\n\n", argv[0]);
             printf("exiting...\n");
             shrQAFinishExit(argc, (const char **)argv, QA_PASSED);
        }

        // First initialize OpenGL context, so we can properly set the GL for CUDA.
        // This is necessary in order to achieve optimal performance with OpenGL/CUDA interop.
        initGL( &argc, argv );

        //cudaGLSetGLDevice (cutGetMaxGflopsDeviceId() );
        int dev = findCapableDevice(argc, argv);
        if( dev != -1 ) {
            cudaGLSetGLDevice( dev );
        } else {
            shrQAFinishExit2(g_bQAReadback, *pArgc, (const char **)pArgv, QA_PASSED);
        }

        cutilCheckError(cutCreateTimer(&timer));
        cutilCheckError(cutResetTimer(timer));  
     
        glutDisplayFunc(display);
        glutKeyboardFunc(keyboard);
        glutReshapeFunc(reshape);

        if (g_bOpenGLQA) {
            loadDefaultImage( argc, argv );
        }

        if (argc > 1) {
            char *filename;
            if (cutGetCmdLineArgumentstr(argc, (const char **)argv, "file", &filename)) {
                initializeData(filename, argc, argv);
            }
        } else {
            loadDefaultImage( argc, argv );
        }


        // If code is not printing the USage, then we execute this path.
        if (!bQuit) {
            if (g_bOpenGLQA) {
                g_CheckRender = new CheckBackBuffer(wWidth, wHeight, 4);
                g_CheckRender->setPixelFormat(GL_BGRA);
                g_CheckRender->setExecPath(argv[0]);
                g_CheckRender->EnableQAReadback(true);
            }

            printf("I: display Image (no filtering)\n");
            printf("T: display Sobel Edge Detection (Using Texture)\n");
            printf("S: display Sobel Edge Detection (Using SMEM+Texture)\n");
            printf("Use the '-' and '=' keys to change the brightness.\n");
			printf("b: switch block filter operation (mean/Sobel)\n");
			printf("p: switch point filter operation (threshold on/off)\n");
            fflush(stdout);
            atexit(cleanup); 
            glutTimerFunc(REFRESH_DELAY, timerEvent,0);
            glutMainLoop();
        }
    }

    cutilDeviceReset();
    shrQAFinishExit(argc, (const char **)argv, QA_PASSED);
}
int main(int argc, char** argv) 
{
    printf("[%s]\n", sSDKsample);
    if (argc > 1) {
        if (cutCheckCmdLineFlag(argc, (const char **)argv, "help")) {
            printHelp();
        }
		if (cutCheckCmdLineFlag(argc, (const char **)argv, "qatest") ||
		    cutCheckCmdLineFlag(argc, (const char **)argv, "noprompt"))
		{
            g_bQAReadback = true;
            fpsLimit = frameCheckNumber;
        }
        if (cutCheckCmdLineFlag(argc, (const char **)argv, "glverify"))
		{
            g_bOpenGLQA = true;
            fpsLimit = frameCheckNumber;
        }
        if (cutCheckCmdLineFlag(argc, (const char **)argv, "fbo")) {
            g_bFBODisplay = true;
            fpsLimit = frameCheckNumber;
        }
    }
	

    if (g_bQAReadback) 
    {
        runAutoTest(argc, argv);
    } 
    else 
    {
        // First initialize OpenGL context, so we can properly set the GL for CUDA.
        // This is necessary in order to achieve optimal performance with OpenGL/CUDA interop.
        initGL( &argc, argv );

        // use command-line specified CUDA device if possible, otherwise search for capable device
        if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") ) {
            cutilGLDeviceInit(argc, argv);
			int device;
			cudaGetDevice( &device );
			if( checkCUDAProfile( device ) == false ) {
				cudaThreadExit();
				cutilExit(argc, argv);
			}
        } else {
            //cudaGLSetGLDevice (cutGetMaxGflopsDeviceId() );
			int dev = findCapableDevice(argc, argv);
			if( dev != -1 ) 
				cudaGLSetGLDevice( dev );
			else {
				cudaThreadExit();
				cutilExit(argc, argv);
			}
        }

        cutilCheckError(cutCreateTimer(&timer));
        cutilCheckError(cutResetTimer(timer));  
     
        glutDisplayFunc(display);
        glutKeyboardFunc(keyboard);
        glutReshapeFunc(reshape);
        glutIdleFunc(idle);

        if (g_bOpenGLQA) {
            loadDefaultImage( argc, argv );
        }

        if (argc > 1) {
            char *filename;
            if (cutGetCmdLineArgumentstr(argc, (const char **)argv, "file", &filename)) {
                initializeData(filename, argc, argv);
            }
        } else {
            loadDefaultImage( argc, argv );
        }


        // If code is not printing the USage, then we execute this path.
        if (!bQuit) {
            if (g_bOpenGLQA) {
                g_CheckRender = new CheckBackBuffer(wWidth, wHeight, 4);
                g_CheckRender->setPixelFormat(GL_BGRA);
                g_CheckRender->setExecPath(argv[0]);
                g_CheckRender->EnableQAReadback(true);
            }

            printf("I: display image\n");
            printf("T: display Sobel edge detection (computed with tex)\n");
            printf("S: display Sobel edge detection (computed with tex+shared memory)\n");
            printf("Use the '-' and '=' keys to change the brightness.\n");
			printf("b: switch block filter operation (mean/Sobel)\n");
			printf("p: swtich point filter operation (threshold on/off)\n");
            fflush(stdout);
            atexit(cleanup); 
            glutMainLoop();
        }
    }

    cudaThreadExit();
    cutilExit(argc, argv);
}
示例#30
0
int readFile( FILE *in ) {

      char temp[DATATEMP1];
      char temp2[DATATEMP2];
      char label[DATATEMP1];
      int numFeature;
      int i,j;
      int lineCount;
      int idValue;
      double featureValue;
      char c;
      extern int maxFeature;
      extern int numExample;

      lineCount = 0;
      dataSetSize = 0;

  /* Estimate number of examples */

      while (fgets(temp, MAXLINE, in ) != NULL )
        dataSetSize++;

      dataSetSize++;
      rewind ( in );

     if( !initializeData( dataSetSize ) )  {
          fprintf( stderr, "Error in initializing data\n" );
          return 0;
    }

     numExample = 0;
     exampleIndex = 0;
     maxFeature = 0;
     printf("Reading training file . . .\n");

    /* Ignore comment and blank lines */
     while( ( c = getc(in) ) != EOF ) {
            while( c == '#' || c == '\n' ) {
                if( c == '#' ) {
                   while( ( c = getc(in) ) != '\n' ) ;
                }
                if( c == '\n' )
                   c = getc( in );
            }

             if( c == EOF )
                    break;

             /* Read one line of description */
           else {
              //exampleIndex++;
              i = 0; numFeature = 0;
              temp[i] = c; i++;
              while( ( c = getc(in) ) != '\n' ) {
                  temp[i] = c; i++;
                  if( c == ':' )
                    numFeature++;
              }
              temp[i] = '\0';
              lineCount++;

              /* each line should start with a class label */
              j = 0;
             while ( temp[j] != ' ' ) {
                label[j] = temp[j];
                j++;
             }
             label[j] = '\0';
              if( atoi(label) != 1 && atoi(label) != -1 ) {
                   fprintf( stderr, "Expect a class label in line %d\n",  lineCount);
                   return 0;
              }

             numExample++;
             nonZeroFeature[exampleIndex] = numFeature;

             if( numFeature != 0 ) {
                 example[exampleIndex] = (FeaturePtr *)malloc( numFeature*sizeof( FeaturePtr ) );
                 if ( example[exampleIndex] == NULL ) {
                   fprintf( stderr, "Memory allocation failed\n");
                   return 0;
                 }

           for (j = 0; j < numFeature; j++) {
               example[exampleIndex][j] = (FeaturePtr) malloc (sizeof(struct feature));
               if ( example[exampleIndex][j] == NULL ) {
                 fprintf( stderr, "Memory allocation failed\n");
                 return 0;
               }
           }
       } else {
           /* We have examples with all features zero. We set the number of nonZerFeatures to zero */
           example[exampleIndex] = (FeaturePtr*)malloc( sizeof( FeaturePtr ) );
           if ( example[exampleIndex] == NULL ){
             fprintf( stderr, "Memory allocation failed\n");
             return 0;
           }
           example[exampleIndex][0] = (FeaturePtr)malloc( sizeof(struct feature) );
           if ( example[exampleIndex][0] == NULL ) {
              fprintf( stderr, "Memory allocation failed\n");
              printf( "Memory allocation failed for example[exampleIndex][0]\n");
              return 0;
           }
             nonZeroFeature[exampleIndex] = 0;
       }
        /* Extract the class label of the example */
        i = 0;
        while( temp[i] != ' ') {
            temp2[i] = temp[i];
            i++;
        }
        temp2[i] = '\0';
        target[exampleIndex] = atoi( temp2 );
        error[exampleIndex] = 0 - target[exampleIndex];
        i++;

       if( numFeature != 0 )  {
          /* Extract and store feature id-value pairs */
          featureIndex = 0;
          while( temp[i] != '\0' ) {
             j = 0;
             while( temp[i] != ':' ) {
                 temp2[j] = temp[i];
                 i++;
                 j++;
             }

             temp2[j] = '\0';
             if( sscanf( temp2, "%d",  &idValue) == 0 ) {
                 fprintf( stderr, "Expect an integer for id in line %d\n",  lineCount);
                 return 0;
             }
             printf("idValue %s\n", temp2);
             printf("EXAMPLEINDEX %d, FEATUREINDEX %d\n", exampleIndex, featureIndex);
             example[exampleIndex][featureIndex]->id = atoi( temp2 );
             j = 0;
             i++;
             while( temp[i] != ' ' && temp[i] != '\0' ) {
                temp2[j] = temp[i];
                i++;
                j++;
             }

              temp2[j] = '\0';
              if( sscanf( temp2, "%f",  &featureValue) == 0 ) {
                  fprintf( stderr, "Expect a real number for feature value in line %d\n",  lineCount );
                  return 0;
              }
              if( fabs(atof( temp2 )) > EPS ) {
                  printf("TEMP2 %s\n", temp2);
                  example[exampleIndex][featureIndex]->value = atof( temp2 );
                  featureIndex++;
              }

          } // end while not end of line

             /* Update the number of nonzero features of the example and the largest feature id found so far for all the examples read */               nonZeroFeature[exampleIndex] = featureIndex;
               if( example[exampleIndex][featureIndex-1]->id > maxFeature )
                    maxFeature = example[exampleIndex][featureIndex-1]->id;
                }
                exampleIndex++;
           } // end else
     }  // end while not EOF

       printf("Finish reading training file.\n");
       return 1;
}