Пример #1
0
int test_reg5(void *state) {
	errr r = parser_reg(state, "abc str foo int bar", ignored);
	eq(r, -EINVAL);
	ok;
}
Пример #2
0
bool operator==(const image_transform& lhs, const image_transform& rhs)
{
    return eq(lhs.opacity, rhs.opacity) && eq(lhs.contrast, rhs.contrast) && eq(lhs.brightness, rhs.brightness) &&
           eq(lhs.saturation, rhs.saturation) && boost::range::equal(lhs.anchor, rhs.anchor, eq) &&
           boost::range::equal(lhs.fill_translation, rhs.fill_translation, eq) &&
           boost::range::equal(lhs.fill_scale, rhs.fill_scale, eq) &&
           boost::range::equal(lhs.clip_translation, rhs.clip_translation, eq) &&
           boost::range::equal(lhs.clip_scale, rhs.clip_scale, eq) && eq(lhs.angle, rhs.angle) &&
           lhs.is_key == rhs.is_key && lhs.invert == rhs.invert && lhs.is_mix == rhs.is_mix &&
           lhs.blend_mode == rhs.blend_mode && lhs.layer_depth == rhs.layer_depth &&
           lhs.chroma.enable == rhs.chroma.enable && lhs.chroma.show_mask == rhs.chroma.show_mask &&
           eq(lhs.chroma.target_hue, rhs.chroma.target_hue) && eq(lhs.chroma.hue_width, rhs.chroma.hue_width) &&
           eq(lhs.chroma.min_saturation, rhs.chroma.min_saturation) &&
           eq(lhs.chroma.min_brightness, rhs.chroma.min_brightness) && eq(lhs.chroma.softness, rhs.chroma.softness) &&
           eq(lhs.chroma.spill_suppress, rhs.chroma.spill_suppress) &&
           eq(lhs.chroma.spill_suppress_saturation, rhs.chroma.spill_suppress_saturation) && lhs.crop == rhs.crop &&
           lhs.perspective == rhs.perspective;
}
Пример #3
0
//--------------------------------------------------------------------------
// test EKKsolution methods.
void
CglProbingUnitTest(
  const OsiSolverInterface * baseSiP,
  const std::string mpsDir )
{
# ifdef CGL_DEBUG
  int i ;	// define just once
# endif
  CoinRelFltEq eq(0.000001);

  // Test default constructor
  {
    CglProbing aGenerator;
  }
  
  // Test copy & assignment
  {
    CglProbing rhs;
    {
      CglProbing bGenerator;
      CglProbing cGenerator(bGenerator);
      rhs=bGenerator;
    }
  }

  {
    OsiCuts osicuts;
    CglProbing test1;
    OsiSolverInterface  * siP = baseSiP->clone();
    int nColCuts;
    int nRowCuts;
    
    std::string fn = mpsDir+"p0033";
    siP->readMps(fn.c_str(),"mps");
    siP->initialSolve();
    // just unsatisfied variables
    test1.generateCuts(*siP,osicuts);
    nColCuts = osicuts.sizeColCuts();
    nRowCuts = osicuts.sizeRowCuts();
    std::cout<<"There are "<<nRowCuts<<" probing cuts"<<std::endl;
    {
      std::cout<<"there are "<<nColCuts<<" probing column cuts"<<std::endl;

#ifdef CGL_DEBUG
      const double * lo = siP->getColLower();
      const double * up = siP->getColUpper();
      for (i=0; i<nColCuts; i++){
	OsiColCut ccut;
	CoinPackedVector cpv;
	ccut = osicuts.colCut(i);
	cpv = ccut.lbs();
	int n = cpv.getNumElements();
        int j;
	const int * indices = cpv.getIndices();
	double* elements = cpv.getElements();
	for (j=0;j<n;j++) {
	  int icol=indices[j];
	  if (elements[j]>lo[icol])
	    std::cout<<"Can increase lb on "<<icol<<" from "<<lo[icol]<<
	      " to "<<elements[j]<<std::endl;
	}
	cpv = ccut.ubs();
	n = cpv.getNumElements();
	indices = cpv.getIndices();
	elements = cpv.getElements();

	for (j=0;j<n;j++) {
	  int icol=indices[j];
	  if (elements[j]<up[icol])
	    std::cout<<"Can decrease ub on "<<icol<<" from "<<up[icol]<<
	      " to "<<elements[j]<<std::endl;
	}
      }

#endif

    }

#ifdef CGL_DEBUG
    for (i=0; i<nRowCuts; i++){
      OsiRowCut rcut;
      CoinPackedVector rpv;
      const double * colsol = siP->getColSolution();
      rcut = osicuts.rowCut(i);
      rpv = rcut.row();
      const int n = rpv.getNumElements();
      const int * indices = rpv.getIndices();
      double* elements = rpv.getElements();
      double sum2=0.0;
      int k=0;
      double lb=rcut.lb();
      double ub=rcut.ub();
      for (k=0; k<n; k++){
	int column=indices[k];
	sum2 += colsol[column]*elements[k];
      }
      if (sum2 >ub + 1.0e-7 ||sum2 < lb - 1.0e-7) {
	std::cout<<"Cut "<<i<<" lb "<<lb<<" solution "<<sum2<<" ub "<<ub<<std::endl;
	for (k=0; k<n; k++){
	  int column=indices[k];
	  std::cout<<"(col="<<column<<",el="<<elements[k]<<",sol="<<
	    colsol[column]<<") ";
	}
	std::cout <<std::endl;
      }
    }
#endif

    if (nRowCuts==1) {
      CoinPackedVector check;
      int index[] = {6,32};
      double el[] = {1,1};
      check.setVector(2,index,el);
      // sort Elements in increasing order
      CoinPackedVector rpv=osicuts.rowCut(0).row();
      assert (rpv.getNumElements()==2);
      rpv.sortIncrIndex();
      assert (check==rpv);
      assert (osicuts.rowCut(0).lb()==1.0);
    }
    // now all variables
    osicuts=OsiCuts();
    test1.setMode(2);
    test1.setRowCuts(3);
    test1.generateCuts(*siP,osicuts);
    nColCuts = osicuts.sizeColCuts();
    nRowCuts = osicuts.sizeRowCuts();
    std::cout<<"There are "<<nRowCuts<<" probing cuts"<<std::endl;
    {
      std::cout<<"there are "<<nColCuts<<" probing column cuts"<<std::endl;

#ifdef CGL_DEBUG
      const double * lo = siP->getColLower();
      const double * up = siP->getColUpper();
      for (i=0; i<nColCuts; i++){
	OsiColCut ccut;
	CoinPackedVector cpv;
	ccut = osicuts.colCut(i);
	cpv = ccut.lbs();
	int n = cpv.getNumElements();
        int j;
	const int * indices = cpv.getIndices();
	double* elements = cpv.getElements();
	for (j=0;j<n;j++) {
	  int icol=indices[j];
	  if (elements[j]>lo[icol])
	    std::cout<<"Can increase lb on "<<icol<<" from "<<lo[icol]<<
	      " to "<<elements[j]<<std::endl;
	}
	cpv = ccut.ubs();
	n = cpv.getNumElements();
	indices = cpv.getIndices();
	elements = cpv.getElements();
	for (j=0;j<n;j++) {
	  int icol=indices[j];
	  if (elements[j]<up[icol])
	    std::cout<<"Can decrease ub on "<<icol<<" from "<<up[icol]<<
	      " to "<<elements[j]<<std::endl;
	}
      }
#endif

    }

#ifdef CGL_DEBUG
    for (i=0; i<nRowCuts; i++){
      OsiRowCut rcut;
      CoinPackedVector rpv;
      const double * colsol = siP->getColSolution();
      rcut = osicuts.rowCut(i);
      rpv = rcut.row();
      const int n = rpv.getNumElements();
      const int * indices = rpv.getIndices();
      double* elements = rpv.getElements();
      double sum2=0.0;
      int k=0;
      double lb=rcut.lb();
      double ub=rcut.ub();
      for (k=0; k<n; k++){
	int column=indices[k];
	sum2 += colsol[column]*elements[k];
      }
      if (sum2 >ub + 1.0e-7 ||sum2 < lb - 1.0e-7) {
	std::cout<<"Cut "<<i<<" lb "<<lb<<" solution "<<sum2<<" ub "<<ub<<std::endl;
	for (k=0; k<n; k++){
	  int column=indices[k];
	  std::cout<<"(col="<<column<<",el="<<elements[k]<<",sol="<<
	    colsol[column]<<") ";
	}
	std::cout <<std::endl;
      }
    }
#endif

    assert (osicuts.sizeRowCuts()>=4);
    delete siP;
  }

}
Пример #4
0
static int test_negative(void *state) {
	errr r = parser_parse(state, "M:F:-1");
	eq(r, PARSE_ERROR_INVALID_VALUE);
	ok;
}
Пример #5
0
cue_t *cue_new(const char *file)
{
  cue_t *r = (cue_t *) mc_malloc(sizeof(cue_t));

  r->audio_file = NULL;
  r->album_title = NULL;
  r->album_performer = NULL;
  r->album_composer = NULL;
  r->genre = NULL;
  r->cuefile = mystrdup(file);
  r->count = 0;
  r->entries = NULL;
  r->_errno = 0;

  FILE *f = fopen(file, "rt");
  time_t _audio_mtime=0;

  if (f == NULL) {
    r->_errno = ENOFILECUE;
  } else {
    char *line;
    char *image = NULL;
    char *year = NULL;
    cue_entry_t *entry = NULL;
    int in_tracks = 0;
    while ((line = readline(f)) != NULL) {
      trim_replace(&line);
      if (strcmp(line, "") != 0) {
        if (!in_tracks) {
          if (eq(line, "performer")) {
            mc_free(r->album_performer);
            r->album_performer = unquote(line, "performer");
          } else if (eq(line, "title")) {
            mc_free(r->album_title);
            r->album_title = unquote(line, "title");
          } else if (eq(line, "file")) {
            mc_free(r->audio_file);
            char *fl = getFilePart(line);
            char *af = unquote(fl, "");
            if (strlen(af) > 0) {
              if (af[0] == '/') {
                r->audio_file = af;
              } else {
                char *cf = mc_strdup(r->cuefile);
                int ii;
                for (ii = strlen(cf) - 1; ii >= 0 && cf[ii] != '/'; ii--) ;
                if (ii >= 0) {
                  cf[ii] = '\0';
                  char *aaf = (char *)mc_malloc(strlen(cf) + strlen(af) + strlen("/") + 1);
                  sprintf(aaf, "%s/%s", cf, af);
                  r->audio_file = aaf;
                  mc_free(cf);
                  mc_free(af);
                } else {
                  r->audio_file = af;
                }
              }
            } else {
              r->audio_file = af;
            }
            // We have a full path audio file now.
            // get the mtime.
            {
              struct stat st;
              stat(r->audio_file,&st);
              _audio_mtime=st.st_mtime;
            }

            mc_free(fl);
          } else if (eq(line, "rem")) {
            if (eq(&line[3], "date")) {
              mc_free(year);
              year = unquote(&line[3], "date");
            } else if (eq(&line[3], "image")) {
              mc_free(image);
              image = unquote(&line[3], "image");
            } else if (eq(&line[3], "composer")) {
              mc_free(r->album_composer);
              r->album_performer = unquote(&line[3], "composer");
            } else if (eq(&line[3], "genre")) {
              mc_free(r->genre);
              r->genre = unquote(&line[3], "genre");
            }
          } else if (eq(line, "track")) {
            in_tracks = 1;
          }
        }

        if (in_tracks) {
          if (eq(line, "track")) {
            log_debug2("track: entry=%p", entry);
            if (entry != NULL) {
              addEntry(r, entry);
            }
            entry = cue_entry_new(r);
            entry->audio_mtime=_audio_mtime;
            entry->year = mystrdup(year);
            entry->performer = mystrdup(r->album_performer);
            entry->composer = mystrdup(r->album_composer);
            entry->piece = NULL;
            log_debug2("track: created new entry %p", entry);
          } else if (eq(line, "title")) {
            mc_free(entry->title);
            entry->title = unquote(line, "title");
          } else if (eq(line, "performer")) {
            mc_free(entry->performer);
            entry->performer = unquote(line, "performer");
          } else if (eq(line, "index")) {
            char *index = unquote(line, "index");
            entry->begin_offset_in_ms = calculateOffset(index);
            mc_free(index);
          } else if (eq(line, "rem")) {
            if (eq(&line[3], "composer")) {
              mc_free(entry->composer);
              entry->composer = unquote(&line[3], "composer");
            } else if (eq(&line[3], "piece")) {
              mc_free(entry->piece);
              entry->piece = unquote(&line[3], "piece");
            } else if (eq(&line[3], "year")) {
              mc_free(year);
              year = unquote(&line[3], "year");
              mc_free(entry->year);
              entry->year = mystrdup(year);
            }
          }
        }
      }
      mc_free(line);
    }
    if (entry != NULL) {
      addEntry(r, entry);
    }
    mc_free(year);
    mc_free(image);


    {
      int i, N;
      for (i = 0, N = r->count; i < N - 1; i++) {
        r->entries[i]->end_offset_in_ms = r->entries[i + 1]->begin_offset_in_ms;
        r->entries[i]->tracknr = i + 1;
      }
      r->entries[i]->tracknr = i + 1;
    }

    fclose(f);
  }

  return r;
}
Пример #6
0
//--------------------------------------------------------------------------
void
CglKnapsackCoverUnitTest(
  const OsiSolverInterface * baseSiP,
  const std::string mpsDir )
{
  int i;
  CoinRelFltEq eq(0.000001);

  // Test default constructor
  {
    CglKnapsackCover kccGenerator;
  }
  
  // Test copy & assignment
  {
    CglKnapsackCover rhs;
    {
      CglKnapsackCover kccGenerator;
      CglKnapsackCover cgC(kccGenerator);
      rhs=kccGenerator;
    }
  }


  // test exactSolveKnapsack
  {  
    CglKnapsackCover kccg;
    const int n=7;
    double c=50;
    double p[n] = {70,20,39,37,7,5,10};
    double w[n] = {31, 10, 20, 19, 4, 3, 6};
    double z;
    int x[n];
    int exactsol = kccg.exactSolveKnapsack(n, c, p, w, z, x);
    assert(exactsol==1);
    assert (z == 107);
    assert (x[0]==1);
    assert (x[1]==0);
    assert (x[2]==0);
    assert (x[3]==1);
    assert (x[4]==0);
    assert (x[5]==0);
    assert (x[6]==0);
  }

  /*
  // Testcase /u/rlh/osl2/mps/scOneInt.mps
  // Model has 3 continous, 2 binary, and 1 general
  // integer variable.
  {
    OsiSolverInterface  * siP = baseSiP->clone();
    int * complement=NULL;
    double * xstar=NULL;

    siP->readMps("../Mps/scOneInt","mps");
    CglKnapsackCover kccg;
    int nCols=siP->getNumCols();
    
    // Test the siP methods for detecting
    // variable type
    int numCont=0, numBinary=0, numIntNonBinary=0, numInt=0;
    for (int thisCol=0; thisCol<nCols; thisCol++) {
      if ( siP->isContinuous(thisCol) ) numCont++;
      if ( siP->isBinary(thisCol) ) numBinary++;
      if ( siP->isIntegerNonBinary(thisCol) ) numIntNonBinary++;
      if ( siP->isInteger(thisCol) ) numInt++;
    }
    assert(numCont==3);
    assert(numBinary==2);
    assert(numIntNonBinary==1);
    assert(numInt==3);
    
    
    // Test initializeCutGenerator
    siP->initialSolve();
    assert(xstar !=NULL);
    for (i=0; i<nCols; i++){
      assert(complement[i]==0);
    }
    int nRows=siP->getNumRows();
    for (i=0; i<nRows; i++){
    int vectorsize = siP->getMatrixByRow()->vectorSize(i);
    assert(vectorsize==2);
    }
    
    kccg.cleanUpCutGenerator(complement,xstar);
    delete siP;
  }
  */  
  
  // Testcase /u/rlh/osl2/mps/tp3.mps
  // Models has 3 cols, 3 rows
  // Row 0 yields a knapsack, others do not.
  {
    // setup
    OsiSolverInterface  * siP = baseSiP->clone();
    std::string fn(mpsDir+"tp3");
    siP->readMps(fn.c_str(),"mps");     
    // All integer variables should be binary.
    // Assert that this is true.
    for ( i = 0;  i < siP->getNumCols();  i++ )
      if ( siP->isInteger(i) ) 
        assert(siP->getColUpper()[i]==1.0 && siP->isBinary(i));  
    OsiCuts cs;
    CoinPackedVector krow;
    double b=0;
    int nCols=siP->getNumCols();
    int * complement=new int [nCols];
    double * xstar=new double [nCols];

    CglKnapsackCover kccg;

    // solve LP relaxation
    // a "must" before calling initialization
    siP->initialSolve();
    double lpRelaxBefore=siP->getObjValue();
    std::cout<<"Initial LP value: "<<lpRelaxBefore<<std::endl;
    assert( eq(siP->getObjValue(), 97.185) );
    double mycs[] = {.627, .667558333333, .038};
    siP->setColSolution(mycs);
    const double *colsol = siP->getColSolution(); 
    int k;
    for (k=0; k<nCols; k++){
      xstar[k]=colsol[k];
      complement[k]=0;
    }
    
    // test deriveAKnapsack
    int rind = ( siP->getRowSense()[0] == 'N' ) ? 1 : 0;
    const CoinShallowPackedVector reqdBySunCC = siP->getMatrixByRow()->getVector(rind) ;
    int deriveaknap = kccg.deriveAKnapsack(*siP, cs, krow,b,complement,xstar,rind,reqdBySunCC);
    assert(deriveaknap ==1);
    assert(complement[0]==0);
    assert(complement[1]==1);
    assert(complement[2]==1);
    int inx[3] = {0,1,2};
    double el[3] = {161, 120, 68};
    CoinPackedVector r;
    r.setVector(3,inx,el);
    assert (krow == r);
    //assert (b == 183.0); ????? but x1 and x2 at 1 is valid 
    
    // test findGreedyCover 
    CoinPackedVector cover,remainder;
#if 0
    int findgreedy =  kccg.findGreedyCover( 0, krow, b, xstar, cover, remainder );
    assert( findgreedy == 1 );
    int coveri = cover.getNumElements();
    assert( cover.getNumElements() == 2);
    coveri = cover.getIndices()[0];
    assert( cover.getIndices()[0] == 0);
    assert( cover.getIndices()[1] == 1);
    assert( cover.getElements()[0] == 161.0);
    assert( cover.getElements()[1] == 120.0);
    assert( remainder.getNumElements() == 1);
    assert( remainder.getIndices()[0] == 2);
    assert( remainder.getElements()[0] == 68.0);

    // test liftCoverCut
    CoinPackedVector cut;
    double * rowupper = ekk_rowupper(model);
    double cutRhs = cover.getNumElements() - 1.0;
    kccg.liftCoverCut(b, krow.getNumElements(),
      cover, remainder,
      cut);
    assert ( cut.getNumElements() == 3 );
    assert ( cut.getIndices()[0] == 0 );
    assert ( cut.getIndices()[1] == 1 );
    assert ( cut.getIndices()[2] == 2 );
    assert( cut.getElements()[0] == 1 );
    assert( cut.getElements()[1] == 1 );
    assert( eq(cut.getElements()[2], 0.087719) );
    
    // test liftAndUncomplementAndAdd
    OsiCuts cuts;    
    kccg.liftAndUncomplementAndAdd(*siP.getRowUpper()[0],krow,b,complement,0,
      cover,remainder,cuts);   
    int sizerowcuts = cuts.sizeRowCuts();
    assert ( sizerowcuts== 1 );
    OsiRowCut testRowCut = cuts.rowCut(0);
    CoinPackedVector testRowPV = testRowCut.row(); 
    OsiRowCut sampleRowCut;
    const int sampleSize = 3;
    int sampleCols[sampleSize]={0,1,2};
    double sampleElems[sampleSize]={1.0,-1.0,-0.087719};
    sampleRowCut.setRow(sampleSize,sampleCols,sampleElems);
    sampleRowCut.setLb(-DBL_MAX);
    sampleRowCut.setUb(-0.087719);
    bool equiv =  testRowPV.equivalent(sampleRowCut.row(),CoinRelFltEq(1.0e-05) );
    assert ( equiv );
#endif
    
    // test find PseudoJohnAndEllisCover
    cover.setVector(0,NULL, NULL);
    remainder.setVector(0,NULL,NULL);

    rind = ( siP->getRowSense()[0] == 'N' ) ? 1 : 0;
    int findPJE =  kccg.findPseudoJohnAndEllisCover( rind, krow, 
						     b, xstar, cover, remainder );
    assert( findPJE == 1 );
    assert ( cover.getIndices()[0] == 0 );
    assert ( cover.getIndices()[1] == 2 );
    assert ( cover.getElements()[0] == 161 );    
    assert ( cover.getElements()[1] == 68 );    
    assert ( remainder.getIndices()[0] == 1 );
    assert ( remainder.getElements()[0] == 120 );    
    OsiCuts cuts;    
    kccg.liftAndUncomplementAndAdd((*siP).getRowUpper()[rind],krow,b, complement, rind,
      cover,remainder,cuts);   
    assert (cuts.sizeRowCuts() == 1 );

    OsiRowCut testRowCut = cuts.rowCut(0);
    CoinPackedVector testRowPV = testRowCut.row();


    const int sampleSize = 3;
    int sampleCols[sampleSize]={0,1,2};
    double sampleElems[sampleSize]={1.0, -1.0, -1.0};
    OsiRowCut sampleRowCut;
    sampleRowCut.setRow(sampleSize,sampleCols,sampleElems);
    sampleRowCut.setLb(-COIN_DBL_MAX);
    sampleRowCut.setUb(-1.0);
    
    // test for 'close enough'
    assert( testRowPV.isEquivalent(sampleRowCut.row(),CoinRelFltEq(1.0e-05) ) );
    // Reset complement & test next row
    for (i=0; i<nCols; i++){
      complement[i]=0;
    }

    rind++;
    const CoinShallowPackedVector reqdBySunCC2 = siP->getMatrixByRow()->getVector(rind) ;
    deriveaknap = kccg.deriveAKnapsack(*siP,cuts,krow,b,complement,xstar,rind,reqdBySunCC2);
    assert(deriveaknap==0);
    
    // Reset complement & test next row
    for (i=0; i<nCols; i++){
      complement[i]=0;
    }
    const CoinShallowPackedVector reqdBySunCC3 = siP->getMatrixByRow()->getVector(2) ;
    deriveaknap = kccg.deriveAKnapsack(*siP,cuts,krow,b,complement,xstar,2,
				       reqdBySunCC3);
    assert(deriveaknap == 0);
    
    // Clean up
    delete [] complement;
    delete [] xstar;
    
    delete siP;
  }

#if 0
  // Testcase /u/rlh/osl2/mps/tp4.mps
  // Models has 6 cols, 1 knapsack row and 
  // 3 rows explicily bounding variables
  // Row 0 yields a knapsack cover cut 
  // using findGreedyCover which moves the 
  // LP objective function value.
  {
    // Setup
    EKKContext * env=ekk_initializeContext();
    EKKModel * model = ekk_newModel(env,"");
    OsiSolverInterface si(model);
    ekk_importModel(model, "tp4.mps");
    CglKnapsackCover kccg;
    kccg.ekk_validateIntType(si);     
    
    // Solve the LP relaxation of the model and
    // print out ofv for sake of comparison 
    ekk_allSlackBasis(model);
    ekk_crash(model,1); 
    ekk_primalSimplex(model,1);
    double lpRelaxBefore=ekk_getRobjvalue(model);
#ifdef CGL_DEBUG
    printf("\n\nOrig LP min=%f\n",lpRelaxBefore);
#endif
    
    // Determine if lp sol is ip optimal
    // Note: no ekk_function to do this
    int nCols=ekk_getInumcols(model);
    double * optLpSol = ekk_colsol(model);
    int ipOpt = 1;
    i=0;
    while (i++<nCols && ipOpt){
      if(optLpSol[i] < 1.0-1.0e-08 && optLpSol[i]> 1.0e-08) ipOpt = 0;
    }
    
    if (ipOpt){
#ifdef CGL_DEBUG
      printf("Lp solution is within ip optimality tolerance\n");
#endif
    }    
    else {
      OsiSolverInterface iModel(model);
      OsiCuts cuts;    
      
      // Test generateCuts method
      kccg.generateCuts(iModel,cuts);
      OsiSolverInterface::ApplyCutsReturnCode rc = iModel.applyCuts(cuts);
      
      ekk_mergeBlocks(model,1);         
      ekk_dualSimplex(model);
      double lpRelaxAfter=ekk_getRobjvalue(model); 
#ifdef CGL_DEBUG
      printf("\n\nFinal LP min=%f\n",lpRelaxAfter);
#endif
      assert( lpRelaxBefore < lpRelaxAfter );
      
      // This may need to be updated as other 
      // minimal cover finders are added
      assert( cuts.sizeRowCuts() == 1 );
      OsiRowCut testRowCut = cuts.rowCut(0);
      CoinPackedVector testRowPV = testRowCut.row();
      
      OsiRowCut sampleRowCut;
      const int sampleSize = 6;
      int sampleCols[sampleSize]={0,1,2,3,4,5};
      double sampleElems[sampleSize]={1.0,1.0,1.0,1.0,0.5, 2.0};
      sampleRowCut.setRow(sampleSize,sampleCols,sampleElems);
      sampleRowCut.setLb(-DBL_MAX);
      sampleRowCut.setUb(3.0);
      bool equiv = testRowPV.equivalent(sampleRowCut.row(),CoinRelFltEq(1.0e-05) );
      assert( testRowPV.equivalent(sampleRowCut.row(),CoinRelFltEq(1.0e-05) ) );
    }
    
    // Exit out of OSL
    ekk_deleteModel(model);
    ekk_endContext(env);
    
  }
#endif


  // Testcase /u/rlh/osl2/mps/tp5.mps
  // Models has 6 cols, 1 knapsack row and 
  // 3 rows explicily bounding variables
  // Row 0 yields a knapsack cover cut 
  // using findGreedyCover which moves the 
  // LP objective function value.
  {
    // Setup
    OsiSolverInterface  * siP = baseSiP->clone();
    std::string fn(mpsDir+"tp5");
    siP->readMps(fn.c_str(),"mps");
    // All integer variables should be binary.
    // Assert that this is true.
    for ( i = 0;  i < siP->getNumCols();  i++ )
      if ( siP->isInteger(i) ) 
        assert(siP->getColUpper()[i]==1.0 && siP->isBinary(i));  
    CglKnapsackCover kccg;
    
    // Solve the LP relaxation of the model and
    // print out ofv for sake of comparison 
    siP->initialSolve();
    double lpRelaxBefore=siP->getObjValue();
    assert( eq(lpRelaxBefore, -51.66666666667) );
    double mycs[] = {.8999999999, .899999999999, .89999999999, 1.110223e-16, .5166666666667, 0};
    siP->setColSolution(mycs);
#ifdef CGL_DEBUG
    printf("\n\nOrig LP min=%f\n",lpRelaxBefore);
#endif
    
    // Determine if lp sol is 0/1 optimal
    int nCols=siP->getNumCols();
    const double * optLpSol = siP->getColSolution();
    bool ipOpt = true;
    i=0;
    while (i++<nCols && ipOpt){
      if(optLpSol[i] > kccg.epsilon_ && optLpSol[i] < kccg.onetol_) ipOpt = false;
    }
    
    if (ipOpt){
#ifdef CGL_DEBUG
      printf("Lp solution is within ip optimality tolerance\n");
#endif
    }    
    else {
      // set up
      OsiCuts cuts;    
      CoinPackedVector krow;
      double b=0.0;
      int * complement=new int[nCols];
      double * xstar=new double[nCols];
      // initialize cut generator
      const double *colsol = siP->getColSolution(); 
      for (i=0; i<nCols; i++){
	xstar[i]=colsol[i];
	complement[i]=0;
      }
      int row = ( siP->getRowSense()[0] == 'N' ) ? 1 : 0;
      // transform row into canonical knapsack form
      const CoinShallowPackedVector reqdBySunCC = siP->getMatrixByRow()->getVector(row) ;
      if (kccg.deriveAKnapsack(*siP, cuts, krow, b, complement, xstar, row,reqdBySunCC)){
        CoinPackedVector cover, remainder;  
        // apply greedy logic to detect violated minimal cover inequalities
        if (kccg.findGreedyCover(row, krow, b, xstar, cover, remainder) == 1){
          // lift, uncomplements, and add cut to cut set
          kccg.liftAndUncomplementAndAdd((*siP).getRowUpper()[row],krow, b, complement, row, cover, remainder, cuts);   
        }  
        // reset optimal column solution (xstar) information in OSL     
        const double * rowupper = siP->getRowUpper();
	int k;
        if (fabs(b-rowupper[row]) > 1.0e-05) {
          for(k=0; k<krow.getNumElements(); k++) {
            if (complement[krow.getIndices()[k]]){
              xstar[krow.getIndices()[k]]= 1.0-xstar[krow.getIndices()[k]];
              complement[krow.getIndices()[k]]=0;
            }
          }
        }  
        // clean up
        delete [] complement;
	delete [] xstar;
      }
      // apply the cuts
      OsiSolverInterface::ApplyCutsReturnCode rc = siP->applyCuts(cuts);
      
      siP->resolve();
      double lpRelaxAfter=siP->getObjValue();
      assert( eq(lpRelaxAfter, -30.0) );
#ifdef CGL_DEBUG
      printf("\n\nFinal LP min=%f\n",lpRelaxAfter);
#endif
      // test that expected cut was detected
      assert( lpRelaxBefore < lpRelaxAfter );
      assert( cuts.sizeRowCuts() == 1 );
      OsiRowCut testRowCut = cuts.rowCut(0);
      CoinPackedVector testRowPV = testRowCut.row();
      OsiRowCut sampleRowCut;
      const int sampleSize = 6;
      int sampleCols[sampleSize]={0,1,2,3,4,5};
      double sampleElems[sampleSize]={1.0,1.0,1.0,0.25,1.0,2.0};
      sampleRowCut.setRow(sampleSize,sampleCols,sampleElems);
      sampleRowCut.setLb(-COIN_DBL_MAX);
      sampleRowCut.setUb(3.0);
      assert(testRowPV.isEquivalent(sampleRowCut.row(),CoinRelFltEq(1.0e-05)));
    }
    
    delete siP;
  }
 

  // Testcase /u/rlh/osl2/mps/p0033
  // Miplib3 problem p0033
  // Test that no cuts chop off the optimal solution
  {
    // Setup
    OsiSolverInterface  * siP = baseSiP->clone();
    std::string fn(mpsDir+"p0033");
    siP->readMps(fn.c_str(),"mps");
    // All integer variables should be binary.
    // Assert that this is true.
    for ( i = 0;  i < siP->getNumCols();  i++ )
      if ( siP->isInteger(i) ) 
        assert(siP->getColUpper()[i]==1.0 && siP->isBinary(i));  
    int nCols=siP->getNumCols();
    CglKnapsackCover kccg;

    // Solve the LP relaxation of the model and
    // print out ofv for sake of comparison 
    siP->initialSolve();
    double lpRelaxBefore=siP->getObjValue();
    assert( eq(lpRelaxBefore, 2520.5717391304347) );
    double mycs[] = {0, 1, 0, 0, -2.0837010502455788e-19, 1, 0, 0, 1,
		       0.021739130434782594, 0.35652173913043478, 
		       -6.7220534694101275e-18, 5.3125906451789717e-18, 
		       1, 0, 1.9298798670241979e-17, 0, 0, 0,
		       7.8875708048320448e-18, 0.5, 0, 
		       0.85999999999999999, 1, 1, 0.57999999999999996,
		       1, 0, 1, 0, 0.25, 0, 0.67500000000000004};
    siP->setColSolution(mycs);
#ifdef CGL_DEBUG
    printf("\n\nOrig LP min=%f\n",lpRelaxBefore);
#endif
    
    OsiCuts cuts;    
    
    // Test generateCuts method
    kccg.generateCuts(*siP,cuts);
    OsiSolverInterface::ApplyCutsReturnCode rc = siP->applyCuts(cuts);
    
    siP->resolve();
    double lpRelaxAfter=siP->getObjValue(); 
    assert( eq(lpRelaxAfter, 2829.0597826086955) );
#ifdef CGL_DEBUG
    printf("\n\nOrig LP min=%f\n",lpRelaxBefore);
    printf("\n\nFinal LP min=%f\n",lpRelaxAfter);
#endif
    assert( lpRelaxBefore < lpRelaxAfter );
    
    // the CoinPackedVector p0033 is the optimal
    // IP solution to the miplib problem p0033
    int objIndices[14] = { 
       0,  6,  7,  9, 13, 17, 18,
      22, 24, 25, 26, 27, 28, 29 };
    CoinPackedVector p0033(14,objIndices,1.0);

    // Sanity check
    const double *  objective=siP->getObjCoefficients();
    double ofv =0 ;
    int r;
    for (r=0; r<nCols; r++){
      ofv=ofv + p0033[r]*objective[r];
    }
    CoinRelFltEq eq;
    assert( eq(ofv,3089.0) );

    int nRowCuts = cuts.sizeRowCuts();
    OsiRowCut rcut;
    CoinPackedVector rpv;
    for (i=0; i<nRowCuts; i++){
      rcut = cuts.rowCut(i);
      rpv = rcut.row();
      double p0033Sum = (rpv*p0033).sum();
      assert (p0033Sum <= rcut.ub() );
    }
  
    delete siP;
  } 

  // if a debug file is there then look at it
  {
    FILE * fp = fopen("knapsack.debug","r");
    if (fp) {
      int ncol,nel;
      double up;
      int x = fscanf(fp,"%d %d %lg",&ncol,&nel,&up);
      if (x<=0)
	throw("bad fscanf");
      printf("%d columns, %d elements, upper %g\n",ncol,nel,up);
      double * sol1 = new double[nel];
      double * el1 = new double[nel];
      int * col1 = new int[nel];
      CoinBigIndex * start = new CoinBigIndex [ncol+1];
      memset(start,0,ncol*sizeof(CoinBigIndex ));
      int * row = new int[nel];
      int i;
      for (i=0;i<nel;i++) {
	x=fscanf(fp,"%d %lg %lg",col1+i,el1+i,sol1+i);
	if (x<=0)
	  throw("bad fscanf");
	printf("[%d, e=%g, v=%g] ",col1[i],el1[i],sol1[i]);
	start[col1[i]]=1;
	row[i]=0;
      }
      printf("\n");
      // Setup
      OsiSolverInterface  * siP = baseSiP->clone();
      
      double lo=-1.0e30;
      double * upper = new double[ncol];
      start[ncol]=nel;
      int last=0;
      for (i=0;i<ncol;i++) {
	upper[i]=1.0;
	int marked=start[i];
	start[i]=last;
	if (marked)
	  last++;
      }
      siP->loadProblem(ncol,1,start,row,el1,NULL,upper,NULL,&lo,&up);
      // use upper for solution
      memset(upper,0,ncol*sizeof(double));
      for (i=0;i<nel;i++) {
	int icol=col1[i];
	upper[icol]=sol1[i];
	siP->setInteger(icol);
      }
      siP->setColSolution(upper);
      delete [] sol1;
      delete [] el1;
      delete [] col1;
      delete [] start;
      delete [] row;
      delete [] upper;
      CglKnapsackCover kccg;
      
      OsiCuts cuts;    
      
      // Test generateCuts method
      kccg.generateCuts(*siP,cuts);
      // print out and compare to known cuts
      int numberCuts = cuts.sizeRowCuts();
      if (numberCuts) {
	for (i=0;i<numberCuts;i++) {
	  OsiRowCut * thisCut = cuts.rowCutPtr(i);
	  int n=thisCut->row().getNumElements();
	  printf("Cut %d has %d entries, rhs %g %g =>",i,n,thisCut->lb(),
		 thisCut->ub());
	  int j;
	  const int * index = thisCut->row().getIndices();
	  const double * element = thisCut->row().getElements();
	  for (j=0;j<n;j++) {
	    printf(" (%d,%g)",index[j],element[j]);
	  }
	  printf("\n");
	}
      }
      fclose(fp);
    }
  }

  // Testcase /u/rlh/osl2/mps/p0201
  // Miplib3 problem p0282
  // Test that no cuts chop off the optimal ip solution
  {
    // Setup
    OsiSolverInterface  * siP = baseSiP->clone();
    std::string fn(mpsDir+"p0201");
    siP->readMps(fn.c_str(),"mps");
    // All integer variables should be binary.
    // Assert that this is true.
    for ( i = 0;  i < siP->getNumCols();  i++ )
      if ( siP->isInteger(i) ) 
        assert(siP->getColUpper()[i]==1.0 && siP->isBinary(i));    

    const int nCols=siP->getNumCols();
    CglKnapsackCover kccg;
    
    // Solve the LP relaxation of the model and
    // print out ofv for sake of comparisn 
    siP->initialSolve();
    double lpRelaxBefore=siP->getObjValue();
    assert( eq(lpRelaxBefore, 6875.) );
    double mycs[] =
      {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
       0, 0.5, 0, 0, 0, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0.5, 
       0, 0, 0, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0.5, 0, 0, 
       0, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0.5, 0, 0, 0, 0.5, 
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0.5, 0, 0, 0, 0.5, 0, 0, 
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0.5, 0, 0, 0, 0.5, 0, 0, 0, 0, 
       0, 0, 0, 0, 0, 0, 0, 0, 1, 0.5, 0, 0, 0, 0.5, 0, 0, 0, 0, 0, 0, 
       0, 0, 0, 0, 0, 0, 1, 0.5, 0, 0, 0, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 
       0, 0, 0, 0, 1, 0.5, 0, 0, 0, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
       0, 0, 1, 0.5, 0, 0, 0, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
       1};
    siP->setColSolution(mycs);
#ifdef CGL_DEBUG
    printf("\n\nOrig LP min=%f\n",lpRelaxBefore);
#endif
    
    OsiCuts cuts;    
    
    // Test generateCuts method
    kccg.generateCuts(*siP,cuts);
    OsiSolverInterface::ApplyCutsReturnCode rc = siP->applyCuts(cuts);
    
    siP->resolve();
    double lpRelaxAfter=siP->getObjValue(); 
    assert( eq(lpRelaxAfter, 7125) );
#ifdef CGL_DEBUG
    printf("\n\nOrig LP min=%f\n",lpRelaxBefore);
    printf("\n\nFinal LP min=%f\n",lpRelaxAfter);
#endif
    assert( lpRelaxBefore < lpRelaxAfter );
 
    // Optimal IP solution to p0201    
    int objIndices[22] = { 8, 10,  21,  38,  39,  56,
      60,   74, 79,  92, 94, 110, 111, 128, 132, 146, 
      151,164, 166, 182,183, 200 };
    CoinPackedVector p0201(22,objIndices,1.0);
    
    // Sanity check
    const double *  objective=siP->getObjCoefficients();
    double ofv =0 ;
    int r;
    for (r=0; r<nCols; r++){
      ofv=ofv + p0201[r]*objective[r];
    }
    CoinRelFltEq eq;
    assert( eq(ofv,7615.0) );
    //printf("p0201 optimal ofv = %g\n",ofv); 

    int nRowCuts = cuts.sizeRowCuts();
    OsiRowCut rcut;
    CoinPackedVector rpv;
    for (i=0; i<nRowCuts; i++){
      rcut = cuts.rowCut(i);
      rpv = rcut.row();
      double p0201Sum = (rpv*p0201).sum();
      assert (p0201Sum <= rcut.ub() );
    }
  
    delete siP;
  } 

 
  // see if I get the same covers that N&W get
  {
    OsiSolverInterface * siP=baseSiP->clone();
    std::string fn(mpsDir+"nw460");
    siP->readMps(fn.c_str(),"mps");   
    // All integer variables should be binary.
    // Assert that this is true.
    for ( i = 0;  i < siP->getNumCols();  i++ )
      if ( siP->isInteger(i) ) 
        assert(siP->getColUpper()[i]==1.0 && siP->isBinary(i));  
    CglKnapsackCover kccg;
    
    // Solve the LP relaxation of the model and
    // print out ofv for sake of comparison 
    siP->initialSolve();
    double lpRelaxBefore=siP->getObjValue();
    assert( eq(lpRelaxBefore, -225.68951787852194) );
    double mycs[] = {0.7099213482046447, 0, 0.34185802225477174, 1, 1, 0, 1, 1, 0};
    siP->setColSolution(mycs);

    OsiCuts cuts;    
    
    // Test generateCuts method
    kccg.generateCuts(*siP,cuts);
    OsiSolverInterface::ApplyCutsReturnCode rc = siP->applyCuts(cuts);
    
    siP->resolve();
    double lpRelaxAfter=siP->getObjValue(); 
    assert( eq(lpRelaxAfter, -176) );
#ifdef CGL_DEBUG
    printf("\n\nOrig LP min=%f\n",lpRelaxBefore);
    printf("\n\nFinal LP min=%f\n",lpRelaxAfter);
#endif
#ifdef MJS
    assert( lpRelaxBefore < lpRelaxAfter );
#endif    
    
    int nRowCuts = cuts.sizeRowCuts();
    OsiRowCut rcut;
    CoinPackedVector rpv;
    for (i=0; i<nRowCuts; i++){
      rcut = cuts.rowCut(i);
      rpv = rcut.row();
      int j;
      printf("Row cut number %i has rhs = %g\n",i,rcut.ub());
      for (j=0; j<rpv.getNumElements(); j++){
        printf("index %i, element %g\n", rpv.getIndices()[j], rpv.getElements()[j]);
      }
      printf("\n");
    }
    delete siP; 
  }

  // Debugging: try "exmip1.mps"
  {
    // Setup
    OsiSolverInterface  * siP = baseSiP->clone();
    std::string fn(mpsDir+"exmip1");
    siP->readMps(fn.c_str(),"mps");   
    // All integer variables should be binary.
    // Assert that this is true.
    for ( i = 0;  i < siP->getNumCols();  i++ )
      if ( siP->isInteger(i) ) 
        assert(siP->getColUpper()[i]==1.0 && siP->isBinary(i));  
    CglKnapsackCover kccg;
    
    // Solve the LP relaxation of the model and
    // print out ofv for sake of comparison 
    siP->initialSolve();
    double lpRelaxBefore=siP->getObjValue();
    assert( eq(lpRelaxBefore, 3.2368421052631575) );
    double mycs[] = {2.5, 0, 0, 0.6428571428571429, 0.5, 4, 0, 0.26315789473684253};
    siP->setColSolution(mycs);
    // Test generateCuts method
    OsiCuts cuts;    
    kccg.generateCuts(*siP,cuts);
    OsiSolverInterface::ApplyCutsReturnCode rc = siP->applyCuts(cuts);
    
    siP->resolve();
    double lpRelaxAfter=siP->getObjValue();
    assert( eq(lpRelaxAfter, 3.2368421052631575) );
#ifdef CGL_DEBUG
    printf("\n\nOrig LP min=%f\n",lpRelaxBefore);
    printf("\n\nFinal LP min=%f\n",lpRelaxAfter);
#endif
    assert( lpRelaxBefore <= lpRelaxAfter );

    delete siP;
  } 

#ifdef CGL_DEBUG
  // See what findLPMostViolatedMinCover for knapsack with 2 elements does
  {
    int nCols = 2;
    int row = 1;
    CoinPackedVector krow;
    double e[2] = {5,10};
    int ii[2] = {0,1};
    krow.setVector(nCols,ii,e);
    double b=11;
    double xstar[2] = {.2,.9};
    CoinPackedVector cover;
    CoinPackedVector remainder;
    CglKnapsackCover kccg;
    kccg.findLPMostViolatedMinCover(nCols, row, krow, b, xstar, cover, remainder);
    printf("num in cover = %i\n",cover.getNumElements());
    int j;
    for (j=0; j<cover.getNumElements(); j++){
      printf(" index %i element % g\n", cover.getIndices()[j], cover.getElements()[j]);
    }
  }
#endif 

#ifdef CGL_DEBUG
  // see what findLPMostViolatedMinCover does
  {
    int nCols = 5;
    int row = 1;
    CoinPackedVector krow;
    double e[5] = {1,1,1,1,10};
    int ii[5] = {0,1,2,3,4};
    krow.setVector(nCols,ii,e);
    double b=11;
    double xstar[5] = {.9,.9,1,1,.1};
    CoinPackedVector cover;
    CoinPackedVector remainder;
    CglKnapsackCover kccg;
    kccg.findLPMostViolatedMinCover(nCols, row, krow, b, xstar, cover, remainder);
    printf("num in cover = %i\n",cover.getNumElements());
    int j;
    for (j=0; j<cover.getNumElements(); j++){
      printf(" index %i element % g\n", cover.getIndices()[j], cover.getElements()[j]);
    }
  }
#endif

}
Пример #7
0
//void
//inp_nutsource(FILE *fp, bool comfile, char *filename)
void
inp_nutsource(FILE *fp, int comfile, char *filename)
{
    struct line *deck, *dd, *ld;
    struct line *realdeck, *options = NULL;
    char *tt = NULL, name[BSIZE_SP], *s, *t;
    //bool commands = FALSE;
    int commands = FALSE;
    wordlist *wl = NULL, *end = NULL;
    wordlist *controls = NULL;
    FILE *lastin, *lastout, *lasterr;

    deck = inp_readall(fp, NULL, comfile, FALSE); /* still to check if . or filename instead of NULL */
    if (!deck)
        return;

    realdeck = inp_deckcopy(deck);

    if (!comfile) {
        /* Save the title before INPgetTitle gets it. */
        tt = copy(deck->li_line);
        if (!deck->li_next)
            fprintf(cp_err, "Warning: no lines in deck...\n");
    }
    (void) fclose(fp);

    /* Now save the IO context and start a new control set...  After
     * we are done with the source we'll put the old file descriptors
     * back.  I guess we could use a FILE stack, but since this routine
     * is recursive anyway...
     */
    lastin = cp_curin;
    lastout = cp_curout;
    lasterr = cp_curerr;
    cp_curin = cp_in;
    cp_curout = cp_out;
    cp_curerr = cp_err;

    cp_pushcontrol();

    /* We should now go through the deck and execute front-end
     * commands and remove them. Front-end commands are enclosed by
     * the lines .control and .endc, unless comfile
     * is TRUE, in which case every line must be a front-end command.
     * There are too many problems with matching the first word on
     * the line.
     */
    ld = deck;
    if (comfile) {
        /* This is easy. */
        for (dd = deck; dd; dd = ld) {
            ld = dd->li_next;
            if ((dd->li_line[0] == '*') && (dd->li_line[1] != '#'))
                continue;
            if (!ciprefix(".control", dd->li_line) &&
                !ciprefix(".endc", dd->li_line)) {
                if (dd->li_line[0] == '*')
                    (void) cp_evloop(dd->li_line + 2);
                else
                    (void) cp_evloop(dd->li_line);
            }
            tfree(dd->li_line);
            tfree(dd);
        }
    } else {
        for (dd = deck->li_next; dd; dd = ld->li_next) {
            if ((dd->li_line[0] == '*') && (dd->li_line[1] != '#')) {
                ld = dd;
                continue;
            }
            (void) strncpy(name, dd->li_line, BSIZE_SP);
            for (s = name; *s && isspace(*s); s++)
                ;
            for (t = s; *t && !isspace(*t); t++)
                ;
            *t = '\0';

            if (ciprefix(".control", dd->li_line)) {
                ld->li_next = dd->li_next;
                tfree(dd->li_line);
                tfree(dd);
                if (commands)
                    fprintf(cp_err, "Warning: redundant .control line\n");
                else
                    commands = TRUE;
            } else if (ciprefix(".endc", dd->li_line)) {
                ld->li_next = dd->li_next;
                tfree(dd->li_line);
                tfree(dd);
                if (commands)
                    commands = FALSE;
                else
                    fprintf(cp_err, "Warning: misplaced .endc line\n");
            } else if (commands || prefix("*#", dd->li_line)) {
                controls = wl_cons(NULL, controls);
                wl = controls;
                if (prefix("*#", dd->li_line))
                    wl->wl_word = copy(dd->li_line + 2);
                else
                    wl->wl_word = dd->li_line;
                ld->li_next = dd->li_next;
                tfree(dd);
            } else if (!*dd->li_line) {
                /* So blank lines in com files don't get
                 * considered as circuits.
                 */
                ld->li_next = dd->li_next;
                tfree(dd->li_line);
                tfree(dd);
            } else {
                inp_casefix(s);
                inp_casefix(dd->li_line);
                if (eq(s, ".width") || ciprefix(".four", s) ||
                    eq(s, ".plot")  ||
                    eq(s, ".print") ||
                    eq(s, ".save"))
                {
                    wl_append_word(&wl, &end, copy(dd->li_line));
                    ld->li_next = dd->li_next;
                    tfree(dd->li_line);
                    tfree(dd);
                } else {
                    ld = dd;
                }
            }
        }
        if (deck->li_next) {
            /* There is something left after the controls. */
            fprintf(cp_out, "\nCircuit: %s\n\n", tt);
            fprintf(stderr, "\nCircuit: %s\n\n", tt);

            /* Now expand subcircuit macros. Note that we have to
             * fix the case before we do this but after we
             * deal with the commands.
             */
            if (!cp_getvar("nosubckt", CP_BOOL, NULL))
                deck->li_next = inp_subcktexpand(deck->li_next);
            deck->li_actual = realdeck;
            nutinp_dodeck(deck, tt, wl, FALSE, options, filename);
        }

        /* Now that the deck is loaded, do the commands... */
        controls = wl_reverse(controls);
        for (wl = controls; wl; wl = wl->wl_next)
            (void) cp_evloop(wl->wl_word);
        wl_free(controls);
    }

    /* Now reset everything.  Pop the control stack, and fix up the IO
     * as it was before the source.
     */
    cp_popcontrol();

    cp_curin = lastin;
    cp_curout = lastout;
    cp_curerr = lasterr;

    tfree(tt);
}
Пример #8
0
void
/*ARGSUSED*/
doset(Char **v, struct command *t)
{
    Char *p;
    Char   *vp, op;
    Char  **vecp;
    bool    hadsub;
    int     subscr;

    v++;
    p = *v++;
    if (p == 0) {
	prvars();
	return;
    }
    do {
	hadsub = 0;
	vp = p;
	if (letter(*p))
	    for (; alnum(*p); p++)
		continue;
	if (vp == p || !letter(*vp))
	    stderror(ERR_NAME | ERR_VARBEGIN);
	if ((p - vp) > MAXVARLEN) {
	    stderror(ERR_NAME | ERR_VARTOOLONG);
	    return;
	}
	if (*p == '[') {
	    hadsub++;
	    p = getinx(p, &subscr);
	}
	if ((op = *p) != '\0') {
	    *p++ = 0;
	    if (*p == 0 && *v && **v == '(')
		p = *v++;
	}
	else if (*v && eq(*v, STRequal)) {
	    op = '=', v++;
	    if (*v)
		p = *v++;
	}
	if (op && op != '=')
	    stderror(ERR_NAME | ERR_SYNTAX);
	if (eq(p, STRLparen)) {
	    Char **e = v;

	    if (hadsub)
		stderror(ERR_NAME | ERR_SYNTAX);
	    for (;;) {
		if (!*e)
		    stderror(ERR_NAME | ERR_MISSING, ')');
		if (**e == ')')
		    break;
		e++;
	    }
	    p = *e;
	    *e = 0;
	    vecp = saveblk(v);
	    set1(vp, vecp, &shvhed);
	    *e = p;
	    v = e + 1;
	}
	else if (hadsub)
	    asx(vp, subscr, Strsave(p));
	else
	    set(vp, Strsave(p));
	if (eq(vp, STRpath)) {
	    exportpath(adrof(STRpath)->vec);
	    dohash(NULL, NULL);
	}
	else if (eq(vp, STRhistchars)) {
	    Char *pn = value(STRhistchars);

	    HIST = *pn++;
	    HISTSUB = *pn;
	}
	else if (eq(vp, STRuser)) {
	    Setenv(STRUSER, value(vp));
	    Setenv(STRLOGNAME, value(vp));
	}
	else if (eq(vp, STRwordchars)) {
	    word_chars = value(vp);
	}
	else if (eq(vp, STRterm))
	    Setenv(STRTERM, value(vp));
	else if (eq(vp, STRhome)) {
	    Char *cp;

	    cp = Strsave(value(vp));	/* get the old value back */

	    /*
	     * convert to canonical pathname (possibly resolving symlinks)
	     */
	    cp = dcanon(cp, cp);

	    set(vp, Strsave(cp));	/* have to save the new val */

	    /* and now mirror home with HOME */
	    Setenv(STRHOME, cp);
	    /* fix directory stack for new tilde home */
	    dtilde();
	    xfree((ptr_t) cp);
	}
#ifdef FILEC
	else if (eq(vp, STRfilec))
	    filec = 1;
#endif
    } while ((p = *v++) != NULL);
}
bool operator<(const point& a, const point& b){
    return eq(a.x, b.x) ? lt(a.y, b.y) : lt(a.x, b.x);
}
template <typename T> bool ne (T x_, T y_, T round_) {return ! eq (x_, y_, round_);}
Пример #11
0
void
/*ARGSUSED*/
dolet(Char **v, struct command *t)
{
    Char *p;
    Char   *vp, c, op;
    bool    hadsub;
    int     subscr;

    v++;
    p = *v++;
    if (p == 0) {
	prvars();
	return;
    }
    do {
	hadsub = 0;
	vp = p;
	if (letter(*p))
	    for (; alnum(*p); p++)
		continue;
	if (vp == p || !letter(*vp))
	    stderror(ERR_NAME | ERR_VARBEGIN);
	if ((p - vp) > MAXVARLEN)
	    stderror(ERR_NAME | ERR_VARTOOLONG);
	if (*p == '[') {
	    hadsub++;
	    p = getinx(p, &subscr);
	}
	if (*p == 0 && *v)
	    p = *v++;
	if ((op = *p) != '\0')
	    *p++ = 0;
	else
	    stderror(ERR_NAME | ERR_ASSIGN);

	if (*p == '\0' && *v == NULL)
	    stderror(ERR_NAME | ERR_ASSIGN);

	vp = Strsave(vp);
	if (op == '=') {
	    c = '=';
	    p = xset(p, &v);
	}
	else {
	    c = *p++;
	    if (any("+-", c)) {
		if (c != op || *p)
		    stderror(ERR_NAME | ERR_UNKNOWNOP);
		p = Strsave(STR1);
	    }
	    else {
		if (any("<>", op)) {
		    if (c != op)
			stderror(ERR_NAME | ERR_UNKNOWNOP);
		    c = *p++;
		    stderror(ERR_NAME | ERR_SYNTAX);
		}
		if (c != '=')
		    stderror(ERR_NAME | ERR_UNKNOWNOP);
		p = xset(p, &v);
	    }
	}
	if (op == '=')
	    if (hadsub)
		asx(vp, subscr, p);
	    else
		set(vp, p);
	else if (hadsub) {
	    struct varent *gv = getvx(vp, subscr);

	    asx(vp, subscr, operate(op, gv->vec[subscr - 1], p));
	}
	else
	    set(vp, operate(op, value(vp), p));
	if (eq(vp, STRpath)) {
	    exportpath(adrof(STRpath)->vec);
	    dohash(NULL, NULL);
	}
	xfree((ptr_t) vp);
	if (c != '=')
	    xfree((ptr_t) p);
    } while ((p = *v++) != NULL);
}
Пример #12
0
int test_reg_str(void *state) {
	errr r = parser_reg(state, "test-reg-str str baz", ignored);
	eq(r, 0);
	ok;
}
Пример #13
0
int test_reg_sym(void *state) {
	errr r = parser_reg(state, "test-reg-sym sym bar", ignored);
	eq(r, 0);
	ok;
}
Пример #14
0
int test_reg_int(void *state) {
	errr r = parser_reg(state, "test-reg-int int foo", ignored);
	eq(r, 0);
	ok;
}
Пример #15
0
/* search forward for a <patrn>	*/
int
forscan(int *wrapt,	/* boolean indicating search wrapped */
	UCS *patrn,	/* string to scan for */
	LINE *limitp,	/* stop searching if reached */
	int limito,	/* stop searching if reached */
	int leavep)	/* place to leave point
				PTBEG = begining of match
				PTEND = at end of match		*/

{
    LINE *curline;	/* current line during scan */
    int curoff;		/* position within current line */
    LINE *lastline;	/* last line position during scan */
    int lastoff;	/* position within last line */
    UCS c;		/* character at current position */
    LINE *matchline;	/* current line during matching */
    int matchoff;	/* position in matching line */
    UCS *patptr;	/* pointer into pattern */
    int stopoff;	/* offset to stop search */
    LINE *stopline;	/* line to stop search */

    *wrapt = FALSE;

    /*
     * the idea is to set the character to end the search at the 
     * next character in the buffer.  thus, let the search wrap
     * completely around the buffer.
     * 
     * first, test to see if we are at the end of the line, 
     * otherwise start searching on the next character. 
     */
    if(curwp->w_doto == llength(curwp->w_dotp)){
	/*
	 * dot is not on end of a line
	 * start at 0 offset of the next line
	 */
	stopoff = curoff  = 0;
	stopline = curline = lforw(curwp->w_dotp);
	if (curwp->w_dotp == curbp->b_linep)
	  *wrapt = TRUE;
    }
    else{
	stopoff = curoff  = curwp->w_doto;
	stopline = curline = curwp->w_dotp;
    }

    /* scan each character until we hit the head link record */

    /*
     * maybe wrapping is a good idea
     */
    while (curline){

	if (curline == curbp->b_linep)
	  *wrapt = TRUE;

	/* save the current position in case we need to
	   restore it on a match			*/

	lastline = curline;
	lastoff = curoff;

	/* get the current character resolving EOLs */
	if (curoff == llength(curline)) {	/* if at EOL */
	    curline = lforw(curline);	/* skip to next line */
	    curoff = 0;
	    c = '\n';			/* and return a <NL> */
	}
	else
	  c = lgetc(curline, curoff++).c;	/* get the char */

	/* test it against first char in pattern */
	if (eq(c, patrn[0]) != FALSE) {	/* if we find it..*/
	    /* setup match pointers */
	    matchline = curline;
	    matchoff = curoff;
	    patptr = &patrn[0];

	    /* scan through patrn for a match */
	    while (*++patptr != '\0') {
		/* advance all the pointers */
		if (matchoff == llength(matchline)) {
		    /* advance past EOL */
		    matchline = lforw(matchline);
		    matchoff = 0;
		    c = '\n';
		} else
		  c = lgetc(matchline, matchoff++).c;

		if(matchline == limitp && matchoff == limito)
		  return(FALSE);

		/* and test it against the pattern */
		if (eq(*patptr, c) == FALSE)
		  goto fail;
	    }

	    /* A SUCCESSFULL MATCH!!! */
	    /* reset the global "." pointers */
	    if (leavep == PTEND) {	/* at end of string */
		curwp->w_dotp = matchline;
		curwp->w_doto = matchoff;
	    }
	    else {		/* at begining of string */
		curwp->w_dotp = lastline;
		curwp->w_doto = lastoff;
	    }

	    curwp->w_flag |= WFMOVE; /* flag that we have moved */
	    return(TRUE);

	}

fail:;			/* continue to search */
	if(((curline == stopline) && (curoff == stopoff))
	   || (curline == limitp && curoff == limito))
	  break;			/* searched everywhere... */
    }
    /* we could not find a match */

    return(FALSE);
}
// check if point p is on line segment (u, v)
bool is_point_on_segment(const point& p, const point& u, const point& v){
    return eq(0, cross_product(u, v, p)) && ngt(dot_product(u, v, p), 0);
}
Пример #17
0
inline bool eq(const T1& lhs, const T2& rhs) {
  return lhs.get_head() == rhs.get_head() &&
         eq(lhs.get_tail(), rhs.get_tail());
}
// check if two lines intersect
bool is_intersect_l2l(const point& u1, const point& u2,
                      const point& v1, const point& v2){
    return !eq(0, ((u1.x - u2.x)*(v1.y - v2.y) - (u1.y - u2.y)*(v1.x - v2.x)));
}
Пример #19
0
BOOL is_keyword(Symbol sym)
{
    return eq(pkg_kw, symbol_package(sym));
}
// check if two cirles touch(either internally or externally)
bool is_touch_c2c(const circle& a, const circle& b){
    return eq(distance_p2p(a.c, b.c), a.r + b.r)
           || eq(distance_p2p(a.c, b.c), fabs(a.r - b.r));
}
 bool equals(const void* lhs, const void* rhs) const override {
     return eq(deref(lhs), deref(rhs));
 }
Пример #22
0
void
process(FILE *f)
{
	int i, n;
	char line[256];	/* the current line */
	char mac[5];	/* The current macro or nroff command */
	int pl;

	stktop = -1;
	for (lineno = 1; fgets(line, sizeof line, f); lineno++) {
		if (line[0] == '.') {
			/*
			 * find and isolate the macro/command name.
			 */
			strncpy(mac, line+1, 4);
			if (isspace((unsigned char)mac[0])) {
				pe(lineno);
				printf("Empty command\n");
			} else if (isspace((unsigned char)mac[1])) {
				mac[1] = 0;
			} else if (isspace((unsigned char)mac[2])) {
				mac[2] = 0;
			} else if (mac[0] != '\\' || mac[1] != '\"') {
				pe(lineno);
				printf("Command too long\n");
			}

			/*
			 * Is it a known command?
			 */
			checkknown(mac);

			/*
			 * Should we add it?
			 */
			if (eq(mac, "de"))
				addcmd(line);

			chkcmd(line, mac);
		}

		/*
		 * At this point we process the line looking
		 * for \s and \f.
		 */
		for (i=0; line[i]; i++)
			if (line[i]=='\\' && (i==0 || line[i-1]!='\\')) {
				if (!sflag && line[++i]=='s') {
					pl = line[++i];
					if (isdigit((unsigned char)pl)) {
						n = pl - '0';
						pl = ' ';
					} else
						n = 0;
					while (isdigit((unsigned char)line[++i]))
						n = 10 * n + line[i] - '0';
					i--;
					if (n == 0) {
						if (stktop >= 0 && 
						    stk[stktop].opno == SZ) {
							stktop--;
						} else {
							pe(lineno);
							printf("unmatched \\s0\n");
						}
					} else {
						stk[++stktop].opno = SZ;
						stk[stktop].pl = pl;
						stk[stktop].parm = n;
						stk[stktop].lno = lineno;
					}
				} else if (!fflag && line[i]=='f') {
					n = line[++i];
					if (n == 'P') {
						if (stktop >= 0 && 
						    stk[stktop].opno == FT) {
							stktop--;
						} else {
							pe(lineno);
							printf("unmatched \\fP\n");
						}
					} else {
						stk[++stktop].opno = FT;
						stk[stktop].pl = 1;
						stk[stktop].parm = n;
						stk[stktop].lno = lineno;
					}
				}
			}
	}
	/*
	 * We've hit the end and look at all this stuff that hasn't been
	 * matched yet!  Complain, complain.
	 */
	for (i=stktop; i>=0; i--) {
		complain(i);
	}
}
Пример #23
0
static int test_badmax(void *state) {
	errr r = parser_parse(state, "M:D:1");
	eq(r, PARSE_ERROR_UNDEFINED_DIRECTIVE);
	ok;
}
Пример #24
0
/*
 * Moves content of message buffer attached to a message into a heap.
 * The message buffer is deallocated.
 */
void
erts_move_msg_mbuf_to_heap(Eterm** hpp, ErlOffHeap* off_heap, ErlMessage *msg)
{
    struct erl_off_heap_header* oh;
    Eterm term, token, *fhp, *hp;
    Sint offs;
    Uint sz;
    ErlHeapFragment *bp;
#ifdef USE_VM_PROBES
    Eterm utag;
#endif

#ifdef HARD_DEBUG
    ProcBin *dbg_mso_start = off_heap->mso;
    ErlFunThing *dbg_fun_start = off_heap->funs;
    ExternalThing *dbg_external_start = off_heap->externals;
    Eterm dbg_term, dbg_token;
    ErlHeapFragment *dbg_bp;
    Uint *dbg_hp, *dbg_thp_start;
    Uint dbg_term_sz, dbg_token_sz;
#ifdef USE_VM_PROBES
    Eterm dbg_utag;
    Uint dbg_utag_sz;
#endif
#endif

    bp = msg->data.heap_frag;
    term = ERL_MESSAGE_TERM(msg);
    token = ERL_MESSAGE_TOKEN(msg);
#ifdef USE_VM_PROBES
    utag = ERL_MESSAGE_DT_UTAG(msg);
#endif
    if (!bp) {
#ifdef USE_VM_PROBES
        ASSERT(is_immed(term) && is_immed(token) && is_immed(utag));
#else
        ASSERT(is_immed(term) && is_immed(token));
#endif
        return;
    }

#ifdef HARD_DEBUG
    dbg_term_sz = size_object(term);
    dbg_token_sz = size_object(token);
    dbg_bp = new_message_buffer(dbg_term_sz + dbg_token_sz);
#ifdef USE_VM_PROBES
    dbg_utag_sz = size_object(utag);
    dbg_bp = new_message_buffer(dbg_term_sz + dbg_token_sz + dbg_utag_sz );
#endif
    /*ASSERT(dbg_term_sz + dbg_token_sz == erts_msg_used_frag_sz(msg));
      Copied size may be smaller due to removed SubBins's or garbage.
      Copied size may be larger due to duplicated shared terms.
    */
    dbg_hp = dbg_bp->mem;
    dbg_term = copy_struct(term, dbg_term_sz, &dbg_hp, &dbg_bp->off_heap);
    dbg_token = copy_struct(token, dbg_token_sz, &dbg_hp, &dbg_bp->off_heap);
#ifdef USE_VM_PROBES
    dbg_utag = copy_struct(utag, dbg_utag_sz, &dbg_hp, &dbg_bp->off_heap);
#endif
    dbg_thp_start = *hpp;
#endif

    if (bp->next != NULL) {
        move_multi_frags(hpp, off_heap, bp, msg->m,
#ifdef USE_VM_PROBES
                         3
#else
                         2
#endif
                        );
        goto copy_done;
    }

    OH_OVERHEAD(off_heap, bp->off_heap.overhead);
    sz = bp->used_size;

    ASSERT(is_immed(term) || in_heapfrag(ptr_val(term),bp));
    ASSERT(is_immed(token) || in_heapfrag(ptr_val(token),bp));

    fhp = bp->mem;
    hp = *hpp;
    offs = hp - fhp;

    oh = NULL;
    while (sz--) {
        Uint cpy_sz;
        Eterm val = *fhp++;

        switch (primary_tag(val)) {
        case TAG_PRIMARY_IMMED1:
            *hp++ = val;
            break;
        case TAG_PRIMARY_LIST:
        case TAG_PRIMARY_BOXED:
            ASSERT(in_heapfrag(ptr_val(val), bp));
            *hp++ = offset_ptr(val, offs);
            break;
        case TAG_PRIMARY_HEADER:
            *hp++ = val;
            switch (val & _HEADER_SUBTAG_MASK) {
            case ARITYVAL_SUBTAG:
                break;
            case REFC_BINARY_SUBTAG:
            case FUN_SUBTAG:
            case EXTERNAL_PID_SUBTAG:
            case EXTERNAL_PORT_SUBTAG:
            case EXTERNAL_REF_SUBTAG:
                oh = (struct erl_off_heap_header*) (hp-1);
                cpy_sz = thing_arityval(val);
                goto cpy_words;
            default:
                cpy_sz = header_arity(val);

cpy_words:
                ASSERT(sz >= cpy_sz);
                sz -= cpy_sz;
                while (cpy_sz >= 8) {
                    cpy_sz -= 8;
                    *hp++ = *fhp++;
                    *hp++ = *fhp++;
                    *hp++ = *fhp++;
                    *hp++ = *fhp++;
                    *hp++ = *fhp++;
                    *hp++ = *fhp++;
                    *hp++ = *fhp++;
                    *hp++ = *fhp++;
                }
                switch (cpy_sz) {
                case 7:
                    *hp++ = *fhp++;
                case 6:
                    *hp++ = *fhp++;
                case 5:
                    *hp++ = *fhp++;
                case 4:
                    *hp++ = *fhp++;
                case 3:
                    *hp++ = *fhp++;
                case 2:
                    *hp++ = *fhp++;
                case 1:
                    *hp++ = *fhp++;
                default:
                    break;
                }
                if (oh) {
                    /* Add to offheap list */
                    oh->next = off_heap->first;
                    off_heap->first = oh;
                    ASSERT(*hpp <= (Eterm*)oh);
                    ASSERT(hp > (Eterm*)oh);
                    oh = NULL;
                }
                break;
            }
            break;
        }
    }

    ASSERT(bp->used_size == hp - *hpp);
    *hpp = hp;

    if (is_not_immed(token)) {
        ASSERT(in_heapfrag(ptr_val(token), bp));
        ERL_MESSAGE_TOKEN(msg) = offset_ptr(token, offs);
#ifdef HARD_DEBUG
        ASSERT(dbg_thp_start <= ptr_val(ERL_MESSAGE_TOKEN(msg)));
        ASSERT(hp > ptr_val(ERL_MESSAGE_TOKEN(msg)));
#endif
    }

    if (is_not_immed(term)) {
        ASSERT(in_heapfrag(ptr_val(term),bp));
        ERL_MESSAGE_TERM(msg) = offset_ptr(term, offs);
#ifdef HARD_DEBUG
        ASSERT(dbg_thp_start <= ptr_val(ERL_MESSAGE_TERM(msg)));
        ASSERT(hp > ptr_val(ERL_MESSAGE_TERM(msg)));
#endif
    }
#ifdef USE_VM_PROBES
    if (is_not_immed(utag)) {
        ASSERT(in_heapfrag(ptr_val(utag), bp));
        ERL_MESSAGE_DT_UTAG(msg) = offset_ptr(utag, offs);
#ifdef HARD_DEBUG
        ASSERT(dbg_thp_start <= ptr_val(ERL_MESSAGE_DT_UTAG(msg)));
        ASSERT(hp > ptr_val(ERL_MESSAGE_DT_UTAG(msg)));
#endif
    }
#endif

copy_done:

#ifdef HARD_DEBUG
    {
        int i, j;
        ErlHeapFragment* frag;
        {
            ProcBin *mso = off_heap->mso;
            i = j = 0;
            while (mso != dbg_mso_start) {
                mso = mso->next;
                i++;
            }
            for (frag=bp; frag; frag=frag->next) {
                mso = frag->off_heap.mso;
                while (mso) {
                    mso = mso->next;
                    j++;
                }
            }
            ASSERT(i == j);
        }
        {
            ErlFunThing *fun = off_heap->funs;
            i = j = 0;
            while (fun != dbg_fun_start) {
                fun = fun->next;
                i++;
            }
            for (frag=bp; frag; frag=frag->next) {
                fun = frag->off_heap.funs;
                while (fun) {
                    fun = fun->next;
                    j++;
                }
            }
            ASSERT(i == j);
        }
        {
            ExternalThing *external = off_heap->externals;
            i = j = 0;
            while (external != dbg_external_start) {
                external = external->next;
                i++;
            }
            for (frag=bp; frag; frag=frag->next) {
                external = frag->off_heap.externals;
                while (external) {
                    external = external->next;
                    j++;
                }
            }
            ASSERT(i == j);
        }
    }
#endif


    bp->off_heap.first = NULL;
    free_message_buffer(bp);
    msg->data.heap_frag = NULL;

#ifdef HARD_DEBUG
    ASSERT(eq(ERL_MESSAGE_TERM(msg), dbg_term));
    ASSERT(eq(ERL_MESSAGE_TOKEN(msg), dbg_token));
#ifdef USE_VM_PROBES
    ASSERT(eq(ERL_MESSAGE_DT_UTAG(msg), dbg_utag));
#endif
    free_message_buffer(dbg_bp);
#endif

}
Пример #25
0
            return x;
        }

    private:
        int x;
    };
}

FIXTURE(ListTest)
{
	TEST("should be empty when init")
	{
		ASSERT_THAT(__IS_NULL(elems.getFirst()), be_true());
	    ASSERT_THAT(__IS_NULL(elems.getLast()), be_true());
	    ASSERT_THAT(elems.isEmpty(), be_true());
	    ASSERT_THAT(elems.size(), eq(0));
	}

	TEST("should be get elem when list is not empty")
	{
	    Foo elem(1);

	    elems.pushBack(elem);

	    ASSERT_THAT(elems.isEmpty(), be_false());
	    ASSERT_THAT(elems.size(), eq(1));
	    ASSERT_THAT(elems.getFirst(), eq(&elem));
	    ASSERT_THAT(elems.getLast(), eq(&elem));

	    Foo* first = elems.popFront();
	    ASSERT_THAT(first->getValue(), eq(1));
Пример #26
0
ErlHeapFragment*
erts_resize_message_buffer(ErlHeapFragment *bp, Uint size,
                           Eterm *brefs, Uint brefs_size)
{
#ifdef DEBUG
    int i;
#endif
#ifdef HARD_DEBUG
    ErlHeapFragment *dbg_bp;
    Eterm *dbg_brefs;
    Uint dbg_size;
    Uint dbg_tot_size;
    Eterm *dbg_hp;
#endif
    ErlHeapFragment* nbp;

    /* ToDo: Make use of 'used_size' to avoid realloc
    when shrinking just a few words */

#ifdef DEBUG
    {
        Uint off_sz = size < bp->used_size ? size : bp->used_size;
        for (i = 0; i < brefs_size; i++) {
            Eterm *ptr;
            if (is_immed(brefs[i]))
                continue;
            ptr = ptr_val(brefs[i]);
            ASSERT(&bp->mem[0] <= ptr && ptr < &bp->mem[0] + off_sz);

        }
    }
#endif

    if (size == bp->used_size)
        return bp;

#ifdef HARD_DEBUG
    dbg_brefs = erts_alloc(ERTS_ALC_T_UNDEF, sizeof(Eterm *)*brefs_size);
    dbg_bp = new_message_buffer(bp->used_size);
    dbg_hp = dbg_bp->mem;
    dbg_tot_size = 0;
    for (i = 0; i < brefs_size; i++) {
        dbg_size = size_object(brefs[i]);
        dbg_tot_size += dbg_size;
        dbg_brefs[i] = copy_struct(brefs[i], dbg_size, &dbg_hp,
                                   &dbg_bp->off_heap);
    }
    ASSERT(dbg_tot_size == (size < bp->used_size ? size : bp->used_size));
#endif

    nbp = (ErlHeapFragment*) ERTS_HEAP_REALLOC(ERTS_ALC_T_HEAP_FRAG,
            (void *) bp,
            ERTS_HEAP_FRAG_SIZE(bp->alloc_size),
            ERTS_HEAP_FRAG_SIZE(size));
    if (bp != nbp) {
        Uint off_sz = size < nbp->used_size ? size : nbp->used_size;
        Eterm *sp = &bp->mem[0];
        Eterm *ep = sp + off_sz;
        Sint offs = &nbp->mem[0] - sp;
        erts_offset_off_heap(&nbp->off_heap, offs, sp, ep);
        erts_offset_heap(&nbp->mem[0], off_sz, offs, sp, ep);
        if (brefs && brefs_size)
            erts_offset_heap_ptr(brefs, brefs_size, offs, sp, ep);
#ifdef DEBUG
        for (i = 0; i < brefs_size; i++) {
            Eterm *ptr;
            if (is_immed(brefs[i]))
                continue;
            ptr = ptr_val(brefs[i]);
            ASSERT(&nbp->mem[0] <= ptr && ptr < &nbp->mem[0] + off_sz);
        }
#endif
    }
    nbp->alloc_size = size;
    nbp->used_size = size;

#ifdef HARD_DEBUG
    for (i = 0; i < brefs_size; i++)
        ASSERT(eq(dbg_brefs[i], brefs[i]));
    free_message_buffer(dbg_bp);
    erts_free(ERTS_ALC_T_UNDEF, dbg_brefs);
#endif

    return nbp;
}
Пример #27
0
bool operator==(const audio_transform& lhs, const audio_transform& rhs) { return eq(lhs.volume, rhs.volume); }
Пример #28
0
int
forwsearch(int f, int n)
{
  int              status;
  int              wrapt = FALSE, wrapt2 = FALSE;
  int              repl_mode = FALSE;
  UCS              defpat[NPAT];
  int              search = FALSE;
  EML              eml;

    /* resolve the repeat count */
    if (n == 0)
      n = 1;

    if (n < 1)			/* search backwards */
      FWS_RETURN(0);

    defpat[0] = '\0';

    /* ask the user for the text of a pattern */
    while(1){

	if (gmode & MDREPLACE)
	  status = srpat("Search", defpat, NPAT, repl_mode);
	else
	  status = readpattern("Search", TRUE);

	switch(status){
	  case TRUE:                         /* user typed something */
	    search = TRUE;
	    break;

	  case HELPCH:			/* help requested */
	    if(Pmaster){
		VARS_TO_SAVE *saved_state;

		saved_state = save_pico_state();
		(*Pmaster->helper)(Pmaster->search_help,
				   _("Help for Searching"), 1);
		if(saved_state){
		    restore_pico_state(saved_state);
		    free_pico_state(saved_state);
		}
	    }
	    else
	      pico_help(SearchHelpText, _("Help for Searching"), 1);

	  case (CTRL|'L'):			/* redraw requested */
	    pico_refresh(FALSE, 1);
	    update();
	    break;

	  case  (CTRL|'V'):
	    gotoeob(0, 1);
	    mlerase();
	    FWS_RETURN(TRUE);

	  case (CTRL|'Y'):
	    gotobob(0, 1);
	    mlerase();
	    FWS_RETURN(TRUE); 

	  case (CTRL|'T') :
	    switch(status = readnumpat(_("Search to Line Number : "))){
	      case -1 :
		emlwrite(_("Search to Line Number Cancelled"), NULL);
		FWS_RETURN(FALSE);

	      case  0 :
		emlwrite(_("Line number must be greater than zero"), NULL);
		FWS_RETURN(FALSE);

	      case -2 :
		emlwrite(_("Line number must contain only digits"), NULL);
		FWS_RETURN(FALSE);
		
	      case -3 :
		continue;

	      default :
		gotoline(0, status);
		mlerase();
		FWS_RETURN(TRUE);
	    }

	    break;

	  case  (CTRL|'W'):
	    {
		LINE *linep = curwp->w_dotp;
		int   offset = curwp->w_doto;

		gotobop(0, 1);
		gotobol(0, 1);

		/*
		 * if we're asked to backup and we're already
		 *
		 */
		if((lastflag & CFSRCH)
		   && linep == curwp->w_dotp
		   && offset == curwp->w_doto
		   && !(offset == 0 && lback(linep) == curbp->b_linep)){
		    backchar(0, 1);
		    gotobop(0, 1);
		    gotobol(0, 1);
		}
	    }

	    mlerase();
	    FWS_RETURN(TRUE);

	  case  (CTRL|'O'):
	    if(curwp->w_dotp != curbp->b_linep){
		gotoeop(0, 1);
		forwchar(0, 1);
	    }

	    mlerase();
	    FWS_RETURN(TRUE);

	  case (CTRL|'U'):
	    fillbuf(0, 1);
	    mlerase();
	    FWS_RETURN(TRUE);

	  case  (CTRL|'R'):        /* toggle replacement option */
	    repl_mode = !repl_mode;
	    break;

	  default:
	    if(status == ABORT)
	      emlwrite(_("Search Cancelled"), NULL);
	    else
	      mlerase();

	    FWS_RETURN(FALSE);
	}

	/* replace option is disabled */
	if (!(gmode & MDREPLACE)){
	    ucs4_strncpy(defpat, pat, NPAT);
	    defpat[NPAT-1] = '\0';
	    break;
	}
	else if (search){  /* search now */
	    ucs4_strncpy(pat, defpat, NPAT);	/* remember this search for the future */
	    pat[NPAT-1] = '\0';
	    break;
	}
    }

    /*
     * This code is kind of dumb.  What I want is successive C-W 's to 
     * move dot to successive occurences of the pattern.  So, if dot is
     * already sitting at the beginning of the pattern, then we'll move
     * forward a char before beginning the search.  We'll let the
     * automatic wrapping handle putting the dot back in the right 
     * place...
     */
    status = 0;		/* using "status" as int temporarily! */
    while(1){
	if(defpat[status] == '\0'){
	    forwchar(0, 1);
	    break;		/* find next occurence! */
	}

	if(status + curwp->w_doto >= llength(curwp->w_dotp) ||
	   !eq(defpat[status],lgetc(curwp->w_dotp, curwp->w_doto + status).c))
	  break;		/* do nothing! */
	status++;
    }

    /* search for the pattern */
    
    while (n-- > 0) {
	if((status = forscan(&wrapt,defpat,NULL,0,PTBEG)) == FALSE)
	  break;
    }

    /* and complain if not there */
    if (status == FALSE){
      char *utf8;
      UCS x[1];

      x[0] = '\0';

      utf8 = ucs4_to_utf8_cpystr(defpat ? defpat : x); 
      /* TRANSLATORS: reporting the result of a failed search */
      eml.s = utf8;
      emlwrite(_("\"%s\" not found"), &eml);
      if(utf8)
	fs_give((void **) &utf8);
    }
    else if((gmode & MDREPLACE) && repl_mode == TRUE){
        status = replace_pat(defpat, &wrapt2);    /* replace pattern */
	if (wrapt == TRUE || wrapt2 == TRUE){
	    eml.s = (status == ABORT) ? "cancelled but wrapped" : "Wrapped";
	    emlwrite("Replacement %s", &eml);
	}
    }
    else if(wrapt == TRUE){
	emlwrite("Search Wrapped", NULL);
    }
    else if(status == TRUE){
	emlwrite("", NULL);
    }

    FWS_RETURN(status);
}
Пример #29
0
std::uint16_t VirtualCPU::executeInstructionAtAddress(std::uint16_t address) {
  debugger_.pc_  = address; //HACK FOR NOW
    switch (memoryController_.readAtAddress(address)) {
        case 0:
            return address + halt();
        case 1:
            return address + set(memoryController_.readAtAddress(address + 1), memoryController_.readAtAddress(address + 2));
        case 2:
            return address + push(memoryController_.readAtAddress(address + 1));
        case 3:
            return address + pop(memoryController_.readAtAddress(address + 1));
        case 4:
            return address +
                    eq(memoryController_.readAtAddress(address + 1),
                       memoryController_.readAtAddress(address + 2),
                       memoryController_.readAtAddress(address + 3));
        case 5:
            return address + gt(memoryController_.readAtAddress(address + 1),
                                memoryController_.readAtAddress(address +2),
                                memoryController_.readAtAddress(address + 3));
        case 6:
            return jump(memoryController_.readAtAddress(address + 1), address);
        case 7:
            return jt(memoryController_.readAtAddress(address + 1),
                                memoryController_.readAtAddress(address + 2),
                                address);
        case 8:
            return jf(memoryController_.readAtAddress(address + 1),
                                memoryController_.readAtAddress(address + 2),
                                address);
        case 9:
            return address + add(memoryController_.readAtAddress(address + 1),
                                 memoryController_.readAtAddress(address + 2),
                                 memoryController_.readAtAddress(address + 3));
        case 10:
            return address + mult(memoryController_.readAtAddress(address + 1),
                                 memoryController_.readAtAddress(address + 2),
                                 memoryController_.readAtAddress(address + 3));
        case 11:
            return address + mod(memoryController_.readAtAddress(address + 1),
                                  memoryController_.readAtAddress(address + 2),
                                  memoryController_.readAtAddress(address + 3));
        case 12:
            return address + and_i(memoryController_.readAtAddress(address + 1),
                                 memoryController_.readAtAddress(address + 2),
                                 memoryController_.readAtAddress(address + 3));
        case 13:
            return address + or_i(memoryController_.readAtAddress(address + 1),
                                 memoryController_.readAtAddress(address + 2),
                                 memoryController_.readAtAddress(address + 3));
        case 14:
            return address + not_i(memoryController_.readAtAddress(address + 1),
                                 memoryController_.readAtAddress(address + 2));
        case 15:
            return address + rmem(memoryController_.readAtAddress(address + 1),
                                 memoryController_.readAtAddress(address + 2));
        case 16:
            return address + wmem(memoryController_.readAtAddress(address + 1),
                                  memoryController_.readAtAddress(address + 2));
        case 17:
            return call(memoryController_.readAtAddress(address + 1), address);
        case 18:
            return ret();
        case 19:
            return address + out(memoryController_.readAtAddress(address + 1));
        case 21:
            return address + noop();
        case 20:
            return address + in(memoryController_.readAtAddress(address + 1));
        default:
            std::cout << "CPU ERROR illegal op code: " << memoryController_.readAtAddress(address) << std::endl;
            return address + 1;
    }
}
Пример #30
0
int test_reg4(void *state) {
	errr r = parser_reg(state, "abc int a ?int b int c", ignored);
	eq(r, -EINVAL);
	ok;
}