void rawForcesAndMoments::readForceAndMomentData
(
    List<std::pair<scalar, label> >& timeLabel,
    vectorField& forces,
    vectorField& moments
)
{
    scalar val(0.0);
    string dummy;
    label Nentries(0);

    resizeFields( timeLabel, forces, moments, 10000 );

    forAll (timeDirs_, timeI)
    {
        scalar truncateReading(0);

        if (removeDuplicate_ && timeI < timeDirs_.size() -1)
        {
            truncateReading = std::atof( timeDirs_[timeI + 1].c_str() );
        }
        else
        {
            truncateReading = GREAT;
        }

        std::stringstream ss;
        ss << inputDir_ << "/" << timeDirs_[timeI] << "/forces.dat";

        std::ifstream input;
        input.open( (ss.str()).c_str() );

        std::string line;

        // Discard the first line
        std::getline(input, line);

#if OFPLUSBRANCH==1
    // Discard two lines
    std::getline(input, line);
    std::getline(input, line);
#elif EXTBRANCH == 0
    #if OFVERSION >= 222
        // Discard yet another line
        std::getline(input, line);

        #if OFVERSION >= 230
            // Discard yet and yet another line
            std::getline(input, line);
        #endif
    #endif
#endif

        // Extracting time and overtopping flux vector
        while (std::getline( input, line ))
        {
            std::istringstream iss(line);

            // Reading the time instance
            iss >> val;

            if (truncateReading <= val)
            {
                break;
            }

            timeLabel[Nentries].first = val;
            timeLabel[Nentries].second = Nentries;

            vector temp( vector::zero );

            // Reading the first vector component with starting parenteres
            iss >> dummy;
#if EXTBRANCH==1
            temp.x() = std::atof((dummy.substr(3,dummy.size()-1)).c_str());
#elif OFPLUSBRANCH==1
            temp.x() = std::atof((dummy.substr(2,dummy.size()-1)).c_str());
#else
    #if 220<=OFVERSION
            temp.x() = std::atof((dummy.substr(3,dummy.size()-1)).c_str());
    #else
            temp.x() = std::atof((dummy.substr(2,dummy.size()-1)).c_str());
    #endif
#endif
            // Reading the second vector component. Simple scalar
            iss >> val;
            temp.y() = val;

            // Reading the third vector component with ending parenteres
            iss >> dummy;
            temp.z() = std::atof((dummy.substr(0,dummy.size()-1)).c_str());

            forces[Nentries] = temp;

            // Ignore the viscous forces
            iss >> dummy; iss >> dummy; iss >> dummy;

            // Reading the first vector component with starting parenteres
            iss >> dummy;
            temp.x() = std::atof((dummy.substr(2,dummy.size()-1)).c_str());

            // Reading the second vector component. Simple scalar
            iss >> val;
            temp.y() = val;

            // Reading the third vector component with ending parenteres
            iss >> dummy;
            temp.z() = std::atof((dummy.substr(0,dummy.size()-1)).c_str());

            moments[Nentries] = temp;

            Nentries++;

            if (Nentries == timeLabel.size())
            {
                resizeFields( timeLabel, forces, moments, 2*Nentries );
            }
        }

        input.close();
    }
コード例 #2
0
ファイル: resourcemanager.cpp プロジェクト: DYFeng/infinidb
bool ResourceManager::userPriorityEnabled() const
{
	std::string val(getStringVal("UserPriority", "Enabled", "N" ));
	boost::to_upper(val);
	return "Y" == val;
}
コード例 #3
0
ファイル: DexCalc.cpp プロジェクト: onlyuser/Legacy
float DexCalc::eval(std::string expr)
{
	int i;
	std::string result;
	std::string newExpr, token, prevToken;
	std::stack<std::string> opStack, elemStack, inStack;
	int depth;
	newExpr = "(" + expr + ")";
	if (!mTurbo)
		newExpr = TS_Util::fixExpr(newExpr);
	newExpr = replaceEx(newExpr, "E", "*10^");
	// STEP #1 (GROUP)
	// group tokens into operators and operands
	// (check for syntax errors)
	//
	// "(1 * 2 + 3)"
	//
	// [O]: ( * + )
	// [E]: 1 2 3
	// [I]:
	token = "";
	depth = 0;
	i = 0;
	while (i < newExpr.length())
	{
		prevToken = token;
		//==============================
		token = getNextTerm(newExpr, i);
		//==============================
		depth += (token == "(") ? 1 : 0;
		depth -= (token == ")") ? 1 : 0;
		if (depth < 0)
			throw Exception("expected end of statement");
		#ifndef TURBO_MODE
			if (TS_Util::rankOp(prevToken[0]) > 0 || prevToken == "(")
			{
				if (token == "+")
				{
					token = prevToken;
					continue;
				}
				if (token == "-") token = "neg";
				if (token == "!") token = "not";
				if (token == "~") token = "bnot";
				std::string prefix = left(token, 2);
				std::string value = lcase(right(token, token.length() - 2));
				if (prefix == "0x")
					token = changeBase(value, 16, 10);
				if (prefix == "0o")
					token = changeBase(value, 8, 10);
				if (prefix == "0b")
					token = changeBase(value, 2, 10);
			}
			if (
				TS_Util::rankOp(prevToken[0]) && (token[0] == OP_INC || token[0] == OP_DEC) ||
				(prevToken[0] == OP_INC || prevToken[0] == OP_DEC) && TS_Util::rankOp(token[0])
				)
				elemStack.push("0");
			else if (TS_Util::isFunc(prevToken) && token != "@" && token != ")")
				opStack.push("@");
			else
				TS_Util::checkSyntaxError(prevToken, token);
		#endif
		//=================================
		if (TS_Util::rankOp(token[0]))
			opStack.push(token);
		else
			elemStack.push(token);
		//=================================
	}
	if (depth > 0)
		throw Exception("expected close paren");
	// force operator into inStack
	// (start chain reaction)
	//
	// "(1 * 2 + 3)"
	//
	// [O]: ( * +
	// [E]: 1 2 3
	// [I]: )
	inStack.push(opStack.top());
	opStack.pop();
	while (!inStack.empty())
	{
		// STEP #2 (LOAD)
		// load inStack with opStack, elemStack elements
		// (stop at appropriate point)
		//
		// "(1 * 2 + 3)"
		//
		// [O]: (
		// [E]: 1
		// [I]: ) 3 + 2 *
		while
			(
				(opStack.top()[0] == OP_SET && TS_Util::rankOp(opStack.top()[0]) > TS_Util::rankOp(inStack.top()[0])) ||
				(opStack.top()[0] != OP_SET && TS_Util::rankOp(opStack.top()[0]) >= TS_Util::rankOp(inStack.top()[0])) ||
				opStack.top() == ")"
			)
		{
			// transfer close-parens to inStack
			// (if any)
			while (opStack.top() == ")")
			{
				inStack.push(opStack.top());
				opStack.pop();
			}
			// transfer operand to inStack
			inStack.push(elemStack.top());
			elemStack.pop();
			// force operator into inStack
			// (continue chain reaction)
			if (opStack.top() != "(")
			{
				inStack.push(opStack.top());
				opStack.pop();
			}
		}
		// STEP #3 (BIND)
		// bind elemStack, inStack operands with an opStack operator
		// (push result into elemStack)
		//
		// "(1 * 2 + 3)"
		//
		// [O]: ( *
		// [E]: 1
		// [I]: ) 3 + 2
		//
		// [O]: ( +
		// [E]: 2
		// [I]: ) 3
		//
		// [O]: (
		// [E]: 5
		// [I]: )
		//
		// [O]:
		// [E]: 5
		// [I]:
		while (TS_Util::rankOp(opStack.top()[0]) <= TS_Util::rankOp(inStack.top()[0]))
		{
			if (TS_Util::rankOp(inStack.top()[0]))
			{
				//======================================================
				opStack.push(inStack.top());
				inStack.pop();
				float temp =
					this->bind(
						elemStack.top(), opStack.top()[0], inStack.top()
						);
				result = (fabs(temp) == HUGE_VAL) ? "0" : cstr(temp);
				opStack.pop();
				elemStack.pop();
				//======================================================
			}
			else
				result = inStack.top();
			//============
			inStack.pop();
			//============
			while (!opStack.empty() && opStack.top() == "(" && inStack.top() == ")")
			{
				opStack.pop();
				inStack.pop();
			}
			if (inStack.empty())
			{
				if (isNumeric(result))
					return val(result);
				else
					return this->getVar(result);
			}
			else
				elemStack.push(result);
		}
	}
	throw Exception("unknown error");
}
コード例 #4
0
ファイル: test.C プロジェクト: bainbrid/usercode
// -----------------------------------------------------------------------------
//
void test() {

  time_t start = TTimeStamp().GetSec();

  set_plot_style();

  bool draw = true;
  //bool debug = true;

  // Define analysis configuration
  PSet ps;
  defaultPSet(ps);

  // Response plots
  if (false) {
    //xSectDistr(ps);
    responseProfile();
    return;
  }
  
  // Print configuration
  std::stringstream ss;
  printPSet(ps,ss);
  std::cout << ss.str() << std::endl;
  
  // Params to store
  DoubleVV ratio, ratio_errh, ratio_errl, pass, pass_err, fail, fail_err;
  IntV length;
  clear( ratio, ratio_errh, ratio_errl, pass, pass_err, fail, fail_err, length );
  init( ps, ratio, ratio_errh, ratio_errl, pass, pass_err, fail, fail_err, length );
  
  // Loop through Meff bins 
  int loop = 0;
  int nloops = ps.nmeff;
  for ( int imeff = 0; imeff < ps.nmeff; ++imeff ) {

    // Generate numbers in (x1,x2) plane
    DoubleVV dalitz;
    generateTruth( ps, imeff, dalitz, true );

    // Integrate across dalitz plane
    integrate( ps, imeff, dalitz, ratio, ratio_errh, ratio_errl, 
	       pass, pass_err, fail, fail_err, length );
    
    // Labeling
    std::stringstream ss;
    ss << "Meff" << int( ps.meff_bins[imeff] );
    
    // New canvas for plots
    TCanvas* c1 = 0;
    if (draw) c1 = new TCanvas( TString("Canvas"+ss.str()), "" );
    
    // Pad for cross-section plot
    TPad* pad = 0;
    if (draw) pad = new TPad(TString("Pad"+ss.str()),"",0.,0.,1.,1.);
    if (pad) {
      pad->SetGrid();
      pad->Draw();
      pad->cd();
      pad->SetLogz();
    }
    TH1F* hr = 0;
    if (draw) hr = pad->DrawFrame(ps.min,ps.min,ps.max,ps.max);
    
    // Histo title
    if (hr) {
      std::stringstream sss;
      sss << "M_{eff}=" << ps.meff_bins[imeff] << " GeV"
	  << ", p_{T1}=" << dr(ps.pt1_bins[imeff],1) << " GeV"
	  << ", p_{T2}=" << dr(ps.pt2_bins[imeff],1) << " GeV"
	  << ", p_{T3}=" << dr(ps.pt3_bins[imeff],1) << " GeV";
      hr->SetTitle( sss.str().c_str() );
      hr->GetXaxis()->SetTitle( "x_{2}" );
      hr->GetYaxis()->SetTitle( "x_{1}" );
    }
    
    // Create 2D cross-section plot
    TH2D* his = 0;
    if (draw) his = new TH2D(TString("Histo"+ss.str()),"",
			     ps.nbins,ps.min,ps.max,
			     ps.nbins,ps.min,ps.max);
    
    //double x3 = ( 2. * ps.pt3_bins[imeff] ) / ( ps.meff_bins[imeff] + ps.pt3_bins[imeff] );
    
    // Fill 2D cross-section plot
    for ( int x2_bin = 0; x2_bin < ps.nbins; ++x2_bin ) { 
      for ( int x1_bin = 0; x1_bin < ps.nbins; ++x1_bin ) { 
// 	std::cout << " Fill:"
// 		  << " x2_bin: " << x2_bin 
// 		  << " x2: " << val(x2_bin,nbins) 
// 		  << " x1_bin: " << x1_bin 
// 		  << " x1: " << val(x1_bin,nbins) 
// 		  << " val: " << dalitz[x2_bin][x1_bin]
// 		  << std::endl;
	if (his) his->Fill( val(x2_bin,ps)+ps.width/2.,
			    val(x1_bin,ps)+ps.width/2.,
			    dalitz[x2_bin][x1_bin] ); 
      }
    }
    
    // Draw 2D cross-section plot
    gStyle->SetPalette(1);
    if (his) {
      //his->SetMaximum( his->GetMaximum()*10. );
      //his->SetMinimum( his->GetMinimum(1.e-12)*0.1 );
//       his->SetMaximum( 1.e9 );
//       his->SetMinimum( 1.e0 );
      his->Draw("COLZsame");
    }
    
    // Pad for AlphaT contours
    if (c1) c1->cd();
    TPad* overlay = 0;
    if (draw) overlay = new TPad(TString("Overlay"+ss.str()),"",0.,0.,1.,1.);
    if (overlay) {
      overlay->SetFillStyle(4000);
      overlay->SetFillColor(0);
      overlay->SetFrameFillStyle(4000);
      overlay->Draw();
      overlay->cd();
    }
    //TH1F* hframe = 0;
    if (draw) overlay->DrawFrame(pad->GetUxmin(),
				 pad->GetUymin(),
				 pad->GetUxmax(),
				 pad->GetUymax());
	  
    // Graphs of AlphaT contours
    TMultiGraph* mg = 0;
    if (draw) {
      mg = new TMultiGraph();
      for ( Int_t icut = 0; icut < (int)ps.cutValues.size(); icut++ ) {
	Double_t alpha_t = ps.cutValues[icut];
	const Int_t n = ps.nbins;
	DoubleV x1(n,0.);
	DoubleV x2(n,0.);
	for ( Int_t x2_bin = 0; x2_bin < ps.nbins; x2_bin++ ) {
	  x2[x2_bin] = x2_bin * ps.width;
	  x1[x2_bin] = cutAlgoInverse(ps.cutValues[icut],x2[x2_bin],ALGO_TYPE);
	}
	TGraph* gr = new TGraph(n,&x2.front(),&x1.front());
	mg->Add(gr,"l");
      }
      mg->Draw();
    }
	  
    if (c1) c1->cd();
    if (c1) c1->SaveAs(TString(ss.str()+".png"));
    if (c1) c1->SaveAs(TString(ss.str()+".pdf"));
    if (c1) c1->SaveAs(TString(ss.str()+".C"));

  }

  // Canvas for ratio vs Meff
  if (false) {
    
    TCanvas* c2 = new TCanvas( "c2", "" );
    c2->SetRightMargin(0.2);
    c2->SetLogy();
    c2->cd();
    TMultiGraph* mg2 = new TMultiGraph();

    DoubleV err( ps.nmeff, 0. );
    for ( Int_t icut = 0; icut < (int)ps.cutValues.size(); icut++ ) {
      if ( length[icut] == 0 ) { continue; }
//       TGraphAsymmErrors* gr = new TGraphAsymmErrors( length[icut], 
//  						     &ps.meff_bins.front(), 
//  						     &err.front(),
//  						     &err.front(),
//  						     &ratio[icut].front(),
//  						     &ratio_errl[icut].front(),
//  						     &ratio_errh[icut].front() );
      TGraph* gr = new TGraphAsymmErrors( length[icut], 
 					  &ps.meff_bins.front(), 
 					  &ratio[icut].front() );
      std::stringstream ss;
      ss << "a_{T}=" << ps.cutValues[icut];
// 	 << " Meff=" << meff_bins[imeff]
// 	 << ", p_{T3}=" << pt3_bins[imeff];
      mg2->Add(gr,"lp");
      gr->SetTitle(TString(ss.str()));
      gr->SetLineColor(2+icut);
      gr->SetLineWidth(2);
      gr->SetMarkerStyle(20+icut);
      gr->SetMarkerColor(2+icut);
      gr->SetMarkerSize(1.5);
    }
    
    mg2->Draw("a");
    mg2->GetYaxis()->SetRangeUser(1.e-6,1.e0);
    c2->Update();
    c2->BuildLegend(0.81,0.1,0.99,0.9);
    
    // Save canvases
    c2->cd();
    c2->SaveAs("RatioVsMeff.png");
    c2->SaveAs("RatioVsMeff.pdf");
    c2->SaveAs("RatioVsMeff.C");
    
  }
  
  time_t stop = TTimeStamp().GetSec();
  std::cout << " Time taken: " << stop - start <<  " seconds" << std::endl;

}
コード例 #5
0
ファイル: GobiQMICoreUIM.cpp プロジェクト: borovsky/libqmi
/*===========================================================================
METHOD:
   UIMUnblockControlKey (Public Method)

DESCRIPTION:
   This function unblocks the specified facility control key

PARAMETERS:
   id                   [ I ] - Facility ID
   pValue               [ I ] - Control key de-personalization string
   pUnblockRetriesLeft  [ O ] - The number of unblock retries left, after 
                                which the control key  will be permanently 
                                blocked (0xFFFFFFFF = unknown)
RETURN VALUE:
   ULONG - Return code
===========================================================================*/
eGobiError cGobiQMICore::UIMUnblockControlKey( 
   ULONG                      id, 
   CHAR *                     pValue,
   ULONG *                    pUnblockRetriesLeft )
{
   // Validate arguments
   if ( (pValue == 0) 
   ||   (pValue[0] == 0) 
   ||   (pUnblockRetriesLeft == 0) )
   {
      return eGOBI_ERR_INVALID_ARG;
   }

   *pUnblockRetriesLeft = ULONG_MAX;

   WORD msgID = (WORD)eQMI_DMS_UIM_UNBLOCK_CK;
   std::vector <sDB2PackingInput> piv;

   std::string val( pValue );
   ULONG valSz = val.size();

   // "%u %u \"%s\""
   std::ostringstream tmp;
   tmp << (UINT)id << " " << (UINT)valSz << " \"" << val << "\"";
   
   sProtocolEntityKey pek( eDB2_ET_QMI_DMS_REQ, msgID, 1 );
   sDB2PackingInput pi( pek, (LPCSTR)tmp.str().c_str() );
   piv.push_back( pi );

   // Pack up the QMI request
   const cCoreDatabase & db = GetDatabase();
   sSharedBuffer * pRequest = DB2PackQMIBuffer( db, piv );
   if (pRequest == 0)
   {
      return eGOBI_ERR_MEMORY;
   }
   
   // Send the QMI request
   sProtocolBuffer rsp = Send( eQMI_SVC_DMS, pRequest, 5000 );
   if (rsp.IsValid() == false)
   {
      return GetCorrectedLastError();
   }

   // Did we receive a valid QMI response?
   sQMIServiceBuffer qmiRsp( rsp.GetSharedBuffer() );
   if (qmiRsp.IsValid() == false)
   {
      return eGOBI_ERR_MALFORMED_RSP;
   }
   
   // Check the mandatory QMI result TLV for success
   ULONG rc = 0;
   ULONG ec = 0;
   bool bResult = qmiRsp.GetResult( rc, ec );
   if (bResult == false)
   {
      return eGOBI_ERR_MALFORMED_RSP;
   }
   else if (rc != 0)
   {
      // Prepare TLVs for parsing
      std::vector <sDB2NavInput> tlvs = DB2ReduceQMIBuffer( qmiRsp );

      // Parse the optional TLV we want (by DB key)
      sProtocolEntityKey tlvKey( eDB2_ET_QMI_DMS_RSP, msgID, 16 );
      cDataParser::tParsedFields pf = ParseTLV( db, rsp, tlvs, tlvKey );
      if (pf.size() >= 1) 
      {
         *pUnblockRetriesLeft = (ULONG)pf[0].mValue.mU8;
      }

      return GetCorrectedQMIError( ec );
   }

   return eGOBI_ERR_NONE;
}
コード例 #6
0
ファイル: Quantizer.c プロジェクト: blickly/ptii
/*** preinitBlock ***/
Token $actorSymbol(levels);
double* $actorSymbol(transitionPoints);
int $actorSymbol(i);
/**/

//$numPoints is number of transition points (# of levels - 1)

/*** initBlock ($numPoints)***/
$actorSymbol(levels) = $val(levels);
// allocate space to store levels and transitionPoints
// We use CALLOC to optimizate array performance
$actorSymbol(transitionPoints) =
(double*) calloc($numPoints, sizeof(double));

for ($actorSymbol(i) = 0;
     $actorSymbol(i) < ($numPoints - 1);
     $actorSymbol(i)++) {
    // transitionPoint[I] = (levels[I] + levels[I+1]) / 2;
    $actorSymbol(transitionPoints)[$actorSymbol(i)] =
        ($actorSymbol(levels).payload.DoubleArray->elements[$actorSymbol(i)]
                + $actorSymbol(levels).payload.DoubleArray->elements[$actorSymbol(i) + 1]) / 2.0;
}
/**/

/*** fireBlock ($numPoints)***/
for ($actorSymbol(i) = 0;
     $actorSymbol(i) < $numPoints;
     $actorSymbol(i)++) {
    if ($ref(input)
            <= $actorSymbol(transitionPoints)[$actorSymbol(i)]) {
コード例 #7
0
ファイル: user.cpp プロジェクト: swallen/mineserver
bool User::saveData()
{
  std::string outfile = Map::get().mapDirectory+"/players/"+this->nick+".dat";
  // Try to create parent directories if necessary
  struct stat stFileInfo;
  if(stat(outfile.c_str(), &stFileInfo) != 0)
  {
    std::string outdir = Map::get().mapDirectory+"/players";

    if(stat(outdir.c_str(), &stFileInfo) != 0)
    {
#ifdef WIN32
      if(_mkdir(outdir.c_str()) == -1)
#else
      if(mkdir(outdir.c_str(), 0755) == -1)
#endif

        return false;
    }
  }

  NBT_Value val(NBT_Value::TAG_COMPOUND);
  val.Insert("OnGround", new NBT_Value((sint8)1));
  val.Insert("Air", new NBT_Value((sint16)300));
  val.Insert("AttackTime", new NBT_Value((sint16)0));
  val.Insert("DeathTime", new NBT_Value((sint16)0));
  val.Insert("Fire", new NBT_Value((sint16)-20));
  val.Insert("Health", new NBT_Value((sint16)20));
  val.Insert("HurtTime", new NBT_Value((sint16)0));
  val.Insert("FallDistance", new NBT_Value(54.f));

  NBT_Value *nbtInv = new NBT_Value(NBT_Value::TAG_LIST, NBT_Value::TAG_COMPOUND);

  //Start with main items
  Item *slots   = (Item *)&inv.main;
  char slotid   = 0;
  char itemslot = 0;
  for(int i = 0; i < 36+4+4; i++)
  {
    //Crafting items after main
    if(i == 36)
    {
      slots    = (Item *)&inv.crafting;
      itemslot = 80;
      slotid   = 0;
    }
    //Equipped items last
    else if(i == 36+4)
    {
      slots    = (Item *)&inv.equipped;
      itemslot = 100;
      slotid   = 0;
    }
    if(slots[(uint8)slotid].count)
    {
    NBT_Value *val = new NBT_Value(NBT_Value::TAG_COMPOUND);
    val->Insert("Count", new NBT_Value((sint8)slots[(uint8)slotid].count));
    val->Insert("Slot", new NBT_Value((sint8)itemslot));
    val->Insert("Damage", new NBT_Value((sint16)slots[(uint8)slotid].health));
    val->Insert("id", new NBT_Value((sint16)slots[(uint8)slotid].type));
    nbtInv->GetList()->push_back(val);
    }

    slotid++;
    itemslot++;
  }

  val.Insert("Inventory", nbtInv);

  NBT_Value *nbtPos = new NBT_Value(NBT_Value::TAG_LIST, NBT_Value::TAG_DOUBLE);
  nbtPos->GetList()->push_back(new NBT_Value((double)pos.x));
  nbtPos->GetList()->push_back(new NBT_Value((double)pos.y));
  nbtPos->GetList()->push_back(new NBT_Value((double)pos.z));
  val.Insert("Pos", nbtPos);
  

  NBT_Value *nbtRot = new NBT_Value(NBT_Value::TAG_LIST, NBT_Value::TAG_FLOAT);
  nbtRot->GetList()->push_back(new NBT_Value((float)pos.yaw));
  nbtRot->GetList()->push_back(new NBT_Value((float)pos.pitch));
  val.Insert("Rotation", nbtRot);


  NBT_Value *nbtMotion = new NBT_Value(NBT_Value::TAG_LIST, NBT_Value::TAG_DOUBLE);
  nbtMotion->GetList()->push_back(new NBT_Value((double)0.0));
  nbtMotion->GetList()->push_back(new NBT_Value((double)0.0));
  nbtMotion->GetList()->push_back(new NBT_Value((double)0.0));
  val.Insert("Motion", nbtMotion);

  val.SaveToFile(outfile);

  return true;

}
コード例 #8
0
ファイル: Key.cpp プロジェクト: Gozala/gecko-dev
nsresult
Key::EncodeJSValInternal(JSContext* aCx, const jsval aVal,
                         uint8_t aTypeOffset, uint16_t aRecursionDepth)
{
  NS_ENSURE_TRUE(aRecursionDepth < MaxRecursionDepth, NS_ERROR_DOM_INDEXEDDB_DATA_ERR);

  static_assert(eMaxType * MaxArrayCollapse < 256,
                "Unable to encode jsvals.");

  if (JSVAL_IS_STRING(aVal)) {
    nsDependentJSString str;
    if (!str.init(aCx, aVal)) {
      return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
    }
    EncodeString(str, aTypeOffset);
    return NS_OK;
  }

  if (JSVAL_IS_INT(aVal)) {
    EncodeNumber((double)JSVAL_TO_INT(aVal), eFloat + aTypeOffset);
    return NS_OK;
  }

  if (JSVAL_IS_DOUBLE(aVal)) {
    double d = JSVAL_TO_DOUBLE(aVal);
    if (mozilla::IsNaN(d)) {
      return NS_ERROR_DOM_INDEXEDDB_DATA_ERR;
    }
    EncodeNumber(d, eFloat + aTypeOffset);
    return NS_OK;
  }

  if (!JSVAL_IS_PRIMITIVE(aVal)) {
    JS::Rooted<JSObject*> obj(aCx, JSVAL_TO_OBJECT(aVal));
    if (JS_IsArrayObject(aCx, obj)) {
      aTypeOffset += eMaxType;

      if (aTypeOffset == eMaxType * MaxArrayCollapse) {
        mBuffer.Append(aTypeOffset);
        aTypeOffset = 0;
      }
      NS_ASSERTION((aTypeOffset % eMaxType) == 0 &&
                   aTypeOffset < (eMaxType * MaxArrayCollapse),
                   "Wrong typeoffset");

      uint32_t length;
      if (!JS_GetArrayLength(aCx, obj, &length)) {
        return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
      }

      for (uint32_t index = 0; index < length; index++) {
        JS::Rooted<JS::Value> val(aCx);
        if (!JS_GetElement(aCx, obj, index, &val)) {
          return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
        }

        nsresult rv = EncodeJSValInternal(aCx, val, aTypeOffset,
                                          aRecursionDepth + 1);
        if (NS_FAILED(rv)) {
          return rv;
        }

        aTypeOffset = 0;
      }

      mBuffer.Append(eTerminator + aTypeOffset);

      return NS_OK;
    }

    if (JS_ObjectIsDate(aCx, obj)) {
      if (!js_DateIsValid(obj))  {
        return NS_ERROR_DOM_INDEXEDDB_DATA_ERR;
      }
      EncodeNumber(js_DateGetMsecSinceEpoch(obj), eDate + aTypeOffset);
      return NS_OK;
    }
  }

  return NS_ERROR_DOM_INDEXEDDB_DATA_ERR;
}
コード例 #9
0
ファイル: Key.cpp プロジェクト: Gozala/gecko-dev
// static
nsresult
Key::DecodeJSValInternal(const unsigned char*& aPos, const unsigned char* aEnd,
                         JSContext* aCx, uint8_t aTypeOffset, JS::MutableHandle<JS::Value> aVal,
                         uint16_t aRecursionDepth)
{
  NS_ENSURE_TRUE(aRecursionDepth < MaxRecursionDepth, NS_ERROR_DOM_INDEXEDDB_DATA_ERR);

  if (*aPos - aTypeOffset >= eArray) {
    JS::Rooted<JSObject*> array(aCx, JS_NewArrayObject(aCx, 0, nullptr));
    if (!array) {
      NS_WARNING("Failed to make array!");
      return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
    }

    aTypeOffset += eMaxType;

    if (aTypeOffset == eMaxType * MaxArrayCollapse) {
      ++aPos;
      aTypeOffset = 0;
    }

    uint32_t index = 0;
    JS::Rooted<JS::Value> val(aCx);
    while (aPos < aEnd && *aPos - aTypeOffset != eTerminator) {
      nsresult rv = DecodeJSValInternal(aPos, aEnd, aCx, aTypeOffset,
                                        &val, aRecursionDepth + 1);
      NS_ENSURE_SUCCESS(rv, rv);

      aTypeOffset = 0;

      if (!JS_SetElement(aCx, array, index++, &val)) {
        NS_WARNING("Failed to set array element!");
        return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
      }
    }

    NS_ASSERTION(aPos >= aEnd || (*aPos % eMaxType) == eTerminator,
                 "Should have found end-of-array marker");
    ++aPos;

    aVal.setObject(*array);
  }
  else if (*aPos - aTypeOffset == eString) {
    nsString key;
    DecodeString(aPos, aEnd, key);
    if (!xpc::StringToJsval(aCx, key, aVal)) {
      return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
    }
  }
  else if (*aPos - aTypeOffset == eDate) {
    double msec = static_cast<double>(DecodeNumber(aPos, aEnd));
    JSObject* date = JS_NewDateObjectMsec(aCx, msec);
    if (!date) {
      NS_WARNING("Failed to make date!");
      return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
    }

    aVal.setObject(*date);
  }
  else if (*aPos - aTypeOffset == eFloat) {
    aVal.setDouble(DecodeNumber(aPos, aEnd));
  }
  else {
    NS_NOTREACHED("Unknown key type!");
  }

  return NS_OK;
}
コード例 #10
0
ファイル: data.cpp プロジェクト: volterra-luo/z-afepack
double velocity(const Point<DIM>& x, const double& u)
{
  std::vector<double> val(DIM);
  val[0] = 2*u; val[1] = exp(u);
  return sqrt(val[0]*val[0] + val[1]*val[1]);
}
コード例 #11
0
nsSVGAnimatedPreserveAspectRatio::~nsSVGAnimatedPreserveAspectRatio()
{
    nsCOMPtr<nsISVGValue> val( do_QueryInterface(mBaseVal) );
    if (!val) return;
    val->RemoveObserver(this);
}
コード例 #12
0
ファイル: data.cpp プロジェクト: volterra-luo/z-afepack
std::vector<double> flux(const Point<DIM>& x, const double& u)
{
  std::vector<double> val(DIM);
  val[0] = u*u; val[1] = exp(u);
  return val;
}
コード例 #13
0
std::string
CommandEventHandler::exec(std::vector<std::string>& args)
{
  if (args.size() < 1)
    return agentWarnInvalidNumArgs(1);

  // delete double quotes from args[0], easier to parse
  if (args[0][0] == '"')
  {
    args[0].erase(0, 1); // delete the beginning one
    args[0].erase(args[0].size() - 1); // delete the ending one
  }

  std::vector<std::string>::iterator argi = args.begin();

  // handle first part separately, check if we have env vars
  bool envs = args[0].find('=') != std::string::npos;

  std::vector<std::string> envNames, envValues;
  // if we have envs we have to handle them separately
  if (envs)
  {
    char envVarStr[(*argi).size() + 1];
    envVarStr[(*argi).size()] = 0;
    (*argi).copy(envVarStr, (*argi).size());
    envVarStr[(*argi).size()] = 0;
    char *r_env;
    char *env = strtok_r(envVarStr, ",", &r_env);
    // now we have something like env1=val1
    while (env)
    {
      int len = strlen(env);
      int pos = -1;
      for (int i = 0; i < len; ++i)
      {
        if (env[i] == '=')
        {
          pos = i;
          break;
        }
      }
      if (pos == -1)
        continue;

      std::string var(env, pos), val(env + pos + 1);
      envNames.push_back(var);
      envValues.push_back(val);

      env = strtok_r(NULL, ",", &r_env);
    }
    // skip past the env part
    argi++;
  }

  // extract the prog
  std::string prog(*argi++);

  // what remains are the args
  std::ostringstream to_exec;
  to_exec << prog;
  for (; argi != args.end(); ++argi)
    to_exec << " " << *argi;

  mDataEventHandler = new SubprocessEventHandler(mBufSocket, *this,
                                                 to_exec.str(), envNames,
                                                 envValues);
  if (mDataEventHandler->closed())
  {
    delete mDataEventHandler;
    mDataEventHandler = NULL;
    return agentWarn("failed to launch process");
  }
  return "";
}
コード例 #14
0
ファイル: QXmppRpcIq.cpp プロジェクト: berndhs/qxmpp
QVariant XMLRPC::demarshall(const QDomElement &elem, QStringList &errors)
{
    if ( elem.tagName().toLower() != "value" )
    {
        errors << "Bad param value";
        return QVariant();
    }

    if ( !elem.firstChild().isElement() )
    {
        return QVariant( elem.text() );
    }

    const QDomElement typeData = elem.firstChild().toElement();
    const QString typeName = typeData.tagName().toLower();

    if (typeName == "nil")
    {
        return QVariant();
    }
    if ( typeName == "string" )
    {
        return QVariant( typeData.text() );
    }
    else if (typeName == "int" || typeName == "i4" )
    {
        bool ok = false;
        QVariant val( typeData.text().toInt( &ok ) );
        if (ok)
            return val;
        errors << "I was looking for an integer but data was courupt";
        return QVariant();
    }
    else if( typeName == "double" )
    {
        bool ok = false;
        QVariant val( typeData.text().toDouble( &ok ) );
        if (ok)
            return val;
        errors <<  "I was looking for an double but data was corrupt";
    }
    else if( typeName == "boolean" )
        return QVariant( typeData.text() == "1" || typeData.text().toLower() == "true" );
    else if( typeName == "datetime" || typeName == "datetime.iso8601" )
        return QVariant( QDateTime::fromString( typeData.text(), Qt::ISODate ) );
    else if( typeName == "array" )
    {
        QVariantList arr;
        QDomElement valueNode = typeData.firstChildElement("data").firstChildElement();
        while (!valueNode.isNull() && errors.isEmpty())
        {
            arr.append(demarshall(valueNode, errors));
            valueNode = valueNode.nextSiblingElement();
        }
        return QVariant( arr );
    }
    else if( typeName == "struct" )
    {
        QMap<QString,QVariant> stct;
        QDomNode valueNode = typeData.firstChild();
        while(!valueNode.isNull() && errors.isEmpty())
        {
            const QDomElement memberNode = valueNode.toElement().elementsByTagName("name").item(0).toElement();
            const QDomElement dataNode = valueNode.toElement().elementsByTagName("value").item(0).toElement();
            stct[ memberNode.text() ] = demarshall(dataNode, errors);
            valueNode = valueNode.nextSibling();
        }
        return QVariant(stct);
    }
    else if( typeName == "base64" )
    {
        QVariant returnVariant;
        QByteArray dest;
        QByteArray src = typeData.text().toLatin1();
        return QVariant(QByteArray::fromBase64(src));
    }

    errors << QString( "Cannot handle type %1").arg(typeName);
    return QVariant();
}
コード例 #15
0
ファイル: Scale.c プロジェクト: blickly/ptii
/***scaleOnLeft***/
    $ref(output) = $multiply_$cgType(input)_$cgType(factor)($ref(input), $val(factor));
/**/

/***scaleOnRight***/
    $ref(output) = $multiply_$cgType(factor)_$cgType(input)($val(factor), $ref(input));
/**/
コード例 #16
0
ファイル: qlocale_symbian.cpp プロジェクト: phen89/rtqt
/*!
    Returns a Qt version of the given \a sys_fmt Symbian locale format string.
*/
static QString s60ToQtFormat(const QString &sys_fmt)
{
    TLocale *locale = _s60Locale.GetLocale();

    QString result;
    QString other;
    QString qtformatchars = QString::fromLatin1("adhmsyzAHM");

    QChar c;
    int i = 0;
    bool open_escape = false;
    bool abbrev_next = false;
    bool abbrev_day = false;
    bool abbrev_month = false;
    bool abbrev_year = false;
    bool locale_indep_ordering = false;
    bool minus_mode = false;
    bool plus_mode = false;
    bool n_mode = false;
    TTimeFormat tf = locale->TimeFormat();

    while (i < sys_fmt.size()) {

        c = sys_fmt.at(i);

        // let formatting thru
        if (c.unicode() == '%') {
            // if we have gathered string, concat it
            if (!other.isEmpty()) {
                result += other;
                other.clear();
            }
            // if we have open escape, end it
            if (open_escape) {
                result += QLatin1Char('\'');
                open_escape = false;
            }

            ++i;
            if (i >= sys_fmt.size())
                break;

            c = sys_fmt.at(i);

            // process specials
            abbrev_next = c.unicode() == '*';
            plus_mode = c.unicode() == '+';
            minus_mode = c.unicode() == '-';

            if (abbrev_next || plus_mode || minus_mode) {
                ++i;
                if (i >= sys_fmt.size())
                    break;

                c = sys_fmt.at(i);

                if (plus_mode || minus_mode) {
                    // break on undefined plus/minus mode
                    if (c.unicode() != 'A' && c.unicode() != 'B')
                        break;
                }
            }

            switch (c.unicode()) {
                case 'F':
                {
                    // locale indep mode on
                    locale_indep_ordering = true;
                    break;
                }

                case '/':
                {
                    // date sep 0-3
                    ++i;
                    if (i >= sys_fmt.size())
                        break;

                    c = sys_fmt.at(i);
                    if (c.isDigit() && c.digitValue() <= 3) {
                        TChar s = locale->DateSeparator(c.digitValue());
                        TUint val = s;
                        // some indexes return zero for empty
                        if (val > 0)
                            result += QChar(val);
                    }
                    break;
                }

                case 'D':
                {
                    if (!locale_indep_ordering) {
                        if (abbrev_next)
                            abbrev_day = true;
                        break;
                    }

                    if (!abbrev_next)
                        result += QLatin1String("dd");
                    else
                        result += QLatin1Char('d');

                    break;
                }

                case 'M':
                {
                    if (!locale_indep_ordering) {
                        if (abbrev_next)
                            abbrev_month = true;
                        break;
                    }

                    if (!n_mode) {
                        if (!abbrev_next)
                            result += QLatin1String("MM");
                        else
                            result += QLatin1String("M");
                    } else {
                        if (!abbrev_next)
                            result += QLatin1String("MMMM");
                        else
                            result += QLatin1String("MMM");
                    }

                    break;
                }

                case 'N':
                {
                    n_mode = true;

                    if (!locale_indep_ordering) {
                        if (abbrev_next)
                            abbrev_month = true;
                        break;
                    }

                    if (!abbrev_next)
                        result += QLatin1String("MMMM");
                    else
                        result += QLatin1String("MMM");

                    break;
                }

                case 'Y':
                {
                    if (!locale_indep_ordering) {
                        if (abbrev_next)
                            abbrev_year = true;
                        break;
                    }

                    if (!abbrev_next)
                        result += QLatin1String("yyyy");
                    else
                        result += QLatin1String("yy");

                    break;
                }

                case 'E':
                {
                    if (!abbrev_next)
                        result += QLatin1String("dddd");
                    else
                        result += QLatin1String("ddd");

                    break;
                }

                case ':':
                {
                    // timesep 0-3
                    ++i;
                    if (i >= sys_fmt.size())
                        break;

                    c = sys_fmt.at(i);
                    if (c.isDigit() && c.digitValue() <= 3) {
                        TChar s = locale->TimeSeparator(c.digitValue());
                        TUint val = s;
                        // some indexes return zero for empty
                        if (val > 0)
                            result += QChar(val);
                    }

                    break;
                }

                case 'J':
                {
                    if (tf == ETime24 && !abbrev_next)
                        result += QLatin1String("hh");
                    else
                        result += QLatin1Char('h');

                    break;
                }

                case 'H':
                {
                    if (!abbrev_next)
                        result += QLatin1String("hh");
                    else
                        result += QLatin1Char('h');

                    break;
                }

                case 'I':
                {
                    result += QLatin1Char('h');
                    break;
                }

                case 'T':
                {
                    if (!abbrev_next)
                        result += QLatin1String("mm");
                    else
                        result += QLatin1Char('m');

                    break;
                }

                case 'S':
                {
                    if (!abbrev_next)
                        result += QLatin1String("ss");
                    else
                        result += QLatin1Char('s');

                    break;
                }

                case 'B':
                {
                    // only done for 12h clock
                    if (tf == ETime24)
                        break;
                }

                    // fallthru to A
                case 'A': {
                    // quickie to get capitalization, can't use s60 string as is because Qt 'hh' format's am/pm logic
                    TAmPmName ampm = TAmPmName();
                    TChar first(ampm[0]);
                    QString qtampm = QString::fromLatin1(first.IsUpper() ? "AP" : "ap");

                    int pos = locale->AmPmSymbolPosition();

                    if ((minus_mode && pos != ELocaleBefore) ||
                        (plus_mode && pos != ELocaleAfter))
                        break;

                    if (!abbrev_next && locale->AmPmSpaceBetween()) {
                        if (pos == ELocaleBefore)
                            qtampm.append(QLatin1Char(' '));
                        else
                            qtampm.prepend(QLatin1Char(' '));
                    }

                    result += qtampm;
                    }
                    break;

                case '.': {
                        // decimal sep
                        TChar s = locale->DecimalSeparator();
                        TUint val = s;
                        if (val > 0)
                            result += QChar(val);
                    }
                    break;

                case 'C':
                {
                    // six digits in s60, three digits in qt
                    if (!abbrev_next) {
                        result += QLatin1String("zzz");
                    } else {
                        // next char is number from 0-6, how many digits to display
                        ++i;
                        if (i >= sys_fmt.size())
                            break;

                        c = sys_fmt.at(i);

                        if (c.isDigit()) {
                            // try to match wanted digits
                            QChar val(c.digitValue());

                            if (val >= 3) {
                                result += QLatin1String("zzz");
                            } else if (val > 0) {
                                result += QLatin1Char('z');
                            }
                        }
                    }
                    break;
                }

                // these cases fallthru
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                {

                    // shouldn't parse these with %F
                    if (locale_indep_ordering)
                        break;

                    TDateFormat df = locale->DateFormat();

                    const char **locale_dep;
                    switch (df) {
                        default:
                            df = EDateAmerican;
                            // fallthru to american
                        case EDateAmerican:
                            locale_dep = us_locale_dep;
                            break;
                        case EDateEuropean:
                            locale_dep = eu_locale_dep;
                            break;
                        case EDateJapanese:
                            locale_dep = jp_locale_dep;
                            break;
                    }
                    int offset = 0;
                    int adjustedDigit = c.digitValue() - 1;

                    bool abbrev_this = abbrev_next;
                    // If abbreviation specified for this digit, use that.
                    // Otherwise abbreviate according to %D, %M, and %Y specified previously.
                    if (!abbrev_this) {
                        switch (digit_map[adjustedDigit + (static_cast<int>(df) * 5)]) {
                            case 0:
                                abbrev_this = abbrev_day;
                                break;
                            case 1:
                                abbrev_this = abbrev_month;
                                break;
                            case 2:
                                abbrev_this = abbrev_year;
                                break;
                            default:
                                break; // never happens
                        }
                    }

                    if (abbrev_this)
                        offset += 5;
                    if (n_mode)
                        offset += 10;

                    result += QLatin1String(locale_dep[offset + (adjustedDigit)]);
                    break;
                }

                case '%': // fallthru percent
                {
                // any junk gets copied as is
                }
                default:
                {
                    result += c;
                    break;
                }

                case 'Z': // Qt doesn't support these :(
                case 'X':
                case 'W':
                {
                    break;
                }
            }
        } else {
            // double any single quotes, don't begin escape
            if (c.unicode() == '\'') {
                // end open escape
                if (open_escape) {
                    result += other;
                    other.clear();
                    result += QLatin1Char('\'');
                    open_escape = false;
                }

                other += c;
            }

            // gather chars and escape them in one go if any format chars are found
            if (!open_escape && qtformatchars.indexOf(c) != -1) {
                result += QLatin1Char('\'');
                open_escape = true;
            }
            other += c;
        }

        ++i;
    }

    if (!other.isEmpty())
        result += other;
    if (open_escape)
        result += QLatin1Char('\'');

    return result;
}
コード例 #17
0
ファイル: sym.cpp プロジェクト: cymerio/MuseScore
void initSymbols(int idx)
      {
      if (symbolsInitialized[idx])
            return;
      symbolsInitialized[idx] = true;
      symbols[idx] = QVector<Sym>(lastSym);

      symbols[idx][clefEightSym] = Sym(0x38, 2);
      symbols[idx][clefOneSym]   = Sym(0x31, 2);
      symbols[idx][clefFiveSym]  = Sym(0x35, 2);
      symbols[idx][letterTSym]   = Sym('T',  2);
      symbols[idx][letterSSym]   = Sym('S',  2);
      symbols[idx][letterPSym]   = Sym('P',  2);

      QString path;
#ifdef Q_WS_IOS
      {
      extern QString resourcePath();
      QString rpath = resourcePath();
      path = rpath + QString(idx == 0 ? "/mscore20.xml" : "/mscore/gonville.xml");
      }
#else
      path = idx == 0 ? ":/fonts/mscore20.xml" : ":/fonts/gonville.xml";
#endif
      QFile f(path);
      if (!f.open(QFile::ReadOnly)) {
            qDebug("cannot open symbols file %s\n", qPrintable(path));
            exit(-1);
            }
      XmlReader e(&f);
      int fid = idx == 0 ? 0 : 3;

      while (e.readNextStartElement()) {
            if (e.name() == "museScore") {
                  while (e.readNextStartElement()) {
                        if (e.name() == "Glyph") {
                              QString name;
                              int code = -1;
                              QPointF p;
                              QRectF b;
                              while (e.readNextStartElement()) {
                                    const QStringRef& tag(e.name());
                                    if (tag == "name")
                                          name = e.readElementText();
                                    else if (tag == "code") {
                                          QString val(e.readElementText());
                                          bool ok;
                                          code = val.mid(2).toInt(&ok, 16);
                                          if (!ok)
                                                qDebug("cannot read code");
                                          }
                                    else if (tag == "attach")
                                          p = e.readPoint();
                                    else if (tag == "bbox")
                                          b = e.readRect();
                                    else
                                          e.unknown();
                                    }
                              if (code == -1)
                                    qDebug("no code for glyph <%s>", qPrintable(name));
                              SymId idx1 = Sym::name2id(name);
                              if (idx1 != noSym)
                                    symbols[idx][idx1] = Sym(code, fid, p, b);
                              else {
                                    qDebug("symbol <%s> for symbol set %d not found in %s",
                                       qPrintable(name), idx, qPrintable(path));
                                    }
                              }
                        else
                              e.unknown();
                        }
                  }
            else
                  e.unknown();
            }
      for (int i = 0; i < lastSym; ++i) {
            Sym* sym = &symbols[idx][i];
            if (sym->code() == -1)
                  qDebug("no code for symbol %s", Sym::id2name(SymId(i)));
            }
      }
コード例 #18
0
void QNCLContourLine::getValueFromNode(QDomNode &node)
{
    QDomNodeList    childList;
    QDomElement     elem;
    QString         tagName;
    int             idx;
    QDomNode        childNode;
    QDomAttr        attr;
    QString         firstChildTagName;
    childList = node.childNodes();
    elem = node.toElement();
    tagName = elem.tagName();
    QString         lineNo;
    firstChildTagName = node.firstChild().toElement().tagName();
    if (tagName == QObject::tr("MapProject")) {
        elem = node.toElement();
        attr = elem.attributeNode(QObject::tr("value"));
        mapProject = attr.value();
        for (idx = 0; idx < childList.size(); idx ++) {
            childNode = childList.at(idx);
            getValueFromNode(childNode);
        }
        return;
    } else if (tagName == QObject::tr("LevelSelectionMode")) {
        elem = node.toElement();
        attr = elem.attributeNode(QObject::tr("value"));
        levelSelectionMode = attr.value();
        for (idx = 0; idx < childList.size(); idx ++) {
            childNode = childList.at(idx);
            getValueFromNode(childNode);
        }
        return;
    } else if (firstChildTagName.isNull() || firstChildTagName.isEmpty()) {
        if (tagName == QObject::tr("TemplateName")) {
            templateName = elem.text();
        } else if ((tagName == QObject::tr("ForegroundColor")) ||
                   (tagName == QObject::tr("BackgroundColor"))) {
            int color = elem.text().toInt();
            QColor val(color/65536, (color%65536)/256, color%256);
            if (tagName == QObject::tr("ForegroundColor"))
                foregroundColor = val;
            else
                backgroundColor = val;
        } else if (tagName == QObject::tr("Colormap")) {
            colormap = elem.text();
        } else if (tagName == QObject::tr("Polar")) {
            polarPosition = elem.text();
        }  else if (tagName == QObject::tr("MaxLevelCount")) {
            maxLevelCount = elem.text().toInt();
        } else if (tagName == QObject::tr("Width")) {
            width = elem.text().toInt();
        } else if (tagName == QObject::tr("Height")) {
            height = elem.text().toInt();
        } else if (tagName == QObject::tr("Left")) {
            leftLongitude = elem.text().toDouble();
        } else if (tagName == QObject::tr("Top")) {
            topLatitude = elem.text().toDouble();
        } else if (tagName == QObject::tr("Right")) {
            rightLongitude = elem.text().toDouble();
        } else if (tagName == QObject::tr("Bottom")) {
            bottomLatitude = elem.text().toDouble();
        } else if (tagName == QObject::tr("PlotMode")) {
            if (elem.text() == "Line")
                plotMode = 0;
            else
                plotMode = 1;
        } else if (tagName == QObject::tr("MonoColor")) {
            if (elem.text() == QObject::tr("true"))
                monoColor = true;
            else
                monoColor = false;
        } else if (tagName == QObject::tr("LineColor")) {
            lineColor = elem.text().toInt();
        } else if (tagName == QObject::tr("MonoFont")) {
            if (elem.text() == QObject::tr("true"))
                monoFont = true;
            else
                monoFont = false;
        } else if (tagName == QObject::tr("Font")) {
            font = elem.text();
        } else if (tagName == QObject::tr("MonoDashPattern")) {
            if (elem.text() == QObject::tr("true"))
                monoDashPattern = true;
            else
                monoDashPattern = false;
        } else if (tagName == QObject::tr("DashPattern")) {
            dashPattern = elem.text().toInt();
        } else if (tagName == QObject::tr("MonoFillPattern")) {
            if (elem.text() == QObject::tr("true"))
                monoFillPattern = true;
            else
                monoFillPattern = false;
        } else if (tagName == QObject::tr("FillPattern")) {
            fillPattern = elem.text().toInt();
        } else if (tagName == QObject::tr("MonoThickness")) {
            if (elem.text() == QObject::tr("true"))
                monoThickness = true;
            else
                monoThickness = false;
        } else if (tagName == QObject::tr("Thickness")) {
            thickness = elem.text().toDouble();
        } else if (tagName == QObject::tr("MinLevel")) {
            minLevel = elem.text().toDouble();
        } else if (tagName == QObject::tr("MaxLevel")) {
            maxLevel = elem.text().toDouble();
        } else if (tagName == QObject::tr("LevelSpacing")) {
            levelSpacing = elem.text().toDouble();
        } else if (tagName.left(4) == QObject::tr("Line") && tagName.right(5) == QObject::tr("Level")) {
            lineNo = tagName.mid(4);
            lineNo.truncate(lineNo.length()-5);
            lineLevels[lineNo.toInt()-1] = elem.text().toDouble();
        } else if (tagName.left(4) == QObject::tr("Line") && tagName.right(9) == QObject::tr("Thickness")) {
            lineNo = tagName.mid(4);
            lineNo.truncate(lineNo.length()-9);
            lineThicknesses[lineNo.toInt()-1] = elem.text().toDouble();
        } else if (tagName.left(4) == QObject::tr("Line") && tagName.right(5) == QObject::tr("Color")) {
            lineNo = tagName.mid(4);
            lineNo.truncate(lineNo.length()-5);
            lineColors[lineNo.toInt()-1] = elem.text().toInt();
        } else if (tagName.left(4) == QObject::tr("Line") && tagName.right(4) == QObject::tr("Font")) {
            lineNo = tagName.mid(4);
            lineNo.truncate(lineNo.length()-4);
            lineFont[lineNo.toInt()-1] = elem.text();
        } else if (tagName.left(4) == QObject::tr("Line") && tagName.right(11) == QObject::tr("DashPattern")) {
            lineNo = tagName.mid(4);
            lineNo.truncate(lineNo.length()-11);
            lineDashPatterns[lineNo.toInt()-1] = elem.text().toInt();
        } else if (tagName.left(4) == QObject::tr("Line") && tagName.right(11) == QObject::tr("FillPattern")) {
            lineNo = tagName.mid(4);
            lineNo.truncate(lineNo.length()-11);
            lineFillPatterns[lineNo.toInt()-1] = elem.text().toInt();
        }
    } else {
        for (idx = 0; idx < childList.size(); idx ++) {
            childNode = childList.at(idx);
            getValueFromNode(childNode);
        }
    }
}
コード例 #19
0
QoreValue QoreHashMapOperatorNode::evalValueImpl(bool& needs_deref, ExceptionSink* xsink) const {
   ValueEvalRefHolder arg_lst(e[2], xsink);
   if (*xsink || arg_lst->isNothing())
      return QoreValue();
   
   qore_type_t arglst_type = arg_lst->getType();
   assert(arglst_type != NT_NOTHING);
   ReferenceHolder<QoreHashNode> ret_val(ref_rv ? new QoreHashNode : 0, xsink);
   if (NT_LIST != arglst_type) { // Single value
      // check if it's an AbstractIterator object
      if (NT_OBJECT == arglst_type) {
         AbstractIteratorHelper h(xsink, "hmap operator select", 
				  const_cast<QoreObject*>(arg_lst->get<const QoreObject>()));
         if (*xsink)
	    return QoreValue();
         if (h)
            return mapIterator(h, xsink); // TODO!!
	 // passed iterator
      }

      // check if value can be mapped
      ReferenceHolder<> arg_ival(arg_lst.getReferencedValue(), xsink);
      SingleArgvContextHelper argv_helper(*arg_ival, xsink);
      ValueEvalRefHolder arg_key(e[0], xsink);
      if (*xsink)
	 return QoreValue();

      ValueEvalRefHolder arg_val(e[1], xsink);
      if (*xsink)
	 return QoreValue();

      // we have to convert to a string in the default encoding to use a hash key
      QoreStringValueHelper str_util(*arg_key, QCS_DEFAULT, xsink);
      if (*xsink)
	 return QoreValue();
      
      // Insert key-Value pair to the hash
      ret_val->setKeyValue(str_util->getBuffer(), arg_val.getReferencedValue(), xsink);
   }
   else {// List of values
      ConstListIterator li(arg_lst->get<const QoreListNode>());
      while (li.next()) {
         // set offset in thread-local data for "$#"
         ImplicitElementHelper eh(li.index()); 
         SingleArgvContextHelper argv_helper(li.getValue(), xsink);

	 {
	    ValueEvalRefHolder ekey(e[0], xsink);
	    if (*xsink)
	       return QoreValue();

	    // we have to convert to a string in the default encoding to use a hash key
	    QoreStringValueHelper key(*ekey, QCS_DEFAULT, xsink);
	    if (*xsink)
	       return QoreValue();
	    
	    ValueEvalRefHolder val(e[1], xsink);
	    if (*xsink)
	       return QoreValue();

	    if (ref_rv)
	       ret_val->setKeyValue(key->getBuffer(), val.getReferencedValue(), xsink);
	 }
	 // if there is an exception dereferencing one of the evaluted nodes above, then exit the loop
	 if (*xsink)
	    return QoreValue();
      }
   }
   if (*xsink || !ref_rv)
      return QoreValue();

   return ret_val.release();
}
コード例 #20
0
bool KJSEmbedPart::execute( KJS::Completion &result, const QString &script, const KJS::Value &self )
{
    KJS::Value val( self );
    result = js->evaluate( script, self.isNull() ? partobj : val );
    return (result.complType() == KJS::Normal) || (result.complType() == KJS::ReturnValue);
}
コード例 #21
0
ファイル: ext_std_process.cpp プロジェクト: DerPapst/hhvm
Variant HHVM_FUNCTION(proc_open,
                      const String& cmd,
                      const Array& descriptorspec,
                      VRefParam pipesParam,
                      const Variant& cwd /* = uninit_variant */,
                      const Variant& env /* = uninit_variant */,
                      const Variant& other_options /* = uninit_variant */) {
  if (RuntimeOption::WhitelistExec && !check_cmd(cmd.data())) {
    return false;
  }
  if (cmd.size() != strlen(cmd.c_str())) {
    raise_warning("NULL byte detected. Possible attack");
    return false;
  }
  Variant pipes(pipesParam, Variant::WithRefBind{});

  std::vector<DescriptorItem> items;

  std::string scwd = "";
  if (!cwd.isNull() && cwd.isString() && !cwd.asCStrRef().empty()) {
    scwd = cwd.asCStrRef().c_str();
  } else if (!g_context->getCwd().empty()) {
    scwd = g_context->getCwd().c_str();
  }

  Array enva;

  if (env.isNull()) {
    if (is_cli_mode()) {
      enva = cli_env();
    } else {
      // Build out an environment that conceptually matches what we'd
      // see if we were to iterate the environment and call getenv()
      // for each name.

      // Env vars defined in the hdf file go in first
      for (const auto& envvar : RuntimeOption::EnvVariables) {
        enva.set(String(envvar.first), String(envvar.second));
      }

      // global environment overrides the hdf
      for (char **env = environ; env && *env; env++) {
        char *p = strchr(*env, '=');
        if (p) {
          String name(*env, p - *env, CopyString);
          String val(p + 1, CopyString);
          enva.set(name, val);
        }
      }
    }

    // and then any putenv() changes take precedence
    for (ArrayIter iter(g_context->getEnvs()); iter; ++iter) {
      enva.set(iter.first(), iter.second());
    }
  } else {
    enva = env.toArray();
  }


#ifdef _WIN32
  PROCESS_INFORMATION pi;
  HANDLE childHandle;
  STARTUPINFO si;
  BOOL newprocok;
  SECURITY_ATTRIBUTES security;
  DWORD dwCreateFlags = 0;
  char *command_with_cmd;
  UINT old_error_mode;
  char cur_cwd[MAXPATHLEN];
  bool suppress_errors = false;
  bool bypass_shell = false;

  if (!other_options.isNull() && other_options.isArray()) {
    auto arr = other_options.asCArrRef();
    if (arr.exists(String("suppress_errors", CopyString), true)) {
      auto v = arr[String("suppress_errors", CopyString)];
      if ((v.isBoolean() && v.asBooleanVal()) ||
          (v.isInteger() && v.asInt64Val())) {
        suppress_errors = true;
      }
    }

    if (arr.exists(String("bypass_shell", CopyString), true)) {
      auto v = arr[String("bypass_shell", CopyString)];
      if ((v.isBoolean() && v.asBooleanVal()) ||
          (v.isInteger() && v.asInt64Val())) {
        bypass_shell = true;
      }
    }
  }

  /* we use this to allow the child to inherit handles */
  memset(&security, 0, sizeof(security));
  security.nLength = sizeof(security);
  security.bInheritHandle = true;
  security.lpSecurityDescriptor = nullptr;

  memset(&si, 0, sizeof(si));
  si.cb = sizeof(si);
  si.dwFlags = STARTF_USESTDHANDLES;

  si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
  si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  si.hStdError = GetStdHandle(STD_ERROR_HANDLE);

  if (!pre_proc_open(descriptorspec, items)) return false;
  /* redirect stdin/stdout/stderr if requested */
  for (size_t i = 0; i < items.size(); i++) {
    switch (items[i].index) {
      case 0:
        si.hStdInput = items[i].childend;
        break;
      case 1:
        si.hStdOutput = items[i].childend;
        break;
      case 2:
        si.hStdError = items[i].childend;
        break;
    }
  }


  memset(&pi, 0, sizeof(pi));

  if (suppress_errors) {
    old_error_mode = SetErrorMode(
      SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
  }

  dwCreateFlags = NORMAL_PRIORITY_CLASS;
  if (!RuntimeOption::ServerExecutionMode()) {
    dwCreateFlags |= CREATE_NO_WINDOW;
  }

  char *envp = build_envp(enva);
  if (bypass_shell) {
    newprocok = CreateProcess(
      nullptr,
      strdup(cmd.c_str()),
      &security,
      &security,
      TRUE,
      dwCreateFlags,
      envp,
      scwd.c_str(),
      &si,
      &pi);
  } else {
    std::string command_with = "cmd.exe /c ";
    command_with += cmd.toCppString();

    newprocok = CreateProcess(
      nullptr,
      strdup(command_with.c_str()),
      &security,
      &security,
      TRUE,
      dwCreateFlags,
      envp,
      scwd.c_str(),
      &si,
      &pi);
  }
  free(envp);

  if (suppress_errors) {
    SetErrorMode(old_error_mode);
  }

  if (newprocok == FALSE) {
    DWORD dw = GetLastError();
    char* msg;
    FormatMessageA(
      FORMAT_MESSAGE_ALLOCATE_BUFFER
        | FORMAT_MESSAGE_FROM_SYSTEM
        | FORMAT_MESSAGE_IGNORE_INSERTS,
      nullptr,
      dw,
      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
      (LPSTR)&msg,
      0,
      nullptr);

    /* clean up all the descriptors */
    for (size_t i = 0; i < items.size(); i++) {
      CloseHandle(items[i].childend);
      if (items[i].parentend) {
        CloseHandle(items[i].parentend);
      }
    }
    raise_warning("CreateProcess failed, error code - %u: %s", dw, msg);
    LocalFree(msg);
    return false;
  }

  childHandle = pi.hProcess;
  DWORD child = pi.dwProcessId;
  CloseHandle(pi.hThread);
  return post_proc_open(cmd, pipes, enva, items, (pid_t)child, childHandle);
#else
  pid_t child;

  if (LightProcess::Available()) {
    // light process available
    // there is no need to do any locking, because the forking is delegated
    // to the light process
    if (!pre_proc_open(descriptorspec, items)) return false;
    const int item_size = items.size();
    std::vector<int> created;
    created.reserve(item_size);
    std::vector<int> intended;
    intended.reserve(item_size);
    for (int i = 0; i < item_size; i++) {
      const auto& item = items[i];
      created.push_back(item.childend);
      intended.push_back(item.index);
    }

    std::vector<std::string> envs;
    for (ArrayIter iter(enva); iter; ++iter) {
      StringBuffer nvpair;
      nvpair.append(iter.first().toString());
      nvpair.append('=');
      nvpair.append(iter.second().toString());
      std::string tmp = nvpair.detach().c_str();
      if (tmp.find('\n') == std::string::npos) {
        envs.push_back(tmp);
      }
    }

    child = LightProcess::proc_open(cmd.c_str(), created, intended,
                                    scwd.c_str(), envs);
    assert(child);
    return post_proc_open(cmd, pipes, enva, items, child);
  } else {
    /* the unix way */
    Lock lock(DescriptorItem::s_mutex);
    if (!pre_proc_open(descriptorspec, items)) return false;
    child = fork();
    if (child) {
      // the parent process
      return post_proc_open(cmd, pipes, enva, items, child);
    }
  }

  assert(child == 0);
  /* this is the child process */

  /* close those descriptors that we just opened for the parent stuff,
   * dup new descriptors into required descriptors and close the original
   * cruft */
  for (auto& item : items) {
    item.dupChild();
  }
  if (scwd.length() > 0 && chdir(scwd.c_str())) {
    // chdir failed, the working directory remains unchanged
  }
  std::vector<String> senvs; // holding those char *
  char **envp = build_envp(enva, senvs);
  execle("/bin/sh", "sh", "-c", cmd.data(), nullptr, envp);
  free(envp);
  _exit(127);
#endif
}
コード例 #22
0
QMap<BindpointMap, QVector<BoundResource>> CommonPipelineState::GetReadWriteResources(
    ShaderStageType stage)
{
  QMap<BindpointMap, QVector<BoundResource>> ret;

  if(LogLoaded())
  {
    if(IsLogD3D11())
    {
      if(stage == eShaderStage_Compute)
      {
        for(int i = 0; i < m_D3D11->m_CS.UAVs.count; i++)
        {
          BindpointMap key(0, i);
          BoundResource val;

          val.Id = m_D3D11->m_CS.UAVs[i].Resource;
          val.HighestMip = (int)m_D3D11->m_CS.UAVs[i].HighestMip;
          val.FirstSlice = (int)m_D3D11->m_CS.UAVs[i].FirstArraySlice;
          val.typeHint = m_D3D11->m_CS.UAVs[i].Format.compType;

          ret[key] = {val};
        }
      }
      else
      {
        for(int i = 0; i < m_D3D11->m_OM.UAVs.count; i++)
        {
          BindpointMap key(0, i);
          BoundResource val;

          val.Id = m_D3D11->m_OM.UAVs[i].Resource;
          val.HighestMip = (int)m_D3D11->m_OM.UAVs[i].HighestMip;
          val.FirstSlice = (int)m_D3D11->m_OM.UAVs[i].FirstArraySlice;
          val.typeHint = m_D3D11->m_OM.UAVs[i].Format.compType;

          ret[key] = {val};
        }
      }
    }
    else if(IsLogD3D12())
    {
      const D3D12PipelineState::ShaderStage &s = GetD3D12Stage(stage);

      for(int space = 0; space < s.Spaces.count; space++)
      {
        for(int reg = 0; reg < s.Spaces[space].UAVs.count; reg++)
        {
          const D3D12PipelineState::ResourceView &bind = s.Spaces[space].UAVs[reg];
          BindpointMap key(space, reg);
          BoundResource val;

          val.Id = bind.Resource;
          val.HighestMip = (int)bind.HighestMip;
          val.FirstSlice = (int)bind.FirstArraySlice;
          val.typeHint = bind.Format.compType;

          ret[key] = {val};
        }
      }
    }
    else if(IsLogGL())
    {
      for(int i = 0; i < m_GL->Images.count; i++)
      {
        BindpointMap key(0, i);
        BoundResource val;

        val.Id = m_GL->Images[i].Resource;
        val.HighestMip = (int)m_GL->Images[i].Level;
        val.FirstSlice = (int)m_GL->Images[i].Layer;
        val.typeHint = m_GL->Images[i].Format.compType;

        ret[key] = {val};
      }
    }
    else if(IsLogVK())
    {
      const auto &descsets =
          stage == eShaderStage_Compute ? m_Vulkan->compute.DescSets : m_Vulkan->graphics.DescSets;

      ShaderStageBits mask = (ShaderStageBits)(1 << (int)stage);

      for(int set = 0; set < descsets.count; set++)
      {
        const auto &descset = descsets[set];
        for(int slot = 0; slot < descset.bindings.count; slot++)
        {
          const auto &bind = descset.bindings[slot];
          if((bind.type == eBindType_ReadWriteBuffer || bind.type == eBindType_ReadWriteImage ||
              bind.type == eBindType_ReadWriteTBuffer) &&
             (bind.stageFlags & mask) == mask)
          {
            BindpointMap key(set, slot);
            QVector<BoundResource> val(bind.descriptorCount);

            for(uint32_t i = 0; i < bind.descriptorCount; i++)
            {
              val[i].Id = bind.binds[i].res;
              val[i].HighestMip = (int)bind.binds[i].baseMip;
              val[i].FirstSlice = (int)bind.binds[i].baseLayer;
              val[i].typeHint = bind.binds[i].viewfmt.compType;
            }

            ret[key] = val;
          }
        }
      }
    }
  }

  return ret;
}
コード例 #23
0
ファイル: output.cpp プロジェクト: chriseppstein/libsass
  void Output::operator()(Ruleset* r)
  {
    Selector* s     = r->selector();
    Block*    b     = r->block();

    // Filter out rulesets that aren't printable (process its children though)
    if (!Util::isPrintable(r, output_style())) {
      for (size_t i = 0, L = b->length(); i < L; ++i) {
        Statement* stm = (*b)[i];
        if (dynamic_cast<Has_Block*>(stm)) {
          if (typeid(*stm) != typeid(Declaration)) {
            stm->perform(this);
          }
        }
      }
      return;
    }

    if (output_style() == NESTED) indentation += r->tabs();
    if (opt.source_comments) {
      std::stringstream ss;
      append_indentation();
      ss << "/* line " << r->pstate().line + 1 << ", " << r->pstate().path << " */";
      append_string(ss.str());
      append_optional_linefeed();
    }
    s->perform(this);
    append_scope_opener(b);
    for (size_t i = 0, L = b->length(); i < L; ++i) {
      Statement* stm = (*b)[i];
      bool bPrintExpression = true;
      // Check print conditions
      if (typeid(*stm) == typeid(Declaration)) {
        Declaration* dec = static_cast<Declaration*>(stm);
        if (dec->value()->concrete_type() == Expression::STRING) {
          String_Constant* valConst = static_cast<String_Constant*>(dec->value());
          std::string val(valConst->value());
          if (auto qstr = dynamic_cast<String_Quoted*>(valConst)) {
            if (!qstr->quote_mark() && val.empty()) {
              bPrintExpression = false;
            }
          }
        }
        else if (dec->value()->concrete_type() == Expression::LIST) {
          List* list = static_cast<List*>(dec->value());
          bool all_invisible = true;
          for (size_t list_i = 0, list_L = list->length(); list_i < list_L; ++list_i) {
            Expression* item = (*list)[list_i];
            if (!item->is_invisible()) all_invisible = false;
          }
          if (all_invisible) bPrintExpression = false;
        }
      }
      // Print if OK
      if (bPrintExpression) {
        stm->perform(this);
      }
    }
    if (output_style() == NESTED) indentation -= r->tabs();
    append_scope_closer(b);

  }
コード例 #24
0
ファイル: EBMLNumber.cpp プロジェクト: Azzuro/MediaPortal-1
char const* EBMLId::stringName() const {
  switch (val()) {
    case MATROSKA_ID_EBML: { return "EBML"; }
    case MATROSKA_ID_VOID: { return "Void"; }
    case MATROSKA_ID_CRC_32: { return "CRC-32"; }
    case MATROSKA_ID_SEGMENT: { return "Segment"; }
    case MATROSKA_ID_SEEK_HEAD: { return "Seek Head"; }
    case MATROSKA_ID_SEEK: { return "Seek"; }
    case MATROSKA_ID_SEEK_ID: { return "Seek ID"; }
    case MATROSKA_ID_SEEK_POSITION: { return "Seek Position"; }
    case MATROSKA_ID_INFO: { return "Segment Info"; }
    case MATROSKA_ID_SEGMENT_UID: { return "Segment UID"; }
    case MATROSKA_ID_DURATION: { return "Segment Duration"; }
    case MATROSKA_ID_TIMECODE_SCALE: { return "Timecode Scale"; }
    case MATROSKA_ID_DATE_UTC: { return "Date (UTC)"; }
    case MATROSKA_ID_TITLE: { return "Title"; }
    case MATROSKA_ID_MUXING_APP: { return "Muxing App"; }
    case MATROSKA_ID_WRITING_APP: { return "Writing App"; }
    case MATROSKA_ID_CLUSTER: { return "Cluster"; }
    case MATROSKA_ID_TIMECODE: { return "TimeCode"; }
    case MATROSKA_ID_POSITION: { return "Position"; }
    case MATROSKA_ID_PREV_SIZE: { return "Prev. Size"; }
    case MATROSKA_ID_SIMPLEBLOCK: { return "SimpleBlock"; }
    case MATROSKA_ID_BLOCK_GROUP: { return "Block Group"; }
    case MATROSKA_ID_BLOCK: { return "Block"; }
    case MATROSKA_ID_BLOCK_DURATION: { return "Block Duration"; }
    case MATROSKA_ID_REFERENCE_BLOCK: { return "Reference Block"; }
    case MATROSKA_ID_TRACKS: { return "Tracks"; }
    case MATROSKA_ID_TRACK_ENTRY: { return "Track Entry"; }
    case MATROSKA_ID_TRACK_NUMBER: { return "Track Number"; }
    case MATROSKA_ID_TRACK_UID: { return "Track UID"; }
    case MATROSKA_ID_TRACK_TYPE: { return "Track Type"; }
    case MATROSKA_ID_FLAG_ENABLED: { return "Flag Enabled"; }
    case MATROSKA_ID_FLAG_DEFAULT: { return "Flag Default"; }
    case MATROSKA_ID_FLAG_FORCED: { return "Flag Forced"; }
    case MATROSKA_ID_FLAG_LACING: { return "Flag Lacing"; }
    case MATROSKA_ID_MIN_CACHE: { return "Min Cache"; }
    case MATROSKA_ID_DEFAULT_DURATION: { return "Default Duration"; }
    case MATROSKA_ID_TRACK_TIMECODE_SCALE: { return "Track Timecode Scale"; }
    case MATROSKA_ID_MAX_BLOCK_ADDITION_ID: { return "Max Block Addition ID"; }
    case MATROSKA_ID_NAME: { return "Name"; }
    case MATROSKA_ID_LANGUAGE: { return "Language"; }
    case MATROSKA_ID_CODEC: { return "Codec ID"; }
    case MATROSKA_ID_CODEC_PRIVATE: { return "Codec Private"; }
    case MATROSKA_ID_CODEC_NAME: { return "Codec Name"; }
    case MATROSKA_ID_CODEC_DECODE_ALL: { return "Codec Decode All"; }
    case MATROSKA_ID_VIDEO: { return "Video Settings"; }
    case MATROSKA_ID_FLAG_INTERLACED: { return "Flag Interlaced"; }
    case MATROSKA_ID_PIXEL_WIDTH: { return "Pixel Width"; }
    case MATROSKA_ID_PIXEL_HEIGHT: { return "Pixel Height"; }
    case MATROSKA_ID_DISPLAY_WIDTH: { return "Display Width"; }
    case MATROSKA_ID_DISPLAY_HEIGHT: { return "Display Height"; }
    case MATROSKA_ID_DISPLAY_UNIT: { return "Display Unit"; }
    case MATROSKA_ID_AUDIO: { return "Audio Settings"; }
    case MATROSKA_ID_SAMPLING_FREQUENCY: { return "Sampling Frequency"; }
    case MATROSKA_ID_OUTPUT_SAMPLING_FREQUENCY: { return "Output Sampling Frequency"; }
    case MATROSKA_ID_CHANNELS: { return "Channels"; }
    case MATROSKA_ID_BIT_DEPTH: { return "Bit Depth"; }
    case MATROSKA_ID_CONTENT_ENCODINGS: { return "Content Encodings"; }
    case MATROSKA_ID_CONTENT_ENCODING: { return "Content Encoding"; }
    case MATROSKA_ID_CONTENT_COMPRESSION: { return "Content Compression"; }
    case MATROSKA_ID_CONTENT_COMP_ALGO: { return "Content Compression Algorithm"; }
    case MATROSKA_ID_CONTENT_COMP_SETTINGS: { return "Content Compression Settings"; }
    case MATROSKA_ID_CONTENT_ENCRYPTION: { return "Content Encryption"; }
    case MATROSKA_ID_ATTACHMENTS: { return "Attachments"; }
    case MATROSKA_ID_ATTACHED_FILE: { return "Attached File"; }
    case MATROSKA_ID_FILE_DESCRIPTION: { return "File Description"; }
    case MATROSKA_ID_FILE_NAME: { return "File Name"; }
    case MATROSKA_ID_FILE_MIME_TYPE: { return "File MIME Type"; }
    case MATROSKA_ID_FILE_DATA: { return "File Data"; }
    case MATROSKA_ID_FILE_UID: { return "File UID"; }
    case MATROSKA_ID_CUES: { return "Cues"; }
    case MATROSKA_ID_CUE_POINT: { return "Cue Point"; }
    case MATROSKA_ID_CUE_TIME: { return "Cue Time"; }
    case MATROSKA_ID_CUE_TRACK_POSITIONS: { return "Cue Track Positions"; }
    case MATROSKA_ID_CUE_TRACK: { return "Cue Track"; }
    case MATROSKA_ID_CUE_CLUSTER_POSITION: { return "Cue Cluster Position"; }
    case MATROSKA_ID_CUE_BLOCK_NUMBER: { return "Cue Block Number"; }
    case MATROSKA_ID_TAGS: { return "Tags"; }
    case MATROSKA_ID_SEEK_PRE_ROLL: { return "SeekPreRoll"; }
    case MATROSKA_ID_CODEC_DELAY: { return "CodecDelay"; }
    case MATROSKA_ID_DISCARD_PADDING: { return "DiscardPadding"; }
    default: { return "*****unknown*****"; }
  }
}
コード例 #25
0
ファイル: resourcemanager.cpp プロジェクト: DYFeng/infinidb
bool ResourceManager::queryStatsEnabled() const
{
	std::string val(getStringVal("QueryStats", "Enabled", "N" ));
	boost::to_upper(val);
	return "Y" == val;
}
コード例 #26
0
ファイル: type_array.cpp プロジェクト: 524777134/hiphop-php
Array Array::diffImpl(CArrRef array, bool by_key, bool by_value, bool match,
                      PFUNC_CMP key_cmp_function,
                      const void *key_data,
                      PFUNC_CMP value_cmp_function,
                      const void *value_data) const {
  assert(by_key || by_value);
  assert(by_key || key_cmp_function == nullptr);
  assert(by_value || value_cmp_function == nullptr);
  PFUNC_CMP value_cmp_as_string_function = value_cmp_function;
  if (!value_cmp_function) {
    value_cmp_function = SortStringAscending;
    value_cmp_as_string_function = CompareAsStrings;
  }

  Array ret = Array::Create();
  if (by_key && !key_cmp_function) {
    // Fast case
    for (ArrayIter iter(*this); iter; ++iter) {
      Variant key(iter.first());
      CVarRef value(iter.secondRef());
      bool found = false;
      if (array->exists(key)) {
        if (by_value) {
          found = value_cmp_as_string_function(
            value, array.rvalAt(key, AccessFlags::Key), value_data) == 0;
        } else {
          found = true;
        }
      }
      if (found == match) {
        ret.addLval(key, true).setWithRef(value);
      }
    }
    return ret;
  }

  if (!key_cmp_function) {
    key_cmp_function = SortRegularAscending;
  }

  vector<int> perm1;
  SortData opaque1;
  int bottom = 0;
  int top = array.size();
  PFUNC_CMP cmp;
  const void *cmp_data;
  if (by_key) {
    cmp = key_cmp_function;
    cmp_data = key_data;
  } else {
    cmp = value_cmp_function;
    cmp_data = value_data;
  }
  SortImpl(perm1, array, opaque1, cmp, by_key, cmp_data);

  for (ArrayIter iter(*this); iter; ++iter) {
    Variant target;
    if (by_key) {
      target = iter.first();
    } else {
      target = iter.second();
    }

    int mid = -1;
    int min = bottom;
    int max = top;
    while (min < max) {
      mid = (max + min) / 2;
      ssize_t pos = opaque1.positions[perm1[mid]];
      int cmp_res =  cmp(target,
                         by_key ? array->getKey(pos)
                                : array->getValueRef(pos),
                         cmp_data);
      if (cmp_res > 0) { // outer is bigger
        min = mid + 1;
      } else if (cmp_res == 0) {
        break;
      } else {
        max = mid;
      }
    }
    bool found = false;
    if (min < max) { // found
      // if checking both, check value
      if (by_key && by_value) {
        CVarRef val(iter.secondRef());
        // Have to look up and down for matches
        for (int i = mid; i < max; i++) {
          ssize_t pos = opaque1.positions[perm1[i]];
          if (key_cmp_function(target, array->getKey(pos), key_data) != 0) {
            break;
          }
          if (value_cmp_as_string_function(val, array->getValueRef(pos),
                                           value_data) == 0) {
            found = true;
            break;
          }
        }
        if (!found) {
          for (int i = mid-1; i >= min; i--) {
            ssize_t pos = opaque1.positions[perm1[i]];
            if (key_cmp_function(target, array->getKey(pos), key_data) != 0) {
              break;
            }
            if (value_cmp_as_string_function(val, array->getValueRef(pos),
                                             value_data) == 0) {
              found = true;
              break;
            }
          }
        }
      } else {
        // found at mid
        found = true;
      }
    }

    if (found == match) {
      ret.addLval(iter.first(), true).setWithRef(iter.secondRef());
    }
  }
  return ret;
}
コード例 #27
0
ファイル: DexCalc.cpp プロジェクト: onlyuser/Legacy
float DexCalc::getVar(std::string var)
{
	std::map<std::string, std::string> *varTable;
	if ((varTable = this->loadVarTable(var)) != NULL)
		return val((*varTable)[var]);
}
コード例 #28
0
ファイル: Register.c プロジェクト: ptII/ptII
/***preinitBlock_hasInitialValue($channel)***/
static $targetType(output) $actorSymbol(storedValue_$channel) = ($targetType(output)) $val(initialValue);
static unsigned int $actorSymbol(storedValue_$channel_hasValue) = 1;
/**/

/***preinitBlock_noInitialValue($channel)***/
static $targetType(output) $actorSymbol(storedValue_$channel);
static unsigned int $actorSymbol(storedValue_$channel_hasValue) = 0;
/**/

/***triggerBlock($channel)***/
if ($hasToken(trigger) && $actorSymbol(storedValue_$channel_hasValue)) {
        $put(output#$channel, $actorSymbol(storedValue_$channel))
}
/**/

/***updateValueBlock($channel)***/
if ($hasToken(input#$channel)) {
        $actorSymbol(storedValue_$channel) = ($targetType(output)) $get(input#$channel);
        $actorSymbol(storedValue_$channel_hasValue) = 1;
}
/**/
コード例 #29
0
ファイル: fourcc.cpp プロジェクト: CharlesLio/mkvtoolnix
size_t
fourcc_c::write(mm_io_c *io,
                fourcc_c::byte_order_t byte_order) {
  return io->write_uint32_be(val(m_value, byte_order));
}
コード例 #30
0
void GdsRenderStateGroup::SetSamplerState( int index , int iop1 , int iop2 )
{	
	VALUE val( iop1 , iop2 );
	MULTI_VALUE multi_value( index , val );
	m_Opt_SamplerState.push_back( multi_value );
}