Esempio n. 1
0
bool                              // returns true if success
processTreeSection(FILE *fp,
		   string& theline,
		   bool& new_section)
{
  string *tid  = NULL;
  TChain  *t1   = NULL;
  vector<string> v_tokens;

  string treename;

  if (gl_verbose)
    cout << "Processing Tree section" << endl;

  new_section=false;

  while (getLine(fp,theline,"Tree")) {
    if (!theline.size()) continue;
    if (theline[0] == '#') continue; // comments are welcome

    if (theline[0] == '[') {
      new_section=true;
      break;
    }

    string key, value;
    if (!getKeyValue(theline,key,value)) continue;

    //--------------------
    if (key == "id") {
    //--------------------
      if (tid != NULL) {
	cerr << "no more than one id per F1 section allowed " << value << endl;
	break;
      }
      tid = new string(value);
      
      map<string, TChain *>::const_iterator tit = glmap_id2chain.find(*tid);
      if (tit != glmap_id2chain.end()) {
	cerr << "Tree id " << *tid << " already defined" << endl;
	break;
      }
    //------------------------------
    } else if( key == "treename" ) {
    //------------------------------
      if( !tid ) {
	cerr << "id key must be defined first in the section" << endl; continue;
      }
      if( t1 ) {
	cerr << "Tree already defined" << endl; continue;
      }
      treename = value;

    //------------------------------
    } else if( key == "globslist" ) {
    //------------------------------
      t1 = getChainFromGlobslist(*tid,treename,value);
      if( !t1 )
	exit(-1);

    //------------------------------
    } else if( key == "copytree" ) {
    //------------------------------
      if( !tid ) {
	cerr << "id key must be defined first in the section" << endl; continue;      }
    
      Tokenize(value,v_tokens,",");
      
      if (v_tokens.size() != 2) {
	cerr << "copytree syntax expected: copytree=treeid,cutstring: " << value << endl; continue; }

      TChain *t2 = findChain(v_tokens[0]);
      if (!t2) {
	cerr << "tree " << v_tokens[0] << " must be defined previously" << endl; continue;    }
      if (gl_verbose)
	cout<<"Begin CopyTree of "<<v_tokens[0]<<" with selection "<<v_tokens[1]<<flush;
      
      t1 = (TChain *)(t2->CopyTree(v_tokens[1].c_str()));

      if( !t1 ) {
	cerr << "CopyTree failed" << endl; exit(-1); }

      if (gl_verbose)
	cout<<"...Done."<<endl;

    //------------------------------
    } else if( key == "save2file" ) {
    //------------------------------
      if( !t1 ) {
	cerr << "save2file: must define tree first" << endl; continue; }

      TFile *rootfile = openRootFile(value,"RECREATE");
      
      t1->SetDirectory(rootfile);
      t1->Write();
      rootfile->Flush();

      if (gl_verbose)
	cout << "Tree written to file " << value << endl;

      rootfile->Close();

    //------------------------------
    } else if( key == "unbinnedfit" ) {
    //------------------------------
      if( !tid ) {
	cerr << "id key must be defined first in the section" << endl; continue;      }
      if( !t1 ) {
	cerr << "Tree must already be defined using 'globslist'" << endl; continue;   }

      int fitresult=-99;

      Tokenize(value,v_tokens,",");
      switch(v_tokens.size()) {
      case 2: fitresult = t1->UnbinnedFit(v_tokens[0].c_str(),
					  v_tokens[1].c_str());
	break;
      case 3: fitresult = t1->UnbinnedFit(v_tokens[0].c_str(),
					  v_tokens[1].c_str(),
					  v_tokens[2].c_str()); 
	break;
      case 4: fitresult = t1->UnbinnedFit(v_tokens[0].c_str(),  // funcname
					  v_tokens[1].c_str(),  // varexp
					  v_tokens[2].c_str(),  // selection
					  v_tokens[3].c_str()); // option
	break;
      default:
	cerr << "unbinnedfit: expect 2-4 arguments separated by commas: " << value <<endl;
	exit(-1);
      }
      cout << "fit result returned = " << fitresult << endl;
      cout << "Number of selected entries in the fit = " << t1->GetSelectedRows() << endl;
    }
    else {
      cerr << "unknown key " << key << endl;
    }
  }

  if (tid) delete tid;
  return (t1 != NULL);
}                                                  // processTreesection
Esempio n. 2
0
TIntermTyped* TIntermConstantUnion::fold(TOperator op, TIntermTyped* constantNode, TInfoSink& infoSink)
{
    ConstantUnion *unionArray = getUnionArrayPointer();
    int objectSize = getType().getObjectSize();

    if (constantNode) {  // binary operations
        TIntermConstantUnion *node = constantNode->getAsConstantUnion();
        ConstantUnion *rightUnionArray = node->getUnionArrayPointer();
        TType returnType = getType();

        // for a case like float f = 1.2 + vec4(2,3,4,5);
        if (constantNode->getType().getObjectSize() == 1 && objectSize > 1) {
            rightUnionArray = new ConstantUnion[objectSize];
            for (int i = 0; i < objectSize; ++i)
                rightUnionArray[i] = *node->getUnionArrayPointer();
            returnType = getType();
        } else if (constantNode->getType().getObjectSize() > 1 && objectSize == 1) {
            // for a case like float f = vec4(2,3,4,5) + 1.2;
            unionArray = new ConstantUnion[constantNode->getType().getObjectSize()];
            for (int i = 0; i < constantNode->getType().getObjectSize(); ++i)
                unionArray[i] = *getUnionArrayPointer();
            returnType = node->getType();
            objectSize = constantNode->getType().getObjectSize();
        }

        ConstantUnion* tempConstArray = 0;
        TIntermConstantUnion *tempNode;

        bool boolNodeFlag = false;
        switch(op) {
            case EOpAdd:
                tempConstArray = new ConstantUnion[objectSize];
                {// support MSVC++6.0
                    for (int i = 0; i < objectSize; i++)
                        tempConstArray[i] = unionArray[i] + rightUnionArray[i];
                }
                break;
            case EOpSub:
                tempConstArray = new ConstantUnion[objectSize];
                {// support MSVC++6.0
                    for (int i = 0; i < objectSize; i++)
                        tempConstArray[i] = unionArray[i] - rightUnionArray[i];
                }
                break;

            case EOpMul:
            case EOpVectorTimesScalar:
            case EOpMatrixTimesScalar:
                tempConstArray = new ConstantUnion[objectSize];
                {// support MSVC++6.0
                    for (int i = 0; i < objectSize; i++)
                        tempConstArray[i] = unionArray[i] * rightUnionArray[i];
                }
                break;
            case EOpMatrixTimesMatrix:
                if (getType().getBasicType() != EbtFloat || node->getBasicType() != EbtFloat) {
                    infoSink.info.message(EPrefixInternalError, "Constant Folding cannot be done for matrix multiply", getLine());
                    return 0;
                }
                {// support MSVC++6.0
                    int size = getNominalSize();
                    tempConstArray = new ConstantUnion[size*size];
                    for (int row = 0; row < size; row++) {
                        for (int column = 0; column < size; column++) {
                            tempConstArray[size * column + row].setFConst(0.0f);
                            for (int i = 0; i < size; i++) {
                                tempConstArray[size * column + row].setFConst(tempConstArray[size * column + row].getFConst() + unionArray[i * size + row].getFConst() * (rightUnionArray[column * size + i].getFConst()));
                            }
                        }
                    }
                }
                break;
            case EOpDiv:
                tempConstArray = new ConstantUnion[objectSize];
                {// support MSVC++6.0
                    for (int i = 0; i < objectSize; i++) {
                        switch (getType().getBasicType()) {
            case EbtFloat:
                if (rightUnionArray[i] == 0.0f) {
                    infoSink.info.message(EPrefixWarning, "Divide by zero error during constant folding", getLine());
                    tempConstArray[i].setFConst(FLT_MAX);
                } else
                    tempConstArray[i].setFConst(unionArray[i].getFConst() / rightUnionArray[i].getFConst());
                break;

            case EbtInt:
                if (rightUnionArray[i] == 0) {
                    infoSink.info.message(EPrefixWarning, "Divide by zero error during constant folding", getLine());
                    tempConstArray[i].setIConst(INT_MAX);
                } else
                    tempConstArray[i].setIConst(unionArray[i].getIConst() / rightUnionArray[i].getIConst());
                break;
            default:
                infoSink.info.message(EPrefixInternalError, "Constant folding cannot be done for \"/\"", getLine());
                return 0;
                        }
                    }
                }
                break;

            case EOpMatrixTimesVector:
                if (node->getBasicType() != EbtFloat) {
                    infoSink.info.message(EPrefixInternalError, "Constant Folding cannot be done for matrix times vector", getLine());
                    return 0;
                }
                tempConstArray = new ConstantUnion[getNominalSize()];

                {// support MSVC++6.0
                    for (int size = getNominalSize(), i = 0; i < size; i++) {
                        tempConstArray[i].setFConst(0.0f);
                        for (int j = 0; j < size; j++) {
                            tempConstArray[i].setFConst(tempConstArray[i].getFConst() + ((unionArray[j*size + i].getFConst()) * rightUnionArray[j].getFConst()));
                        }
                    }
                }

                tempNode = new TIntermConstantUnion(tempConstArray, node->getType());
                tempNode->setLine(getLine());

                return tempNode;

            case EOpVectorTimesMatrix:
                if (getType().getBasicType() != EbtFloat) {
                    infoSink.info.message(EPrefixInternalError, "Constant Folding cannot be done for vector times matrix", getLine());
                    return 0;
                }

                tempConstArray = new ConstantUnion[getNominalSize()];
                {// support MSVC++6.0
                    for (int size = getNominalSize(), i = 0; i < size; i++) {
                        tempConstArray[i].setFConst(0.0f);
                        for (int j = 0; j < size; j++) {
                            tempConstArray[i].setFConst(tempConstArray[i].getFConst() + ((unionArray[j].getFConst()) * rightUnionArray[i*size + j].getFConst()));
                        }
                    }
                }
                break;

            case EOpLogicalAnd: // this code is written for possible future use, will not get executed currently
                tempConstArray = new ConstantUnion[objectSize];
                {// support MSVC++6.0
                    for (int i = 0; i < objectSize; i++)
                        tempConstArray[i] = unionArray[i] && rightUnionArray[i];
                }
                break;

            case EOpLogicalOr: // this code is written for possible future use, will not get executed currently
                tempConstArray = new ConstantUnion[objectSize];
                {// support MSVC++6.0
                    for (int i = 0; i < objectSize; i++)
                        tempConstArray[i] = unionArray[i] || rightUnionArray[i];
                }
                break;

            case EOpLogicalXor:
                tempConstArray = new ConstantUnion[objectSize];
                {// support MSVC++6.0
                    for (int i = 0; i < objectSize; i++)
                        switch (getType().getBasicType()) {
            case EbtBool: tempConstArray[i].setBConst((unionArray[i] == rightUnionArray[i]) ? false : true); break;
            default: assert(false && "Default missing");
                    }
                }
                break;

            case EOpLessThan:
                assert(objectSize == 1);
                tempConstArray = new ConstantUnion[1];
                tempConstArray->setBConst(*unionArray < *rightUnionArray);
                returnType = TType(EbtBool, EbpUndefined, EvqConst);
                break;
            case EOpGreaterThan:
                assert(objectSize == 1);
                tempConstArray = new ConstantUnion[1];
                tempConstArray->setBConst(*unionArray > *rightUnionArray);
                returnType = TType(EbtBool, EbpUndefined, EvqConst);
                break;
            case EOpLessThanEqual:
                {
                    assert(objectSize == 1);
                    ConstantUnion constant;
                    constant.setBConst(*unionArray > *rightUnionArray);
                    tempConstArray = new ConstantUnion[1];
                    tempConstArray->setBConst(!constant.getBConst());
                    returnType = TType(EbtBool, EbpUndefined, EvqConst);
                    break;
                }
            case EOpGreaterThanEqual:
                {
                    assert(objectSize == 1);
                    ConstantUnion constant;
                    constant.setBConst(*unionArray < *rightUnionArray);
                    tempConstArray = new ConstantUnion[1];
                    tempConstArray->setBConst(!constant.getBConst());
                    returnType = TType(EbtBool, EbpUndefined, EvqConst);
                    break;
                }

            case EOpEqual:
                if (getType().getBasicType() == EbtStruct) {
                    if (!CompareStructure(node->getType(), node->getUnionArrayPointer(), unionArray))
                        boolNodeFlag = true;
                } else {
                    for (int i = 0; i < objectSize; i++) {
                        if (unionArray[i] != rightUnionArray[i]) {
                            boolNodeFlag = true;
                            break;  // break out of for loop
                        }
                    }
                }

                tempConstArray = new ConstantUnion[1];
                if (!boolNodeFlag) {
                    tempConstArray->setBConst(true);
                }
                else {
                    tempConstArray->setBConst(false);
                }

                tempNode = new TIntermConstantUnion(tempConstArray, TType(EbtBool, EbpUndefined, EvqConst));
                tempNode->setLine(getLine());

                return tempNode;

            case EOpNotEqual:
                if (getType().getBasicType() == EbtStruct) {
                    if (CompareStructure(node->getType(), node->getUnionArrayPointer(), unionArray))
                        boolNodeFlag = true;
                } else {
                    for (int i = 0; i < objectSize; i++) {
                        if (unionArray[i] == rightUnionArray[i]) {
                            boolNodeFlag = true;
                            break;  // break out of for loop
                        }
                    }
                }

                tempConstArray = new ConstantUnion[1];
                if (!boolNodeFlag) {
                    tempConstArray->setBConst(true);
                }
                else {
                    tempConstArray->setBConst(false);
                }

                tempNode = new TIntermConstantUnion(tempConstArray, TType(EbtBool, EbpUndefined, EvqConst));
                tempNode->setLine(getLine());

                return tempNode;

            default:
                infoSink.info.message(EPrefixInternalError, "Invalid operator for constant folding", getLine());
                return 0;
        }
        tempNode = new TIntermConstantUnion(tempConstArray, returnType);
        tempNode->setLine(getLine());

        return tempNode;
    } else {
        //
        // Do unary operations
        //
        TIntermConstantUnion *newNode = 0;
        ConstantUnion* tempConstArray = new ConstantUnion[objectSize];
        for (int i = 0; i < objectSize; i++) {
            switch(op) {
                case EOpNegative:
                    switch (getType().getBasicType()) {
                        case EbtFloat: tempConstArray[i].setFConst(-unionArray[i].getFConst()); break;
                        case EbtInt:   tempConstArray[i].setIConst(-unionArray[i].getIConst()); break;
                        default:
                            infoSink.info.message(EPrefixInternalError, "Unary operation not folded into constant", getLine());
                            return 0;
                    }
                    break;
                case EOpLogicalNot: // this code is written for possible future use, will not get executed currently
                    switch (getType().getBasicType()) {
                        case EbtBool:  tempConstArray[i].setBConst(!unionArray[i].getBConst()); break;
                        default:
                            infoSink.info.message(EPrefixInternalError, "Unary operation not folded into constant", getLine());
                            return 0;
                    }
                    break;
                default:
                    return 0;
            }
        }
        newNode = new TIntermConstantUnion(tempConstArray, getType());
        newNode->setLine(getLine());
        return newNode;
    }
}
Esempio n. 3
0
//
// Establishes the type of the resultant operation, as well as
// makes the operator the correct one for the operands.
//
// Returns false if operator can't work on operands.
//
bool TIntermBinary::promote(TInfoSink& infoSink)
{
    // This function only handles scalars, vectors, and matrices.
    if (left->isArray() || right->isArray()) {
        infoSink.info.message(EPrefixInternalError, "Invalid operation for arrays", getLine());
        return false;
    }

    // GLSL ES 2.0 does not support implicit type casting.
    // So the basic type should always match.
    if (left->getBasicType() != right->getBasicType())
        return false;

    //
    // Base assumption:  just make the type the same as the left
    // operand.  Then only deviations from this need be coded.
    //
    setType(left->getType());

    // The result gets promoted to the highest precision.
    TPrecision higherPrecision = GetHigherPrecision(left->getPrecision(), right->getPrecision());
    getTypePointer()->setPrecision(higherPrecision);

    // Binary operations results in temporary variables unless both
    // operands are const.
    if (left->getQualifier() != EvqConst || right->getQualifier() != EvqConst) {
        getTypePointer()->setQualifier(EvqTemporary);
    }

    int size = std::max(left->getNominalSize(), right->getNominalSize());

    //
    // All scalars. Code after this test assumes this case is removed!
    //
    if (size == 1) {
        switch (op) {
            //
            // Promote to conditional
            //
            case EOpEqual:
            case EOpNotEqual:
            case EOpLessThan:
            case EOpGreaterThan:
            case EOpLessThanEqual:
            case EOpGreaterThanEqual:
                setType(TType(EbtBool, EbpUndefined));
                break;

            //
            // And and Or operate on conditionals
            //
            case EOpLogicalAnd:
            case EOpLogicalOr:
                // Both operands must be of type bool.
                if (left->getBasicType() != EbtBool || right->getBasicType() != EbtBool)
                    return false;
                setType(TType(EbtBool, EbpUndefined));
                break;

            default:
                break;
        }
        return true;
    }

    // If we reach here, at least one of the operands is vector or matrix.
    // The other operand could be a scalar, vector, or matrix.
    // Are the sizes compatible?
    //
    if (left->getNominalSize() != right->getNominalSize()) {
        // If the nominal size of operands do not match:
        // One of them must be scalar.
        if (left->getNominalSize() != 1 && right->getNominalSize() != 1)
            return false;
        // Operator cannot be of type pure assignment.
        if (op == EOpAssign || op == EOpInitialize)
            return false;
    }

    //
    // Can these two operands be combined?
    //
    TBasicType basicType = left->getBasicType();
    switch (op) {
        case EOpMul:
            if (!left->isMatrix() && right->isMatrix()) {
                if (left->isVector())
                    op = EOpVectorTimesMatrix;
                else {
                    op = EOpMatrixTimesScalar;
                    setType(TType(basicType, higherPrecision, EvqTemporary, size, true));
                }
            } else if (left->isMatrix() && !right->isMatrix()) {
                if (right->isVector()) {
                    op = EOpMatrixTimesVector;
                    setType(TType(basicType, higherPrecision, EvqTemporary, size, false));
                } else {
                    op = EOpMatrixTimesScalar;
                }
            } else if (left->isMatrix() && right->isMatrix()) {
                op = EOpMatrixTimesMatrix;
            } else if (!left->isMatrix() && !right->isMatrix()) {
                if (left->isVector() && right->isVector()) {
                    // leave as component product
                } else if (left->isVector() || right->isVector()) {
                    op = EOpVectorTimesScalar;
                    setType(TType(basicType, higherPrecision, EvqTemporary, size, false));
                }
            } else {
                infoSink.info.message(EPrefixInternalError, "Missing elses", getLine());
                return false;
            }
            break;
        case EOpMulAssign:
            if (!left->isMatrix() && right->isMatrix()) {
                if (left->isVector())
                    op = EOpVectorTimesMatrixAssign;
                else {
                    return false;
                }
            } else if (left->isMatrix() && !right->isMatrix()) {
                if (right->isVector()) {
                    return false;
                } else {
                    op = EOpMatrixTimesScalarAssign;
                }
            } else if (left->isMatrix() && right->isMatrix()) {
                op = EOpMatrixTimesMatrixAssign;
            } else if (!left->isMatrix() && !right->isMatrix()) {
                if (left->isVector() && right->isVector()) {
                    // leave as component product
                } else if (left->isVector() || right->isVector()) {
                    if (! left->isVector())
                        return false;
                    op = EOpVectorTimesScalarAssign;
                    setType(TType(basicType, higherPrecision, EvqTemporary, size, false));
                }
            } else {
                infoSink.info.message(EPrefixInternalError, "Missing elses", getLine());
                return false;
            }
            break;

        case EOpAssign:
        case EOpInitialize:
        case EOpAdd:
        case EOpSub:
        case EOpDiv:
        case EOpAddAssign:
        case EOpSubAssign:
        case EOpDivAssign:
            if ((left->isMatrix() && right->isVector()) ||
                (left->isVector() && right->isMatrix()))
                return false;
            setType(TType(basicType, higherPrecision, EvqTemporary, size, left->isMatrix() || right->isMatrix()));
            break;

        case EOpEqual:
        case EOpNotEqual:
        case EOpLessThan:
        case EOpGreaterThan:
        case EOpLessThanEqual:
        case EOpGreaterThanEqual:
            if ((left->isMatrix() && right->isVector()) ||
                (left->isVector() && right->isMatrix()))
                return false;
            setType(TType(EbtBool, EbpUndefined));
            break;

        default:
            return false;
    }
    
    return true;
}
Esempio n. 4
0
static void load_one_suppressions_file ( Char* filename )
{
#  define N_BUF 200
   Int  fd;
   Bool eof;
   Char buf[N_BUF+1];
   fd = VG_(open_read)( filename );
   if (fd == -1) {
      VG_(message)(Vg_UserMsg, 
                   "FATAL: can't open suppressions file `%s'", 
                   filename );
      VG_(exit)(1);
   }

   while (True) {
      Suppression* supp;
      supp = VG_(malloc)(VG_AR_PRIVATE, sizeof(Suppression));
      supp->count = 0;
      supp->param = supp->caller0 = supp->caller1 
                  = supp->caller2 = supp->caller3 = NULL;

      eof = getLine ( fd, buf, N_BUF );
      if (eof) break;

      if (!STREQ(buf, "{")) goto syntax_error;
      
      eof = getLine ( fd, buf, N_BUF );
      if (eof || STREQ(buf, "}")) goto syntax_error;
      supp->sname = copyStr(buf);

      eof = getLine ( fd, buf, N_BUF );
      if (eof) goto syntax_error;
      else if (STREQ(buf, "Param"))  supp->skind = Param;
      else if (STREQ(buf, "Value0")) supp->skind = Value0; /* backwards compat */
      else if (STREQ(buf, "Cond"))   supp->skind = Value0;
      else if (STREQ(buf, "Value1")) supp->skind = Value1;
      else if (STREQ(buf, "Value2")) supp->skind = Value2;
      else if (STREQ(buf, "Value4")) supp->skind = Value4;
      else if (STREQ(buf, "Value8")) supp->skind = Value8;
      else if (STREQ(buf, "Addr1"))  supp->skind = Addr1;
      else if (STREQ(buf, "Addr2"))  supp->skind = Addr2;
      else if (STREQ(buf, "Addr4"))  supp->skind = Addr4;
      else if (STREQ(buf, "Addr8"))  supp->skind = Addr8;
      else if (STREQ(buf, "Free"))   supp->skind = FreeS;
      else goto syntax_error;

      if (supp->skind == Param) {
         eof = getLine ( fd, buf, N_BUF );
         if (eof) goto syntax_error;
         supp->param = copyStr(buf);
      }

      eof = getLine ( fd, buf, N_BUF );
      if (eof) goto syntax_error;
      supp->caller0 = copyStr(buf);
      if (!setLocationTy(&(supp->caller0), &(supp->caller0_ty)))
         goto syntax_error;

      eof = getLine ( fd, buf, N_BUF );
      if (eof) goto syntax_error;
      if (!STREQ(buf, "}")) {
         supp->caller1 = copyStr(buf);
         if (!setLocationTy(&(supp->caller1), &(supp->caller1_ty)))
            goto syntax_error;
      
         eof = getLine ( fd, buf, N_BUF );
         if (eof) goto syntax_error;
         if (!STREQ(buf, "}")) {
            supp->caller2 = copyStr(buf);
            if (!setLocationTy(&(supp->caller2), &(supp->caller2_ty)))
               goto syntax_error;

            eof = getLine ( fd, buf, N_BUF );
            if (eof) goto syntax_error;
            if (!STREQ(buf, "}")) {
               supp->caller3 = copyStr(buf);
              if (!setLocationTy(&(supp->caller3), &(supp->caller3_ty)))
                 goto syntax_error;

               eof = getLine ( fd, buf, N_BUF );
               if (eof || !STREQ(buf, "}")) goto syntax_error;
	    }
         }
      }

      supp->next = vg_suppressions;
      vg_suppressions = supp;
   }

   VG_(close)(fd);
   return;

  syntax_error:
   if (eof) {
      VG_(message)(Vg_UserMsg, 
                   "FATAL: in suppressions file `%s': unexpected EOF", 
                   filename );
   } else {
      VG_(message)(Vg_UserMsg, 
                   "FATAL: in suppressions file `%s': syntax error on: %s", 
                   filename, buf );
   }
   VG_(close)(fd);
   VG_(message)(Vg_UserMsg, "exiting now.");
    VG_(exit)(1);

#  undef N_BUF   
}
/**
 * This is called on every game loop.
 */
void Session::step() {
   //printf("in session step\n");
   glfwSwapBuffers(window->glfw_window);
   glfwPollEvents();
   // Clear the screen
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
   // Use "frag.glsl" and "vert.glsl"
   //shaders[SHADER_COOK]->bind();
   shaders[SHADER_DEFAULT]->bind();
   // Send position info to the attribute "aPos"
   GLSL::enableVertexAttribArray(h_aPos);
   // Send normal info to the attribute "aNor"
   GLSL::enableVertexAttribArray(h_aNor);

   // Step other components
   window->step();
   world->step(window);
   //camera->step(window, game_state);
   
   // Disable and unbind
   GLSL::disableVertexAttribArray(h_aPos);
   glBindBuffer(GL_ARRAY_BUFFER, 0);
   glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
   //shaders[SHADER_COOK]->unbind();
   
   //shaders[SHADER_DEFAULT]->bind();
   if (game_state == MINIGAME_STATE) {
      minigame->step(window);
   }

   if (minigame->getGameOver()) {
      //leaveMinigame();
   }
   shaders[SHADER_DEFAULT]->unbind();
   
   if (game_state == WORLD_STATE) {
      world->particleStep(shaders[SHADER_BILLBOARD], window);
   }
   
   char txt[30];
   sprintf(txt, "Matsuriyo!");
   if (game_state == WORLD_STATE || game_state == MINIGAME_STATE) {
      fontEngine->useFont("goodDog", 48);
      fontEngine->display(glm::vec4(0.99, 0.56, 0.55, 1.0), txt, -1.0, 0.9);
   
     if (game_state != MINIGAME_STATE) {
         if (window->time - startTime <= 25.0) {
            char pun[100];
            sprintf(pun, "%s", getLine().c_str());
            fontEngine->display(glm::vec4(0.99, 0.56, 0.55, 1.0), pun, xInc, 0.9);
            
            xInc -= 0.015f;
         }
         else {
            startTime = window->time;
            punLine = rand() % MAX_PUNS + 1;
            xInc = 1.0f;
         }
      }

      char pts[15];
      sprintf(pts, "Points: %d", global_points);
      fontEngine->useFont("goodDog", 36);   
      fontEngine->display(glm::vec4(0.99, 0.56, 0.55, 1.0), pts, -.98, 0.9-(fontEngine->getTextHeight(txt)*1.1));      
   } else if (game_state == TITLE_STATE) {
      fontEngine->useFont("goodDog", 100);
      fontEngine->display(glm::vec4(1.0, 0.22, 0.22, 1.0), txt, -0.75, -0.1);

      char subtext1[30];
      sprintf(subtext1, "Use WASD to move");
      fontEngine->useFont("goodDog", 50);      
      fontEngine->display(glm::vec4(1.0, 0.22, 0.22, 1.0), subtext1, -0.75, -0.25);
   
      char subtext2[30];
      sprintf(subtext2, "Press ENTER to play");
      fontEngine->display(glm::vec4(1.0, 0.22, 0.22, 1.0), subtext2, -0.75, -0.25-fontEngine->getTextHeight(subtext1)*1.3);
   }
   /*
   char txt[30];
   sprintf(txt, "Matsuriyo!");
   fontEngine->useFont("goodDog", 48);
   fontEngine->display(glm::vec4(0.99, 0.56, 0.55, 1.0), txt, -1.0, 0.9);
*/

}
Esempio n. 6
0
main() {
  /* if malloc() and free() are to be used, the following procedure could be used 
   *  set the maximum line of the input to a small digit, like 0
   *  get a line from the input till meets the end of the file
   *  if the line length is longer than the maximum line
   *    record the current line, and modify the maximum number
   *  print the maximum line
   */
  
  /* another way to address the problem */
  /* the examp give the getLine method and copy method */
  /* and the requirement is that we should modify the main routine the accomplish the task */
  /* the end of a line is indicated by a newline symbol */
  /* so the thing to do is to after read a character sequence using getLine() */
  /* is to check the last symbol of the sequence is newline or not */

  int hasMore;
  int maxLen;
  int tempLen;
  int lineLen;

  char line[MAXLINE];
  char longest[MAXLINE];

  /* use a marker to tell whether the current line has more to offer */
  /* set the marker to true when the line has more characters, set it to false otherwise */
  /* the initial state of the marker should be false */
  maxLen = 0;
  tempLen = 0;
  lineLen = 0;
  hasMore = FALSE;
  /* while the cursor doesn't reach the end of the file */
  /*   get a new line sequence */
  /*   if the last symbol of the sequence is not a newline character */
  /*     if the marker is true */
  /*       accumulate the length of the current line */
  /*     if the marker is false */
  /*       copy the current line */
  /*       accumulate the length of the current line */
  /*     if the length of the line is larger than the largest length */
  /*       copy the line into the largest one  */
  /*     set the marker to true */
  /*   if the last symbol of the sequence is a newline character */
  /*     if the marker is true, means this is the last sequence of a line */
  /*       accumulate the length of the line */
  /*     if the marker is false, means this is a line within the maximum capacity of the getLine function */
  /*       record the length of the current line */
  /*     compare the length of the current line(whether full or not full) to the largest length */
  /*     if the length of the line is larger */
  /*       modify the largest line length with the length of the current line */
  /*       if the marker is false */
  /*         copy the sequence into the largest line string */
  /*     set the marker to false */
  /*     set the temporary line length to zero */

  while ((tempLen = getLine(line, MAXLINE)) > 0) {
    if (line[tempLen - 1] != '\n') {
      if (hasMore == TRUE)
	lineLen += tempLen;
      else {
	lineLen = tempLen;
      }
      if (lineLen > maxLen)
	copy(longest, line);
      hasMore = TRUE;
    }
    else {
      if (hasMore == TRUE) 
	lineLen += tempLen;
      else
	lineLen = tempLen;
      if ( lineLen > maxLen) {
	maxLen = lineLen;
	if (hasMore == FALSE)
	  copy(longest, line);
      }
      hasMore == FALSE;
      lineLen = 0;
    }
  }

  if (maxLen > 0) {
    printf("The longest line's length is %d.\n", maxLen);
    printf("%s\n", longest);
  }
  return 0;
}
Esempio n. 7
0
bool hsTokenStream::hasNext() {
    if (fLineTokens.empty())
        getLine();
    return !(fLineTokens.empty());
}
Esempio n. 8
0
void Screen::drawScreen(GameOfLife& game,int s,bool p){
    Surface *swt = surfaces;
    SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 237,191, 130 ) );
    SDL_Rect clip;
    clip.x = 0;
    clip.y = 0;
    clip.w = height;
    clip.h = width;
    SDL_FillRect( screen, &clip, SDL_MapRGB( screen->format, 255,255, 255 ) );


    int i = 0;
    SDL_Rect *vert =  getLine(1,0,0);
    SDL_Rect *hor =  getLine(0,0,0);
        int ax,ay;
    for (ax=0;ax<=(height/BG->w);ax++){
       for (ay=0;ay<=(width/BG->h);ay++)
        apply_surface(ax*BG->w,ay*BG->h,BG);
    }



    apply_surface(0,width,MBG);
    apply_surface(175,width+11,txtp);
    apply_surface(310,width+11,txts);
    apply_surface(410,width+11,txte);
    apply_surface(520,width+11,txtg);
    apply_surface(495,width+8,und);
    apply_surface(10,width+4,ln1);
    apply_surface(10,width+18,ln2);
    apply_surface(460,width+8,refresh);

    apply_surface(580,width+8,gen);
    if (!p)
        apply_surface(250,width+8,play);
    else
        apply_surface(250,width+8,pause);
    switch(s){
    case 1:
        apply_surface(350,width+8,f);
        break;
    case 2:
        apply_surface(350,width+8,ff);
        break;
    case 3:
        apply_surface(350,width+8,fff);
        break;

    }

    for(int i = 0; i < row; i++) {
        for(int j = 0; j < col; j++) {
            if (game.isCellAlive(j,i)){
                int cola[3] = {255,255,255};
                struct rule *r = game.rules;
                while (r){
                    if (game.getCell(j,i)->getType() == r->id){
                        cola[0] = r->color[0];
                        cola[1] = r->color[1];
                        cola[2] = r->color[2];
                        break;
                    }

                    r = r->next;
                }
                SDL_Rect square;
                square.x = ((double)j)*((double)height/(double)col) -.5 ;
                square.y = ((double)i)*((double)width/(double)row) -.5;
                square.h = ((double)width/(double)col) + 1;
                square.w = ((double)height/(double)row) + 1 ;
                SDL_FillRect( screen, &square,  SDL_MapRGB( screen->format, cola[0],cola[1], cola[2] ) );
                //apply_surface(,,game.getCell(j,i)->s);
            }
            //tela->setCell(i,j,);
        }
    }

    int x=0;
    for (x=0;x<=(col);x++){
        vert->x = ((double)height/(double)col)*(double)x;
        if (game.grid)
        SDL_FillRect( screen, vert, SDL_MapRGB( screen->format, 237,191, 130 ) );
        //apply_surface(,0,gv);
    }
    int y=0;
    for (y=0;y<=(row);y++){
        hor->y = ((double)width/(double)row)*(double)y;

        //
        if (game.grid)
        SDL_FillRect( screen, hor, SDL_MapRGB( screen->format, 237,191, 130 ) );
        //apply_surface(0,,gh);
    }
    vert->x = ((double)height/(double)col)*(double)col;
    vert->w = height;
    hor->y = ((double)width/(double)row)*((double)row);
    hor->h = width;
    //SDL_FillRect( screen, vert, SDL_MapRGB( screen->format,237,191, 130 ) );
    //SDL_FillRect( screen, hor, SDL_MapRGB( screen->format, 237,191, 130 ) );
    free(hor);
    free(vert);
    SDL_Flip( screen );

    SDL_Delay(10);
}
//===================>>> vedTextEditor::SaveFile <<<====================
  int vedTextEditor::SaveFile(char* name)
  {
    char buff[maxBuff+2];

//    char* prefix = "Saved ";

    ofstream ofs(name);

    if (!ofs)
      {
	StatusMessage("Can't save file");
	return 0;
      }

    long lx;
    long lim = GetLines();

    for (lx = 1 ; lx <= 12 && lx <= lim ; ++lx)
      {
	getLine(buff,maxBuff,lx);

    	if (GetFileType() == CPP ||		// check date: if C++
	    GetFileType() == Java ||		// if a Java file
	    GetFileType() == Fortran ||		// if a Perl file
	    GetFileType() == Perl ||		// if a Perl file
	    GetFileType() == HTML)		// if HTML
	  {
	    char* cp = strstr(buff,"date:");
	    if (cp != 0)
	      {
		if (GetFileType() != Fortran || buff[0] == 'c' || buff[0] == 'C')
		  {
		    char time[20];
		    char date[20];
		    vGetLocalDate(date);
		    vGetLocalTime(time);
		    *(cp+5) = 0;		// 5 corresponds to "date:"
		    strcat(buff," ");
		    strcat(buff,date);
		    strcat(buff," ");
		    strcat(buff,time);
		  }
	      }
	  }
	ofs << buff << "\n";
      }

    for ( ; lx <= lim ; ++lx)
      {
	getLine(buff,maxBuff,lx);
	ofs << buff << "\n";
      }

    ofs.close();

//    removed in 1.07 - fatal interaction between this
//	message and autosave while user is entering text.
//    strcpy(buff,prefix);
//    int ix;
//    for (ix = strlen(prefix) ; ix < 40 && *name != 0 ; ++ix)
//	buff[ix] = *name++;
//    buff[ix] = 0;
//    StatusMessage(buff);

    state.changes = 0;
    return 1;
  }
Esempio n. 10
0
void MULTIatmos(Atmosphere *atmos, Geometry *geometry)
{
  const char routineName[] = "MULTIatmos";
  register int k, n, mu;

  char    scaleStr[20], inputLine[MAX_LINE_SIZE], *filename;
  bool_t  exit_on_EOF, enhanced_atmos_ID = FALSE;
  int     Nread, Ndep, Nrequired, checkPoint;
  double *dscale, turbpress, turbelecpress, nbaryon, meanweight;
  struct  stat statBuffer;

  getCPU(2, TIME_START, NULL);

  /* --- Get abundances of background elements --        ------------ */
 
  readAbundance(atmos);

  /* --- Open the input file for model atmosphere in MULTI format - - */

  if ((atmos->fp_atmos = fopen(input.atmos_input, "r")) == NULL) {
    sprintf(messageStr, "Unable to open inputfile %s", input.atmos_input);
    Error(ERROR_LEVEL_2, routineName, messageStr);
  } else {
    sprintf(messageStr, "\n -- reading input file: %s\n\n",
	    input.atmos_input);
    Error(MESSAGE, NULL, messageStr);
  }

  atmos->NHydr = N_HYDROGEN_MULTI;

  /* --- Boundary condition at TOP of atmosphere --      ------------ */

  if (strcmp(input.Itop, "none"))
    geometry->vboundary[TOP] = IRRADIATED;
  else 
    geometry->vboundary[TOP] = ZERO;

  /* --- Boundary condition at BOTTOM of atmosphere --   ------------ */

  geometry->vboundary[BOTTOM] = THERMALIZED;

  /* --- Read atmos ID, scale type, gravity, and number of depth
         points --                                       ------------ */
 
  getLine(atmos->fp_atmos, MULTI_COMMENT_CHAR, inputLine, exit_on_EOF=TRUE);
  if (enhanced_atmos_ID) {

    /* --- Construct atmosID from filename and last modification date */

    stat(input.atmos_input, &statBuffer);
    if ((filename = strrchr(input.atmos_input, '/')) != NULL)
      filename++;
    else
      filename = input.atmos_input;
    sprintf(atmos->ID, "%s (%.24s)", filename,
	    asctime(localtime(&statBuffer.st_mtime)));
    Nread = 1;
  } else
    Nread = sscanf(inputLine, "%s", atmos->ID);

  getLine(atmos->fp_atmos, MULTI_COMMENT_CHAR, inputLine, exit_on_EOF=TRUE);
  Nread += sscanf(inputLine, "%20s", scaleStr);
  getLine(atmos->fp_atmos, MULTI_COMMENT_CHAR, inputLine, exit_on_EOF=TRUE);
  Nread += sscanf(inputLine, "%lf", &atmos->gravity);
  getLine(atmos->fp_atmos, MULTI_COMMENT_CHAR, inputLine, exit_on_EOF=TRUE);
  Nread += sscanf(inputLine, "%d", &geometry->Ndep);
  checkNread(Nread, Nrequired=4, routineName, checkPoint=1);

  /* --- Keep duplicates of some of the geometrical quantities in
         Atmos structure --                            -------------- */

  atmos->Ndim = 1;
  atmos->N = (int *) malloc(atmos->Ndim * sizeof(int));
  atmos->Nspace = Ndep = geometry->Ndep;
  atmos->N[0] = Ndep;

  atmos->gravity = POW10(atmos->gravity) * CM_TO_M;

  /* --- Allocate space for arrays that define structure -- --------- */

  geometry->tau_ref = (double *) malloc(Ndep * sizeof(double));
  geometry->cmass   = (double *) malloc(Ndep * sizeof(double));
  geometry->height  = (double *) malloc(Ndep * sizeof(double));
  atmos->T      = (double *) malloc(Ndep * sizeof(double));
  atmos->ne     = (double *) malloc(Ndep * sizeof(double));
  atmos->vturb  = (double *) malloc(Ndep * sizeof(double));
  geometry->vel = (double *) malloc(Ndep * sizeof(double));

  dscale = (double *) malloc(Ndep * sizeof(double));
  for (k = 0;  k < Ndep;  k++) {
    getLine(atmos->fp_atmos, MULTI_COMMENT_CHAR, inputLine, exit_on_EOF=TRUE);
    Nread = sscanf(inputLine, "%lf %lf %lf %lf %lf",
		   &dscale[k], &atmos->T[k], &atmos->ne[k],
		   &geometry->vel[k], &atmos->vturb[k]);
    checkNread(Nread, Nrequired=5, routineName, checkPoint=2);
  }

  switch(toupper(scaleStr[0])) {
  case 'M':
    geometry->scale = COLUMN_MASS;
    for (k = 0;  k < Ndep;  k++)
      geometry->cmass[k] = POW10(dscale[k]) * (G_TO_KG / SQ(CM_TO_M));
    break;
  case 'T':
    geometry->scale = TAU500;
    for (k = 0;  k < Ndep;  k++) geometry->tau_ref[k] = POW10(dscale[k]);
    break;
  case 'H':
    geometry->scale = GEOMETRIC;
    for (k = 0;  k < Ndep;  k++) geometry->height[k] = dscale[k] * KM_TO_M;
    break;
  default:
    sprintf(messageStr, "Unknown depth scale string in file %s: %s",
	    input.atmos_input, scaleStr);
    Error(ERROR_LEVEL_2, routineName, messageStr);
  }
  free(dscale);

  for (k = 0;  k < Ndep;  k++) {
    geometry->vel[k] *= KM_TO_M;
    atmos->vturb[k]  *= KM_TO_M;
    atmos->ne[k]     /= CUBE(CM_TO_M);
  }
  atmos->moving = FALSE;
  for (k = 0;  k < Ndep;  k++) {
    if (fabs(geometry->vel[k]) >= atmos->vmacro_tresh) {
      atmos->moving = TRUE;
      break;
    }
  }
  /* --- Get angle-quadrature and copy geometry independent quantity
         wmu to atmos structure. --                    -------------- */

  getAngleQuad(geometry);
  atmos->wmu = geometry->wmu;

  /* --- Magnetic field is read here. --               -------------- */

  atmos->Stokes = readB(atmos);

  /* --- Read Hydrogen populations if present --       -------------- */

  atmos->nH = matrix_double(atmos->NHydr, Ndep);
  for (k = 0;  k < Ndep;  k++) {
    if (getLine(atmos->fp_atmos, MULTI_COMMENT_CHAR, inputLine,
		exit_on_EOF=FALSE) == EOF) break;
    Nread = sscanf(inputLine, "%lf %lf %lf %lf %lf %lf",
		   &atmos->nH[0][k], &atmos->nH[1][k], &atmos->nH[2][k],
		   &atmos->nH[3][k], &atmos->nH[4][k], &atmos->nH[5][k]);
    checkNread(Nread, Nrequired=6, routineName, checkPoint=3);
  }
  if (k > 0  &&  k < Ndep) {
    sprintf(messageStr,
	    "Reached end of input file %s before all data was read",
	    input.atmos_input);
    Error(ERROR_LEVEL_2, routineName, messageStr);
  } else if (k == 0) {

    /* --- No hydrogen populations supplied: use LTE populations
           like MULTI does --                          -------------- */

    if (geometry->scale != COLUMN_MASS) {
      sprintf(messageStr,
	      "Height scale should be COLUMNMASS when nH not supplied: "
	      "File %s", input.atmos_input);
      Error(ERROR_LEVEL_2, routineName, messageStr);
    }
    atmos->nHtot = (double *) calloc(Ndep, sizeof(double));

    atmos->H_LTE = TRUE;
    meanweight = atmos->avgMolWght * AMU;
    for (k = 0;  k < Ndep;  k++) {
      turbpress     = 0.5 * meanweight * SQ(atmos->vturb[k]);
      turbelecpress = 0.5 * M_ELECTRON * SQ(atmos->vturb[k]);

      nbaryon =
	(atmos->gravity * geometry->cmass[k] -
	 atmos->ne[k] *(KBOLTZMANN * atmos->T[k] + turbelecpress));

      atmos->nHtot[k] =	nbaryon / 
	(atmos->totalAbund * (KBOLTZMANN * atmos->T[k] + turbpress));
    }
  } else if (k == Ndep) {
    atmos->nHtot = (double *) calloc(Ndep, sizeof(double));
    for (n = 0;  n < atmos->NHydr;  n++) {
      for (k = 0;  k < Ndep;  k++) {
	atmos->nH[n][k] /= CUBE(CM_TO_M);
	atmos->nHtot[k] += atmos->nH[n][k];
      }
    }
  }

  getCPU(2, TIME_POLL, "Read Atmosphere");
}
Esempio n. 11
0
/** @cond doxygenLibsbmlInternal */
void SpeciesGlyph::readAttributes (const XMLAttributes& attributes,
                                   const ExpectedAttributes& expectedAttributes)
{
  const unsigned int sbmlLevel   = getLevel  ();
  const unsigned int sbmlVersion = getVersion();

  unsigned int numErrs;

  /* look to see whether an unknown attribute error was logged
  * during the read of the listOfSpeciesGlyphs - which will have
  * happened immediately prior to this read
  */

  bool loSubGlyphs = false;
  if (getParentSBMLObject() != NULL
    && getParentSBMLObject()->getElementName() == "listOfSubGlyphs")
  {
    loSubGlyphs = true;
  }

  if (getErrorLog() != NULL &&
    static_cast<ListOfSpeciesGlyphs*>(getParentSBMLObject())->size() < 2)
  {
    numErrs = getErrorLog()->getNumErrors();
    for (int n = (int)numErrs-1; n >= 0; n--)
    {
      if (getErrorLog()->getError((unsigned int)n)->getErrorId() == UnknownPackageAttribute)
      {
        const std::string details =
          getErrorLog()->getError((unsigned int)n)->getMessage();
        getErrorLog()->remove(UnknownPackageAttribute);
        if (loSubGlyphs == true)
        {
          getErrorLog()->logPackageError("layout", 
            LayoutLOSubGlyphAllowedAttribs,
            getPackageVersion(), sbmlLevel, sbmlVersion, details, getLine(), getColumn());
        }
        else
        {
          getErrorLog()->logPackageError("layout", 
            LayoutLOSpeciesGlyphAllowedAttributes,
            getPackageVersion(), sbmlLevel, sbmlVersion, details, getLine(), getColumn());
        }
      }
      else if (getErrorLog()->getError((unsigned int)n)->getErrorId() == UnknownCoreAttribute)
      {
        const std::string details =
          getErrorLog()->getError((unsigned int)n)->getMessage();
        getErrorLog()->remove(UnknownCoreAttribute);
        if (loSubGlyphs == true)
        {
          getErrorLog()->logPackageError("layout", 
            LayoutLOSubGlyphAllowedAttribs,
            getPackageVersion(), sbmlLevel, sbmlVersion, details, getLine(), getColumn());
        }
        else
        {
          getErrorLog()->logPackageError("layout", 
            LayoutLOSpeciesGlyphAllowedAttributes,
            getPackageVersion(), sbmlLevel, sbmlVersion, details, getLine(), getColumn());
        }
      }
    }
  }

  GraphicalObject::readAttributes(attributes, expectedAttributes);

  // look to see whether an unknown attribute error was logged
  if (getErrorLog() != NULL)
  {
    numErrs = getErrorLog()->getNumErrors();
    for (int n = (int)numErrs-1; n >= 0; n--)
    {
      if (getErrorLog()->getError((unsigned int)n)->getErrorId() == UnknownPackageAttribute)
      {
        const std::string details =
          getErrorLog()->getError((unsigned int)n)->getMessage();
        getErrorLog()->remove(UnknownPackageAttribute);
        getErrorLog()->logPackageError("layout", LayoutSGAllowedAttributes,
          getPackageVersion(), sbmlLevel, sbmlVersion, details, getLine(), getColumn());
      }
      else if (getErrorLog()->getError((unsigned int)n)->getErrorId() == UnknownCoreAttribute)
      {
        const std::string details =
          getErrorLog()->getError((unsigned int)n)->getMessage();
        getErrorLog()->remove(UnknownCoreAttribute);
        getErrorLog()->logPackageError("layout", LayoutSGAllowedCoreAttributes,
          getPackageVersion(), sbmlLevel, sbmlVersion, details, getLine(), getColumn());
      }
    }
  }

  bool assigned = false;

  //
  // species SIdRef   ( use = "optional" )
  //
  assigned = attributes.readInto("species", mSpecies);

  if (assigned == true && getErrorLog() != NULL)
  {
    // check string is not empty and correct syntax

    if (mSpecies.empty() == true)
    {
      logEmptyString(mSpecies, getLevel(), getVersion(), "<SpeciesGlyph>");
    }
    else if (SyntaxChecker::isValidSBMLSId(mSpecies) == false)
    {
      getErrorLog()->logPackageError("layout", LayoutSGSpeciesSyntax,
        getPackageVersion(), sbmlLevel, sbmlVersion, "The species on the <" 
        + getElementName() + "> is '" + mSpecies + "', which does not conform to the syntax.", getLine(), getColumn());
    }
  }

}
Esempio n. 12
0
void SchSpecialDivide::call(SchemeMachine & vm, int N, int step) {
    SchObjectRef ** refs = vm.popResult(N);
    int sum_i = 0, dx_i;
    double sum_f = 0, dx_f;
    bool is_int = true, curr_int;

    if(N < 1) {
        throw Special_DivideExpectedAtLeastOneArgumentError(getLine());
    }
    // first elem
    switch ((*refs[N-1])->getType()) {
    case INTEGER :
        dx_i = static_cast<SchInteger *>(&**refs[N-1])->getN();
        curr_int = true;
        break;
    case FLOAT :
        dx_f = static_cast<SchFloat *>(&**refs[N-1])->getF();
        if(is_int == true) {
            sum_f = (double)sum_i;
        }
        is_int = false;
        curr_int = false;
        break;
    default :
        throw Special_DivideNumericExpectedError((*refs[N-1])->getLine());
        break;
    }
    if(is_int) {
        sum_i = dx_i;
    } else {
        sum_f = dx_f;
    }


    for(int i = N-2; i >= 0; --i) {
        switch ((*refs[i])->getType()) {
        case INTEGER :
            dx_i = static_cast<SchInteger *>(&**refs[i])->getN();
            curr_int = true;
            break;
        case FLOAT :
            dx_f = static_cast<SchFloat *>(&**refs[i])->getF();
            if(is_int == true) {
                sum_f = (double)sum_i;
            }
            is_int = false;
            curr_int = false;
            break;
        default :
            throw Special_DivideNumericExpectedError((*refs[i])->getLine());
            break;
        }

        if(is_int) {
            if(dx_i == 0) {
                throw Special_DivideByZeroError((*refs[i])->getLine());
            }
            sum_i /= dx_i;
        } else {
            if(curr_int) {
                sum_f /= double(dx_i);
            } else {
                sum_f /= dx_f;
            }
        }
    }

    if(N == 1) {
        if(is_int) {
            if(sum_i == 0) {
                throw Special_DivideByZeroError((*refs[N-1])->getLine());
            }
            sum_i = 1 / sum_i;
        } else {
            if(sum_f == 0) {
                throw Special_DivideByZeroError((*refs[N-1])->getLine());
            }
            sum_f = 1 / sum_f;
        }
    }

    if(is_int) {
        vm.pushResult(SchObjectRef(new SchInteger(getLine(), sum_i)));
    } else {
        vm.pushResult(SchObjectRef(new SchFloat(getLine(), sum_f)));
    }
}
Esempio n. 13
0
void SchSpecialDontExec::execute(SchemeMachine & vm, int N, int step) {
    throw NotAnExecutableError(getLine());
}
Esempio n. 14
0
void SchSpecialDontCall::call(SchemeMachine & vm, int N, int step) {
    throw NotAFunctionCalledError(getLine());
}
Esempio n. 15
0
void Shell::process(void const *argument)
{
    char ch;
    static char line[SHELL_MAX_LINE_LEN];
    bool ret;
    char *cmd, *argPos, *tok;
    int i;
    static char *args[SHELL_MAX_ARGUMENTS + 1];
    const Command *exec;
    int result;

    TraceLine();
    Trace("welcome to gBike");
    TraceLine();

    m_pthread = (Thread*)argument;
    memset(line, 0, SHELL_MAX_LINE_LEN);
    while(m_exit == false)
    {
        osEvent evt = m_serialQ.get();
        if (evt.status != osEventMessage)
        {
            Trace("queue->get() return %02x status", evt.status);
            continue;
        }
        ch = (char)evt.value.v;

        ret = getLine(ch, line, SHELL_MAX_LINE_LEN);
        if (false == ret)
            continue;

        cmd = _strtok(line, " \t", &tok);
        i = 0;
        while((argPos = _strtok(NULL," \t", &tok)) != NULL)
        {
            if (i >= SHELL_MAX_ARGUMENTS)
            {
                Trace("too many arguments!");
                cmd = NULL;
                break;
            }
            args[i++] = argPos;
        }
        args[i] = NULL;
        if (cmd == NULL)
        {
            goto loop;
        }
        exec = findCommand(cmd);
        if (exec)
        {
            exec->function(i, args, &result);
        }
        else
        {
            Trace("unknow command:%s", cmd);
        }

    loop:
        memset(line, 0, SHELL_MAX_LINE_LEN);
    }
}
Esempio n. 16
0
//
// Establishes the type of the resultant operation, as well as
// makes the operator the correct one for the operands.
//
// Returns false if operator can't work on operands.
//
bool TIntermBinary::promote(TInfoSink& infoSink)
{
    int size = left->getNominalSize();
    if (right->getNominalSize() > size)
        size = right->getNominalSize();

    TBasicType type = left->getBasicType();

    //
    // Arrays have to be exact matches.
    //
    if ((left->isArray() || right->isArray()) && (left->getType() != right->getType()))
        return false;

    //
    // Base assumption:  just make the type the same as the left
    // operand.  Then only deviations from this need be coded.
    //
    setType(TType(type, EvqTemporary, left->getNominalSize(), left->isMatrix()));

    //
    // Array operations.
    //
    if (left->isArray()) {

        switch (op) {

        //
        // Promote to conditional
        //
        case EOpEqual:
        case EOpNotEqual:
            setType(TType(EbtBool));
            break;

        //
        // Set array information.
        //
        case EOpAssign:
            getType().setArraySize(left->getType().getArraySize());
            getType().setArrayInformationType(left->getType().getArrayInformationType());
            break;

        default:
            return false;
        }

        return true;
    }
    
    //
    // All scalars.  Code after this test assumes this case is removed!
    //
    if (size == 1) {

        switch (op) {

        //
        // Promote to conditional
        //
        case EOpEqual:
        case EOpNotEqual:
        case EOpLessThan:
        case EOpGreaterThan:
        case EOpLessThanEqual:
        case EOpGreaterThanEqual:
            setType(TType(EbtBool));
            break;

        //
        // And and Or operate on conditionals
        //
        case EOpLogicalAnd:
        case EOpLogicalOr:
            if (left->getBasicType() != EbtBool || right->getBasicType() != EbtBool)
                return false;           
            setType(TType(EbtBool));
            break;

        //
        // Check for integer only operands.
        //
        case EOpMod:
        case EOpRightShift:
        case EOpLeftShift:
        case EOpAnd:
        case EOpInclusiveOr:
        case EOpExclusiveOr:
            if (left->getBasicType() != EbtInt || right->getBasicType() != EbtInt)
                return false;
            break;
        case EOpModAssign:
        case EOpAndAssign:
        case EOpInclusiveOrAssign:
        case EOpExclusiveOrAssign:
        case EOpLeftShiftAssign:
        case EOpRightShiftAssign:
            if (left->getBasicType() != EbtInt || right->getBasicType() != EbtInt)
                return false;
            // fall through

        //
        // Everything else should have matching types
        //
        default:
            if (left->getBasicType() != right->getBasicType() ||
                left->isMatrix()     != right->isMatrix())
                return false;
        }

        return true;
    }

    //
    // Are the sizes compatible?
    //
    if ( left->getNominalSize() != size &&  left->getNominalSize() != 1 ||
        right->getNominalSize() != size && right->getNominalSize() != 1)
        return false;

    //
    // Can these two operands be combined?
    //
    switch (op) {
    case EOpMul:
        if (!left->isMatrix() && right->isMatrix()) {
            if (left->isVector())
                op = EOpVectorTimesMatrix;
            else {
                op = EOpMatrixTimesScalar;
                setType(TType(type, EvqTemporary, size, true));
            }
        } else if (left->isMatrix() && !right->isMatrix()) {
            if (right->isVector()) {
                op = EOpMatrixTimesVector;
                setType(TType(type, EvqTemporary, size, false));
            } else {
                op = EOpMatrixTimesScalar;
            }
        } else if (left->isMatrix() && right->isMatrix()) {
            op = EOpMatrixTimesMatrix;
        } else if (!left->isMatrix() && !right->isMatrix()) {
            if (left->isVector() && right->isVector()) {
                // leave as component product
            } else if (left->isVector() || right->isVector()) {
                op = EOpVectorTimesScalar;
                setType(TType(type, EvqTemporary, size, false));
            }
        } else {
            infoSink.info.message(EPrefixInternalError, "Missing elses", getLine());
            return false;
        }
        break;
    case EOpMulAssign:
        if (!left->isMatrix() && right->isMatrix()) {
            if (left->isVector())
                op = EOpVectorTimesMatrixAssign;
            else {
                return false;
            }
        } else if (left->isMatrix() && !right->isMatrix()) {
            if (right->isVector()) {
                return false;
            } else {
                op = EOpMatrixTimesScalarAssign;
            }
        } else if (left->isMatrix() && right->isMatrix()) {
            op = EOpMatrixTimesMatrixAssign;
        } else if (!left->isMatrix() && !right->isMatrix()) {
            if (left->isVector() && right->isVector()) {
                // leave as component product
            } else if (left->isVector() || right->isVector()) {
                if (! left->isVector())
                    return false;
                op = EOpVectorTimesScalarAssign;
                setType(TType(type, EvqTemporary, size, false));
            }
        } else {
            infoSink.info.message(EPrefixInternalError, "Missing elses", getLine());
            return false;
        }
        break;      
    case EOpAssign:
        if (left->getNominalSize() != right->getNominalSize())
            return false;
        // fall through
    case EOpAdd:
    case EOpSub:
    case EOpDiv:
    case EOpMod:
    case EOpAddAssign:
    case EOpSubAssign:
    case EOpDivAssign:
    case EOpModAssign:
        if (left->isMatrix() && right->isVector() ||
            left->isVector() && right->isMatrix() ||
            left->getBasicType() != right->getBasicType())
            return false;
        setType(TType(type, EvqTemporary, size, left->isMatrix() || right->isMatrix()));
        break;
        
    case EOpEqual:
    case EOpNotEqual:
    case EOpLessThan:
    case EOpGreaterThan:
    case EOpLessThanEqual:
    case EOpGreaterThanEqual:
        if (left->isMatrix() && right->isVector() ||
            left->isVector() && right->isMatrix() ||
            left->getBasicType() != right->getBasicType())
            return false;
        setType(TType(EbtBool));
        break;

default:
        return false;
    }

    //
    // One more check for assignment.  The Resulting type has to match the left operand.
    //
    switch (op) {
    case EOpAssign:
    case EOpAddAssign:
    case EOpSubAssign:
    case EOpMulAssign:
    case EOpDivAssign:
    case EOpModAssign:
    case EOpAndAssign:
    case EOpInclusiveOrAssign:
    case EOpExclusiveOrAssign:
    case EOpLeftShiftAssign:
    case EOpRightShiftAssign:
        if (getType() != left->getType())
            return false;
        break;
    default: 
        break;
    }
    
    return true;
}
Esempio n. 17
0
int main( int argc, char const * const argv[] )
{
	if( 2 != argc ){
		fprintf( stderr, "Usage: %s /path/to/controlFile\n", argv[0] );
		return -1 ;
	}
	FILE *fIn = fopen( argv[1], "rt" );
	if( !fIn ){
		perror( argv[1] );
		return -1 ;
	}
	char cmdLine[512];
	if( !getLine( cmdLine, sizeof(cmdLine)-1, fIn ) ){
		perror( "cmdLine" );
		return -1 ;
	}
	while( getLine( inBuf,sizeof(inBuf)-1, fIn ) ){
		char name[80];
		unsigned timeout ;
		int numRead ;
		if( 2 == (numRead = sscanf( inBuf, "%s %u", &name, &timeout ) )){
			watchPoint_t *newOne = new watchPoint_t ;
			memset( newOne, 0, sizeof(*newOne) );
			newOne->name = strdup( name );
			newOne->timeout = timeout ;
			newOne->next = firstWP ;
			firstWP = newOne ;
                        ++numWP ;
		}
	} // until EOF

	if( 0 == numWP ){
		fprintf( stderr, "no watchpoints defined\n" );
		return -1 ;
	}
	fclose( fIn );

	int const sockFd = socket( AF_INET, SOCK_DGRAM, 0 );
	if( 0 > sockFd ){
		perror( "socket" );
		return -1 ;
	}

        int const doit = 1;
	int rval = setsockopt(sockFd, SOL_SOCKET, SO_REUSEADDR, (void *)&doit, sizeof(doit));
	if( 0 != rval ){
		perror( "setsockopt" );
		return -1 ;
	}

	int flags = flags = fcntl( sockFd, F_GETFL, 0 );
	rval = fcntl( sockFd, F_SETFL, flags | O_NONBLOCK );
	if( 0 != rval ){
		perror( "O_NONBLOCK" );
		return -1 ;
	}

	watchpoints = new watchPoint_t *[numWP];
	printf( "command line: %s\n", cmdLine );
	printf( "port %u (0x%x)\n", port, port );
	unsigned idx = 0 ;
       	for( watchPoint_t *next = firstWP ; next ; next = next->next ){
		unsigned wdNum = numWP-1-idx ;
		idx++ ;
		printf( "%u:%s: %u\n", wdNum, next->name, next->timeout );
		watchpoints[wdNum] = next ;
	}

	char *args[80];
	parse( cmdLine, args );
	showArgs( args );

	struct sigaction sa;

	/* Initialize the sa structure */
	sa.sa_handler = (__sighandler_t)childHandler ;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = SA_SIGINFO ; // pass info
	
	//   int result = 
	sigaction( SIGCHLD, &sa, 0 );

	do {
		// start program
		startChild( args, firstWP );

		// now monitor program
		pollfd rdPoll ;
		rdPoll.fd = sockFd ;
		while( 0 < childPid_ ){
			rdPoll.events = POLLIN | POLLERR ;
			int const numEvents = poll( &rdPoll, 1, 1000 );
			long long const now = tickMs();
			if( 1 == numEvents )
			{
				sockaddr_in remote ;
				socklen_t   remSize = sizeof(remote);
				unsigned char in ;
				int numRead ;
				do {
					numRead = recvfrom( sockFd, &in, 1, 0, (struct sockaddr *)&remote, &remSize );
					if( 1 == numRead ){
						if( in < numWP ){
                                                        watchPoint_t &wp = *watchpoints[in];
							unsigned long elapsed = now-wp.lastAlive ;
							wp.lastAlive = now ;
							wp.count++ ;
							if( elapsed < wp.minInterval )
                                                                wp.minInterval = elapsed ;
							if( elapsed > wp.maxInterval )
								wp.maxInterval = elapsed ;
						}
						else
							fprintf( stderr, "Invalid watchpoint %u, max %u\n", in, numRead );
					}
				} while( 1 == numRead );
			}
			bool killit = false ;
			for( unsigned i = 0 ; i < numWP ; i++ ){
				watchPoint_t &wp = *watchpoints[i];
				unsigned long elapsed = now-wp.lastAlive ;
				if( elapsed > wp.timeout ){
					printf( "event %u expired: %u elapsed, max %u\n", i, elapsed, wp.timeout );
					killit = true ;
				}
			}
			if( killit ){
				pid_t pid = childPid_ ;
				printf( "killing child process %d\n", pid );
				if( 0 < pid ){
					kill( pid, SIGKILL );
				}
				while( 0 > childPid_ ){
					printf( "waiting for child\n" );
					sleep(1);
				}
			}
		} // while child is stilll alive
		printf( "%lld:child died. restarting\n", tickMs() );
	} while( 1 );

	return 0 ;
}
Esempio n. 18
0
unsigned SIPClient::getResponseCode() {
  unsigned responseCode = 0;
  do {
    // Get the response from the server:
    unsigned const readBufSize = 10000;
    char readBuffer[readBufSize+1]; char* readBuf = readBuffer;

    char* firstLine = NULL;
    char* nextLineStart = NULL;
    unsigned bytesRead = getResponse(readBuf, readBufSize);
    if (bytesRead == 0) break;
    if (fVerbosityLevel >= 1) {
      envir() << "Received INVITE response: " << readBuf << "\n";
    }

    // Inspect the first line to get the response code:
    firstLine = readBuf;
    nextLineStart = getLine(firstLine);
    if (!parseResponseCode(firstLine, responseCode)) break;

    if (responseCode != 200) {
      if (responseCode >= 400 && responseCode <= 499
	  && fWorkingAuthenticator != NULL) {
	// We have an authentication failure, so fill in
	// "*fWorkingAuthenticator" using the contents of a following
	// "Proxy-Authenticate:" line.  (Once we compute a 'response' for
	// "fWorkingAuthenticator", it can be used in a subsequent request
	// - that will hopefully succeed.)
	char* lineStart;
	while (1) {
	  lineStart = nextLineStart;
	  if (lineStart == NULL) break;

	  nextLineStart = getLine(lineStart);
	  if (lineStart[0] == '\0') break; // this is a blank line

	  char* realm = strDupSize(lineStart);
	  char* nonce = strDupSize(lineStart);
	  // ##### Check for the format of "Proxy-Authenticate:" lines from
	  // ##### known server types.
	  // ##### This is a crock! We should make the parsing more general
          Boolean foundAuthenticateHeader = False;
	  if (
	      // Asterisk #####
	      sscanf(lineStart, "Proxy-Authenticate: Digest realm=\"%[^\"]\", nonce=\"%[^\"]\"",
		     realm, nonce) == 2 ||
	      // Cisco ATA #####
	      sscanf(lineStart, "Proxy-Authenticate: Digest algorithm=MD5,domain=\"%*[^\"]\",nonce=\"%[^\"]\", realm=\"%[^\"]\"",
		     nonce, realm) == 2) {
            fWorkingAuthenticator->setRealmAndNonce(realm, nonce);
            foundAuthenticateHeader = True;
          }
          delete[] realm; delete[] nonce;
          if (foundAuthenticateHeader) break;
	}
      }
      envir().setResultMsg("cannot handle INVITE response: ", firstLine);
      break;
    }

    // Skip every subsequent header line, until we see a blank line.
    // While doing so, check for "To:" and "Content-Length:" lines.
    // The remaining data is assumed to be the SDP descriptor that we want.
    // We should really do some more checking on the headers here - e.g., to
    // check for "Content-type: application/sdp", "CSeq", etc. #####
    int contentLength = -1;
    char* lineStart;
    while (1) {
      lineStart = nextLineStart;
      if (lineStart == NULL) break;

      nextLineStart = getLine(lineStart);
      if (lineStart[0] == '\0') break; // this is a blank line

      char* toTagStr = strDupSize(lineStart);
      if (sscanf(lineStart, "To:%*[^;]; tag=%s", toTagStr) == 1) {
	delete[] (char*)fToTagStr; fToTagStr = strDup(toTagStr);
	fToTagStrSize = strlen(fToTagStr);
      }
      delete[] toTagStr;

      if (sscanf(lineStart, "Content-Length: %d", &contentLength) == 1
          || sscanf(lineStart, "Content-length: %d", &contentLength) == 1) {
        if (contentLength < 0) {
          envir().setResultMsg("Bad \"Content-length:\" header: \"",
                               lineStart, "\"");
          break;
        }
      }
    }

    // We're now at the end of the response header lines
    if (lineStart == NULL) {
      envir().setResultMsg("no content following header lines: ", readBuf);
      break;
    }

    // Use the remaining data as the SDP descr, but first, check
    // the "Content-length:" header (if any) that we saw.  We may need to
    // read more data, or we may have extraneous data in the buffer.
    char* bodyStart = nextLineStart;
    if (bodyStart != NULL && contentLength >= 0) {
      // We saw a "Content-length:" header
      unsigned numBodyBytes = &readBuf[bytesRead] - bodyStart;
      if (contentLength > (int)numBodyBytes) {
        // We need to read more data.  First, make sure we have enough
        // space for it:
        unsigned numExtraBytesNeeded = contentLength - numBodyBytes;
#ifdef USING_TCP
	// THIS CODE WORKS ONLY FOR TCP: #####
        unsigned remainingBufferSize
          = readBufSize - (bytesRead + (readBuf - readBuffer));
        if (numExtraBytesNeeded > remainingBufferSize) {
          char tmpBuf[200];
          sprintf(tmpBuf, "Read buffer size (%d) is too small for \"Content-length:\" %d (need a buffer size of >= %d bytes\n",
                  readBufSize, contentLength,
                  readBufSize + numExtraBytesNeeded - remainingBufferSize);
          envir().setResultMsg(tmpBuf);
          break;
        }

        // Keep reading more data until we have enough:
        if (fVerbosityLevel >= 1) {
          envir() << "Need to read " << numExtraBytesNeeded
		  << " extra bytes\n";
        }
        while (numExtraBytesNeeded > 0) {
          char* ptr = &readBuf[bytesRead];
	  unsigned bytesRead2;
	  struct sockaddr_in fromAddr;
	  Boolean readSuccess
	    = fOurSocket->handleRead((unsigned char*)ptr,
				     numExtraBytesNeeded,
				     bytesRead2, fromAddr);
          if (!readSuccess) break;
          ptr[bytesRead2] = '\0';
          if (fVerbosityLevel >= 1) {
            envir() << "Read " << bytesRead2
		    << " extra bytes: " << ptr << "\n";
          }

          bytesRead += bytesRead2;
          numExtraBytesNeeded -= bytesRead2;
        }
#endif
        if (numExtraBytesNeeded > 0) break; // one of the reads failed
      }

      bodyStart[contentLength] = '\0'; // trims any extra data
    }
  } while (0);

  return responseCode;
}
Esempio n. 19
0
int main(int argc, char **argv) 
{

    clock_t s_time, e_time;
    char line[__INPUT_LENGTH__] = {0};
    int i;
    fstring __path__ = NULL, mode = NULL;

    friso_t friso;
    friso_config_t config;
    friso_task_t task;

    //get the lexicon directory
    for ( i = 0; i < argc; i++ ) {
        if ( strcasecmp( "-init", argv[i] ) == 0 ) {
            __path__ = argv[i+1];
        }
    }
    if ( __path__ == NULL ) {
        println("Usage: friso -init lexicon path");
        exit(0);
    }

    s_time = clock();

    //initialize
    friso = friso_new();
    config = friso_new_config();
    /*friso_dic_t dic = friso_dic_new();
      friso_dic_load_from_ifile( dic, __path__, __LENGTH__ );
      friso_set_dic( friso, dic );
      friso_set_mode( friso, __FRISO_COMPLEX_MODE__ );*/
    if ( friso_init_from_ifile(friso, config, __path__) != 1 ) {
        printf("fail to initialize friso and config.");
        goto err;
    }

    switch ( config->mode ) 
    {
        case __FRISO_SIMPLE_MODE__:
            mode = "Simple";
            break;
        case __FRISO_COMPLEX_MODE__:
            mode = "Complex";
            break;
        case __FRISO_DETECT_MODE__:
            mode = "Detect";
            break;
    }

    //friso_set_mode( config, __FRISO_DETECT_MODE__ );
    //printf("clr_stw=%d\n", friso->clr_stw);
    //printf("match c++?%d\n", friso_dic_match( friso->dic, __LEX_ENPUN_WORDS__, "c++" ));
    //printf("match(研究)?%d\n", friso_dic_match( friso->dic, __LEX_CJK_WORDS__, "研究"));

    e_time = clock();

    printf("Initialized in %fsec\n", (double) ( e_time - s_time ) / CLOCKS_PER_SEC );
    printf("Mode: %s\n", mode);
    printf("+-Version: %s (%s)\n", friso_version(), friso->charset == FRISO_UTF8 ? "UTF-8" : "GBK" );
    ___ABOUT___;

    //set the task.
    task = friso_new_task();

    while ( 1 ) 
    {
        print("friso>> ");
        getLine( stdin, line );
        //exit the programe
        if ( strcasecmp( line, "quit" ) == 0 ) {
            ___EXIT_INFO___
        }

        //for ( i = 0; i < 1000000; i++ ) {
        //set the task text.
        friso_set_text( task, line );
        println("分词结果:");

        s_time = clock();
        while ( ( config->next_token( friso, config, task ) ) != NULL ) 
        {
            //printf("%s[%d, %d, %d] ", task->token->word, 
            //        task->token->offset, task->token->length, task->token->rlen );
            printf("%s ", task->token->word );
        }
        //}
        e_time = clock();
        printf("\nDone, cost < %fsec\n", ( (double)(e_time - s_time) ) / CLOCKS_PER_SEC );

    }

    friso_free_task( task );

    //error block.
err:
    friso_free_config(config);
    friso_free(friso);
    

    return 0;
}
Esempio n. 20
0
BOOL CALLBACK GoToLineDlg::run_dlgProc(UINT message, WPARAM wParam, LPARAM)
{
	switch (message)
	{
		case WM_INITDIALOG :
		{
			::SendDlgItemMessage(_hSelf, IDC_RADIO_GOTOLINE, BM_SETCHECK, TRUE, 0);
			goToCenter();
			return TRUE;
		}
		case WM_COMMAND :
		{
			switch (wParam)
			{
				case IDCANCEL : // Close
					display(false);
                    cleanLineEdit();
					return TRUE;

				case IDOK :
                {
                    int line = getLine();
                    if (line != -1)
                    {
                        display(false);
                        cleanLineEdit();
						if (_mode == go2line) {
							(*_ppEditView)->execute(SCI_ENSUREVISIBLE, line-1);
							(*_ppEditView)->execute(SCI_GOTOLINE, line-1);
						} else {
							int sci_line = (*_ppEditView)->execute(SCI_LINEFROMPOSITION, line);
							(*_ppEditView)->execute(SCI_ENSUREVISIBLE, sci_line);
							(*_ppEditView)->execute(SCI_GOTOPOS, line);
						}
                    }
                    (*_ppEditView)->getFocus();
                    return TRUE;
                }

				case IDC_RADIO_GOTOLINE :
				case IDC_RADIO_GOTOOFFSET :
				{

					bool isLine, isOffset;
					if (wParam == IDC_RADIO_GOTOLINE)
					{
						isLine = true;
						isOffset = false;
						_mode = go2line;
					}
					else
					{
						isLine = false;
						isOffset = true;
						_mode = go2offsset;
					}
					::SendDlgItemMessage(_hSelf, IDC_RADIO_GOTOLINE, BM_SETCHECK, isLine, 0);
					::SendDlgItemMessage(_hSelf, IDC_RADIO_GOTOOFFSET, BM_SETCHECK, isOffset, 0);
					updateLinesNumbers();
					return TRUE;
				}
				default :
				{
					switch (HIWORD(wParam))
					{
						case EN_SETFOCUS :
						case BN_SETFOCUS :
							updateLinesNumbers();
							return TRUE;
						default :
							return TRUE;
					}
					break;
				}
			}
		}

		default :
			return FALSE;
	}
}
Esempio n. 21
0
void hsTokenStream::getLine() {
    while (!fLineTokens.empty())
        fLineTokens.pop();
    if (fStream->eof())
        return;

    plString line = fStream->readLine() + "\n";
    size_t beg=0, end=0;
    int tokType;
    while (end < line.len()) {
        beg = end;
        if (fInComment == -1) {
            while (beg < line.len() && getCharType(line[beg]) == kCharNone)
                beg++;
        }
        for (auto mark = fStringMarkers.begin(); mark != fStringMarkers.end(); ++mark) {
            if (line.mid(beg).startsWith(mark->fStart)) {
                long strEnd = line.mid(beg + mark->fStart.len()).find(mark->fEnd);
                if (strEnd == -1)
                    throw hsBadParamException(__FILE__, __LINE__);
                unsigned long markerLen = mark->fStart.len() + mark->fEnd.len();
                fLineTokens.push(line.mid(beg, strEnd + markerLen));
                beg += strEnd + markerLen;
            }
        }
        for (size_t i=0; i<fCommentMarkers.size(); i++) {
            if (fInComment == -1 && line.mid(beg).startsWith(fCommentMarkers[i].fStart)) {
                fInComment = i;
                beg += fCommentMarkers[i].fStart.len();
            }
        }
        if (fInComment == -1) {
            while (beg < line.len() && getCharType(line[beg]) == kCharNone)
                beg++;
        }
        end = beg;
        if (fInComment != -1) {
            tokType = kCharComment;
            while (end < line.len() && fInComment != -1) {
                if (line.mid(end).startsWith(fCommentMarkers[fInComment].fEnd)) {
                    end += fCommentMarkers[fInComment].fEnd.len();
                    fInComment = -1;
                } else {
                    end++;
                }
            }
        } else {
            tokType = getCharType(line[beg]);
            while (end < line.len() && getCharType(line[end]) == tokType) {
                end++;
                if (tokType == kCharDelim) break; // Only return one Delimiter
            }
            if (end != beg)
                fLineTokens.push(line.mid(beg, end-beg));
        }
    }

    // Check for a blank line and skip it
    if (fLineTokens.empty())
        getLine();
}
Esempio n. 22
0
/* returns >= 0 if action/size has been set to a valid action
   returns -1 for failure (disconnect, timeout, too many bad actions, etc) */
static int readPlayerResponse( const Game *game, const MatchState *state,
			       const int quiet, const uint8_t seat,
			       const struct timeval *sendTime,
			       ErrorInfo *errorInfo,
			       int seatFD, ReadBuf *readBuf,
			       Action *action, struct timeval *recvTime )
{
  int c, r;
  MatchState tempState;
  char line[ MAX_LINE_LEN ];

  while( 1 ) {

    /* read a line of input from player */
    if( getLine( seatFD, readBuf, MAX_LINE_LEN, line,
		 errorInfo->maxResponseMicros ) <= 0 ) {
      /* couldn't get any input from player */

      fprintf( stderr, "ERROR: could not get action from seat %"PRIu8"\n",
	       seat + 1 );
      return -1;
    }

    /* note when the message arrived */
    gettimeofday( recvTime, NULL );

    /* log the response */
    if( !quiet ) {
      fprintf( stderr, "FROM %d at %zu.%06zu %s", seat + 1,
	       recvTime->tv_sec, recvTime->tv_usec, line );
    }

    /* ignore comments */
    if( line[ 0 ] == '#' || line[ 0 ] == ';' ) {
      continue;
    }

    /* check for any timeout issues */
    if( checkErrorTimes( seat, sendTime, recvTime, errorInfo ) < 0 ) {

      fprintf( stderr, "ERROR: seat %"PRIu8" ran out of time\n", seat + 1 );
      return -1;
    }

    /* parse out the state */
    c = readMatchState( line, game, &tempState );
    if( c < 0 ) {
      /* couldn't get an intelligible state */

      fprintf( stderr, "WARNING: bad state format in response\n" );
      continue;
    }

    /* ignore responses that don't match the current state */
    if( !matchStatesEqual( game, state, &tempState ) ) {

      fprintf( stderr, "WARNING: ignoring un-requested response\n" );
      continue;
    }

    /* get the action */
    if( line[ c++ ] != ':'
	|| ( r = readAction( &line[ c ], game, action ) ) < 0 ) {

      if( checkErrorInvalidAction( seat, errorInfo ) < 0 ) {

	fprintf( stderr, "ERROR: bad action format in response\n" );
      }

      fprintf( stderr,
	       "WARNING: bad action format in response, changed to call\n" );
      action->type = call;
      action->size = 0;
      goto doneRead;
    }
    c += r;

    /* make sure the action is valid */
    if( !isValidAction( game, &state->state, 1, action ) ) {

      if( checkErrorInvalidAction( seat, errorInfo ) < 0 ) {

	fprintf( stderr, "ERROR: invalid action\n" );
	return -1;
      }

      fprintf( stderr, "WARNING: invalid action, changed to call\n" );
      action->type = call;
      action->size = 0;
    }

    goto doneRead;
  }

 doneRead:
  return 0;
}
Esempio n. 23
0
 std::string TestAssertionFailureException::toString() const {
     std::ostringstream os;
     os << getMessage() << " @" << getFile() << ":" << getLine();
     return os.str();
 }
Esempio n. 24
0
bool                              // returns true if success
processMultiGraphSection(FILE *fp,
			 string& theline,
			 bool& new_section)
{
  vector<string> v_tokens;
  TString  title;
  string   *gid  = NULL;
  TVectorD vx,vy,vz,exl,exh,eyl,eyh;
  float xoffset=0.0,yoffset=0.0, yscale=1.0;
  float xmin=0.,xmax=0.,ymin=0.,ymax=0.,zmin=0.,zmax=0.;
  bool asymerrors = false;
  wGraph_t *wg = NULL;

  char xheader[80],yheader[80];
  xheader[0]=0;
  yheader[0]=0;

  if (gl_verbose) cout << "Processing multigraph section" << endl;

  new_section=false;

  while (getLine(fp,theline,"multigraph")) {
    if (!theline.size()) continue;
    if (theline[0] == '#') continue; // comments are welcome

    if (theline[0] == '[') {
      new_section=true;
      break;
    }

    string key, value;
    if (!getKeyValue(theline,key,value)) continue;

    //--------------------
    if (key == "id") {
    //--------------------
      if (gid != NULL) {
	cerr << "no more than one id per section allowed " << value << endl;
	break;
      }

      gid = new string(value);

    //------------------------------
    } else if (key == "graphs") {
    //------------------------------
      if (!gid) {
	cerr << "id key must be defined first in the section" << endl; continue;
      }

      Tokenize(value,v_tokens,","); 

      for (size_t i=0; i<v_tokens.size(); i++) {
	map<string,wGraph_t *>::const_iterator it = glmap_id2graph.find(v_tokens[i]);
	if( it == glmap_id2graph.end() ) {
	  cerr << "Graph ID " << v_tokens[i] << " not found,";
	  cerr << "graphs must be defined before multigraph section" << endl;
	  break;
	}
	wg  = new wGraph_t(*(it->second),*gid);
	
      }
      if (wg) {
	cerr << "graph already defined" << endl; continue;
      }
      if (inSet<string>(glset_graphFilesReadIn,path)) {
	cerr << "vector file " << path << " already read in" << endl; break;
      }

      wg = new wGraph_t();

      if (asymerrors)
	loadVectorsFromFile(path.c_str(),scanspec.c_str(),vx,vy,exl,exh,eyl,eyh);
      else
	loadVectorsFromFile(path.c_str(),scanspec.c_str(),vx,vy,xheader,yheader);

      if (strlen(xheader)) wg->xax->SetTitle(xheader);
      if (strlen(yheader)) wg->yax->SetTitle(yheader);

    //------------------------------
    } else if (key == "vectorfile2d") {
    //------------------------------
      if (!gid) {
	cerr << "id key must be defined first in the section" << endl; continue;
      }
      string path = value;
      if (wg) {
	cerr << "graph already defined" << endl; continue;
      }
      if (inSet<string>(glset_graphFilesReadIn,path)) {
	cerr << "vector file " << path << " already read in" << endl; break;
      }

      wg = new wGraph_t();

      wg->gr2d = new TGraph2D(path.c_str());

      if (wg->gr2d->IsZombie()) {
	cerr << "Unable to make Graph2D from file " << path << endl;
	exit(-1);
      }
      wg->gr2d->SetName(gid->c_str());

    //------------------------------
    } else if (key == "path") {
    //------------------------------

      if (!gid) {
	cerr << "id key must be defined first in the section" << endl; continue;
      }
      if (wg) {
	cerr << "graph already defined" << endl; continue;
      }
      wg = new wGraph_t();
      wg->gr  = getGraphFromSpec(*gid,value);
      if (!wg->gr) continue;

    //------------------------------
    } else if (key == "clone") {
    //------------------------------

      if (!gid) {
	cerr << "id key must be defined first in the section" << endl; continue;
      }
      if (wg) {
	cerr << "graph already defined" << endl; continue;
      }
      map<string,wGraph_t *>::const_iterator it = glmap_id2graph.find(value);
      if( it == glmap_id2graph.end() ) {
	cerr << "Graph ID " << value << " not found,";
	cerr << "clone must be defined after the clonee" << endl;
	break;
      }
      wg  = new wGraph_t(*(it->second),*gid);

    //------------------------------
    } else if (key == "bayesdiv") {
    //------------------------------

      Tokenize(value,v_tokens,",/"); // either comma-separated or using '/'
      if (v_tokens.size() != 2) {
	cerr << "expect comma-separated list of exactly two histo specs to divide! ";
	cerr << theline << endl;
	continue;
      }

      TH1 *tmph1 = (TH1 *)findHisto(v_tokens[0]); if (!tmph1) exit(-1);
      TH1 *tmph2 = (TH1 *)findHisto(v_tokens[1]); if (!tmph2) exit(-1);

      cout << tmph1->GetNbinsX() << " " << tmph2->GetNbinsX() << endl;

      wg = new wGraph_t();

      // equivalent to BayesDivide
      //
      if (gl_verbose) wg->gr = new TGraphAsymmErrors(tmph1,tmph2,"debug");
      else            wg->gr = new TGraphAsymmErrors(tmph1,tmph2,"");
      //if (gl_verbose) wg->gr = new TGraphAsymmErrors(tmph1,tmph2,"cl=0.683 b(1,1) mode v");
      //else            wg->gr = new TGraphAsymmErrors(tmph1,tmph2,"cl=0.683 b(1,1) mode");
      if (!wg->gr) {
	cerr << "BayesDivide didn't work! wonder why..." << endl;
	continue;
      } else if (gl_verbose) {
	cout << wg->gr->GetN() << " points in the graph" << endl;
      }

    } else if (!wg) {
      cerr<<"One of keys path,clone,vectorfile,vectorfile2d or bayesdiv must be defined before key..."<<key<<endl;
    } else {
      if     ( key == "xoffset" )      xoffset   = str2flt(value);
      else if( key == "yoffset" )      yoffset   = str2flt(value);
      else if( key == "yscale" )       yscale    = str2flt(value);
      else if( key == "title"  )       title     = TString(value);
      else if( key == "xtitle" )       wg->xax->SetTitle(value.c_str());
      else if( key == "ytitle" )       wg->yax->SetTitle(value.c_str());
      else if( key == "ztitle" )       wg->zax->SetTitle(value.c_str());
      else if( key == "xtitleoffset" ) wg->xax->SetTitleOffset(str2flt(value));
      else if( key == "ytitleoffset" ) wg->yax->SetTitleOffset(str2flt(value));
      else if( key == "ztitleoffset" ) wg->zax->SetTitleOffset(str2flt(value));
      else if( key == "xmin" )         xmin      = str2flt(value);
      else if( key == "xmax" )         xmax      = str2flt(value);
      else if( key == "ymin" )         ymin      = str2flt(value);
      else if( key == "ymax" )         ymax      = str2flt(value);
      else if( key == "zmin" )         zmin      = str2flt(value);
      else if( key == "zmax" )         zmax      = str2flt(value);
      else if( key == "linecolor" )    wg->lcolor  = str2int(value);
      else if( key == "linestyle" )    wg->lstyle  = str2int(value);
      else if( key == "linewidth" )    wg->lwidth  = str2int(value);
      else if( key == "markercolor" )  wg->mcolor  = str2int(value);
      else if( key == "markerstyle" )  wg->mstyle  = str2int(value);
      else if( key == "markersize"  )  wg->msize   = str2int(value);
      else if( key == "fillcolor" )    wg->fcolor  = str2int(value);
      else if( key == "fillstyle" )    wg->fstyle  = str2int(value);
      else if( key == "xndiv" )        wg->xax->SetNdivisions(str2int(value));
      else if( key == "yndiv" )        wg->yax->SetNdivisions(str2int(value));
      else if( key == "asymerrors" )   asymerrors  = (bool)str2int(value);
      else if( key == "leglabel" )     wg->leglabel   = value;
      else if( key == "draw" )         wg->drawopt    = value;
      else if( key == "legdraw" )      wg->legdrawopt = value;
      else if( key == "setprecision" ) cout << setprecision(str2int(value));
      else if( key == "printvecs2file") printVectorsToFile(wg); // ,value);
      else if( key == "fittf1" ) {
	TF1 *tf1 = findTF1(value);
	if( !tf1 ) {
	  cerr << "TF1 " << value << " must be defined first" << endl;
	  continue;
	}
	string funcnewname = value+(*gid);
	wg->fitfn = new TF1(*tf1);
	wg->fitfn->SetName(funcnewname.c_str());
      }
      else if ( key == "contours" ) {
	Tokenize(value,v_tokens,",");
	wg->contours = new TVectorD(v_tokens.size());
	for (size_t i=0; i<v_tokens.size(); i++)
	  wg->contours[i] = str2flt(v_tokens[i]);
      }
      else {
	cerr << "unknown key " << key << endl;
      }
#if 0
      processCommonHistoParams(key,value,*wh);
#endif
    }
  }

  //cout << title << endl;
  if (wg->gr2d) {
    wg->gr2d->SetTitle(title);
    wg->gr2d->SetLineStyle   (wg->lstyle);
    wg->gr2d->SetLineColor   (wg->lcolor);
    wg->gr2d->SetLineWidth   (wg->lwidth);
    wg->gr2d->SetMarkerColor (wg->mcolor);
    wg->gr2d->SetMarkerStyle (wg->mstyle);
    wg->gr2d->SetMarkerSize  (wg->msize);
    wg->gr2d->SetFillStyle   (wg->fstyle);
    wg->gr2d->SetFillColor   (wg->fcolor);
    if (zmax>zmin)  
      wg->zax->SetLimits(zmin,zmax);
  } else {
    if (vx.GetNoElements()) { // load utility guarantees the same size for both
      if (yscale  != 1.0) vy *= yscale;
      if (xoffset != 0.0) vx += xoffset;
      if (yoffset != 0.0) vy += yoffset;
      if (asymerrors) 
	wg->gr = new TGraphAsymmErrors(vx,vy,exl,exh,eyl,eyh);
      else
	wg->gr = new TGraph(vx,vy);
    }
    wg->gr->UseCurrentStyle();
    wg->gr->SetTitle(title);
    wg->gr->SetLineStyle   (wg->lstyle);
    wg->gr->SetLineColor   (wg->lcolor);
    wg->gr->SetLineWidth   (wg->lwidth);
    wg->gr->SetMarkerColor (wg->mcolor);
    wg->gr->SetMarkerStyle (wg->mstyle);
    wg->gr->SetMarkerSize  (wg->msize);
    wg->gr->SetFillStyle   (wg->fstyle);
    wg->gr->SetFillColor   (wg->fcolor);

    if (xmax>xmin) wg->xax->SetLimits(xmin,xmax);
    if (ymax>ymin) wg->yax->SetLimits(ymin,ymax);
  }

  glmap_id2graph.insert(pair<string,wGraph_t *>(*gid,wg));

  return (wg != NULL);
}                                                 // processGraphSection