예제 #1
0
bool isAlive(T & p, std::function<void(typename toShared<T>::type &)> func){
	return isTrue(p, func, &IAgent::isAlive);
}
예제 #2
0
void isVisible(std::vector<T> & v, std::function<void(typename toShared<T>::type &)> func){
	isTrue(v, func, &IDrawer::isVisible);
}
예제 #3
0
bool isAlive(T & p){
	return isTrue(p, &IAgent::isAlive);
}
예제 #4
0
파일: object.cpp 프로젝트: jinrenlab/ink
Ink_Object *InkNative_Object_Not(Ink_InterpreteEngine *engine, Ink_ContextChain *context, Ink_ArgcType argc, Ink_Object **argv, Ink_Object *this_p)
{
	Ink_Object *base = context->searchSlot(engine, "base");
	return isTrue(base) ? new Ink_Numeric(engine, 0) : new Ink_Numeric(engine, 1);
}
예제 #5
0
bool isVisible(T & p, std::function<void(typename toShared<T>::type &)> func){
	return isTrue(p, func, &IDrawer::isVisible);
}
예제 #6
0
bool isValid(T & p, std::function<void(typename toShared<T>::type &)> func){
	return isTrue(p, func, &IModel::isValid);
}
예제 #7
0
bool isVisible(T & p){
	return isTrue(p, &IDrawer::isVisible);
}
예제 #8
0
void JSValue::dumpInContextAssumingStructure(
    PrintStream& out, DumpContext* context, Structure* structure) const
{
    if (!*this)
        out.print("<JSValue()>");
    else if (isInt32())
        out.printf("Int32: %d", asInt32());
    else if (isDouble()) {
#if USE(JSVALUE64)
        out.printf("Double: %lld, %lf", (long long)reinterpretDoubleToInt64(asDouble()), asDouble());
#else
        union {
            double asDouble;
            uint32_t asTwoInt32s[2];
        } u;
        u.asDouble = asDouble();
        out.printf("Double: %08x:%08x, %lf", u.asTwoInt32s[1], u.asTwoInt32s[0], asDouble());
#endif
    } else if (isCell()) {
        if (structure->classInfo()->isSubClassOf(JSString::info())) {
            JSString* string = jsCast<JSString*>(asCell());
            out.print("String");
            if (string->isRope())
                out.print(" (rope)");
            const StringImpl* impl = string->tryGetValueImpl();
            if (impl) {
                if (impl->isAtomic())
                    out.print(" (atomic)");
                if (impl->isAtomic())
                    out.print(" (identifier)");
                if (impl->isSymbol())
                    out.print(" (symbol)");
            } else
                out.print(" (unresolved)");
            out.print(": ", impl);
        } else if (structure->classInfo()->isSubClassOf(Symbol::info()))
            out.print("Symbol: ", RawPointer(asCell()));
        else if (structure->classInfo()->isSubClassOf(Structure::info()))
            out.print("Structure: ", inContext(*jsCast<Structure*>(asCell()), context));
        else if (structure->classInfo()->isSubClassOf(JSObject::info())) {
            out.print("Object: ", RawPointer(asCell()));
            out.print(" with butterfly ", RawPointer(asObject(asCell())->butterfly()));
            out.print(" (", inContext(*structure, context), ")");
        } else {
            out.print("Cell: ", RawPointer(asCell()));
            out.print(" (", inContext(*structure, context), ")");
        }
#if USE(JSVALUE64)
        out.print(", ID: ", asCell()->structureID());
#endif
    } else if (isTrue())
        out.print("True");
    else if (isFalse())
        out.print("False");
    else if (isNull())
        out.print("Null");
    else if (isUndefined())
        out.print("Undefined");
    else
        out.print("INVALID");
}
예제 #9
0
/* ****************************************************************************
*
* isPatternIsTrue - 
*/
bool EntityId::isPatternIsTrue(void)
{
  return isTrue(isPattern);
}
예제 #10
0
bool BkgdObsSplineLoader::loadBkgdObs(QList<real> &bgIn)
{
  // Turn Debug on if there are problems with the vertical spline interpolation,
  // Eventually this should be replaced with the internal spline code
  // SplineD::Debug(1);

  // Geographic functions
  // GeographicLib::TransverseMercatorExact tm = GeographicLib::TransverseMercatorExact::UTM();

  real referenceLon = configHash->value("ref_lon").toFloat();

  int time;
  real lat, lon, alt, u, v, w, t, qv, rhoa, qr;
  
  real Pi = acos(-1);

  bool debugDomain = isTrue("debug_domain");
  
  // bgZ = -32768.;  TODO. What was that about?
  
  // background is in km, ROI is gridpoints
  
  iROI = configHash->value("i_background_roi").toFloat() / iincr;
  jROI = configHash->value("j_background_roi").toFloat() / jincr;
  maxGridDist = 3.0;
  
  QString interp_mode = configHash->value("bg_interpolation");
  if (interp_mode == "Cressman")
    maxGridDist = 1.0;

  if (frameVector.size() == 0) {
    std::cout << "Frame Vector is not initialized."  << std::endl;
    return false;
  }
    
  std::cout << "Loading background onto Gaussian mish with " << iROI
	    << " grid length radius of influence in i direction" << std::endl;
  std::cout << "and " << jROI << " grid length radius of influence in j direction" << std::endl;

  QDateTime startTime = frameVector.front().getTime();
  QDateTime endTime = frameVector.back().getTime();
  
  std::cout << "Start time: " << startTime.toTime_t() << " "
	    << startTime.toString("yyyy-MM-dd-HH:mm:ss").toLatin1().data() << std::endl;
  std::cout << "End  time:  " << endTime.toTime_t()  << " "
	    << endTime.toString("yyyy-MM-dd-HH:mm:ss").toLatin1().data() << std::endl;

  int timeProblem = 0;
  int domainProblem = 0;
  int radiusProblem = 0;
  int levelProblem = 0;
  int splineProblem = 0;

  std::cout << "iROI: " << iROI << ", jROI: " << jROI << ", maxGridDist: "
	    << maxGridDist << std::endl;
  std::cout << "imin: " << imin << ", iincr: " << iincr << std::endl;
  std::cout << "jmin: " << jmin << ", jincr: " << jincr << std::endl;
  std::cout << "kmin: " << kmin << ", kincr: " << kincr << std::endl;
  
  while( bkgdAdapter->next(time, lat, lon, alt, u, v, w, t, qv, rhoa, qr) ) {
    int tci;
    if (! timeCheck(time, startTime, endTime, tci)) {
      timeProblem++;
      continue;
    }
      
    real Um = frameVector[tci].getUmean();
    real Vm = frameVector[tci].getVmean();

    // Get the X, Y & Z
    real tcX, tcY, metX, metY;
    projection.Forward(referenceLon, frameVector[tci].getLat() , frameVector[tci].getLon(),
		       tcX, tcY);
    projection.Forward(referenceLon, lat, lon , metX, metY);
    bgX = (metX - tcX) / 1000.;
    bgY = (metY - tcY) / 1000.;

    real heightm = (alt > 10.0) ? alt : 10;	// don't want to take log of zero below...
    
    bgZ = heightm / 1000.;
    bgRadius = sqrt(bgX * bgX + bgY * bgY);
    bgTheta = 180.0 * atan2(bgY, bgX) / Pi;
    if (configHash->value("allow_negative_angles") != "true")
      if (bgTheta < 0)
	bgTheta += 360.0;

    // Make sure the ob is in the Interpolation domain
    
    if (runMode == RUN_MODE_XYZ) {
      if ((bgX < (imin - iincr - (iROI * iincr * maxGridDist))) or
	  (bgX > (imax + iincr + (iROI * iincr * maxGridDist))) or
	  (bgY < (jmin - jincr - (jROI * jincr * maxGridDist))) or
	  (bgY > (jmax + jincr + (jROI * jincr * maxGridDist))) or
	  (bgZ < kmin)) { //Allow for higher values for interpolation purposes
	domainProblem++;
	if (debugDomain)
	  std::cout << "bgX: " << bgX << " bgY: " << bgY << " bgZ: " << bgZ << std::endl;
	continue;
      }
    } else if (runMode == RUN_MODE_RTZ) {
      if ((bgRadius < (imin - iincr - (iROI * iincr * maxGridDist))) or
	  (bgRadius > (imax + iincr + (iROI * iincr * maxGridDist))) or
	  (bgTheta < jmin - jincr - (jROI * jincr * maxGridDist)) or
	  (bgTheta > jmax + jincr + (jROI * jincr * maxGridDist)) or
	  (bgZ < kmin)) { //Exceeding the Theta domain only makes sense for sectors
	domainProblem++;
	continue;
      }
      real cylUm = (Um * bgX + Vm * bgY) / bgRadius;
      real cylVm = (-Um * bgY + Vm * bgX) / bgRadius;
      Um = cylUm;
      Vm = cylVm;
    }

    // Reference states
    real rhoBar = refstate->getReferenceVariable(ReferenceVariable::rhoaref, heightm);
    real qBar = refstate->getReferenceVariable(ReferenceVariable::qvbhypref, heightm);
    real tBar = refstate->getReferenceVariable(ReferenceVariable::tempref, heightm);

    real rho = rhoa + rhoa * qv / 1000.;
    real rhou = rho * (u - Um);
    real rhov = rho * (v - Vm);
    real rhow = rho * w;
    real tprime = t - tBar;
    qv = refstate->bhypTransform(qv);
    real qvprime = qv - qBar;
    real rhoprime = (rhoa - rhoBar) * 100;
    real logZ = log(bgZ);
    
    if (configHash->value("qr_variable") == "qr")
      qr = refstate->bhypTransform(qr);
    
    // We assume here that the background precipitation field is always zero
    // real qr = 0.;

    if (runMode == RUN_MODE_XYZ) {
      bgIn << bgX << bgY << logZ << time << rhou << rhov << rhow << tprime << qvprime << rhoprime << qr ;
    } else if (runMode == RUN_MODE_RTZ)
      bgIn << bgRadius << bgTheta << logZ << time << rhou << rhov << rhow << tprime
	   << qvprime << rhoprime << qr ;

    // Push values for an entire column, then solve for the spline
    
    if ( (logheights.size() != 0) && (logZ <= logheights.back()) ) {
      // Not first level, not same column, Solve for the spline
      if (logheights.size() == 1) {
	std::cerr << "Error at " << lat << ", " << lon << ", " << bgZ << std::endl
		  << "Only one level found in background spline setup. " << std::endl
		  << "Please check Background.in to ensure sorting by descending Z coordinate and re-run."
		  << std::endl;
	levelProblem++;
	return false;
      }
      splineSolver(0);	// This will also clear logheights, uBG, vBG, ...
    }
    
    logheights.push_back(logZ);
    uBG.push_back(rhou);
    vBG.push_back(rhov);
    wBG.push_back(rhow);
    tBG.push_back(tprime);
    qBG.push_back(qvprime);
    rBG.push_back(rhoprime);
    zBG.push_back(qr);
    
  } // each obs

  std::cout << "timeProblem: " << timeProblem << ", domainProblem: " << domainProblem
       << ", radiusProblem: " << radiusProblem << ", levelProblem: " << levelProblem
       << ", splineProblem: " << splineProblem
       << std::endl;

  if (!logheights.size()) {
    // Error reading in the background field
    std::cout << "No background estimates read in. "
	 << "Please check the time and location of your background field.\n";
#if 0
    std::cout << "Observation window: " << tcstart.toStdString() << " to " << tcend.toStdString() << "\n";
    std::cout << "Background time: " << bgTimestring.toStdString() << "\n";
#endif
    return false;
  }

  // std::cout << "------------------------2\n";
  
  // Solve for the last spline
  if (logheights.size() == 1) {
    std::cerr << "Only one level found in background spline setup. "
	 << "Please check Background.in to ensure sorting by Z coordinate and re-run." << std::endl;
    return false;
  }

  // Exponential interpolation in horizontal, b-Spline interpolation on log height in vertical

  splineSolver(2);  // This will also clear logheights, uBG, vBG, ...

  int numbgObs = bgIn.size() / 11; // 11 entries per ob
  if (isTrue("debug_bgIn"))
    dumpBgIn(0, numbgObs, bgIn);
      
  QVector<int> emptybg;

  // TODO Do we need to check interpolation and fill hole for KD too?
  // bgWeight is a byproduct of calling the spline solver, so that's not available.
  // what about fill holes? It depends on emptyBg which is also a byproduct of the spline solver.
  
  // Check interpolation
  
  if (numbgObs > 0) {
    
    START_TIMER(timeci);

    for (int ki = -1; ki < (kdim); ki++) {
      for (int kmu = -1; kmu <= 1; kmu += 2) {
	real kPos = kmin + kincr * (ki + (0.5 * sqrt(1. / 3.) * kmu + 0.5));
	
	for (int ii = -1; ii < (idim); ii++) {
	  for (int imu = -1; imu <= 1; imu += 2) {
	    real iPos = imin + iincr * (ii + (0.5 * sqrt(1. / 3.) * imu + 0.5));
	    
	    for (int ji = -1; ji < (jdim); ji++) {
	      for (int jmu = -1; jmu <= 1; jmu += 2) {
		real jPos = jmin + jincr * (ji + (0.5 * sqrt(1. / 3.) * jmu + 0.5));
		
		int bgI = (ii + 1) * 2 + (imu + 1) / 2;
		int bgJ = (ji + 1) * 2 + (jmu + 1) / 2;
		int bgK = (ki + 1) * 2 + (kmu + 1) / 2;
		
		int bIndex = numVars * (idim + 1) * 2 * (jdim + 1) * 2 * bgK
		  + numVars * (idim + 1) * 2 * bgJ + numVars * bgI;

		for (unsigned int var = 0; var < numVars; var++) {
		  if (bgWeights[bIndex] != 0) {
		    bgU[bIndex + var] /= bgWeights[bIndex];
		  } else {
		    emptybg.push_back(bIndex);
		    if (emptybg.size() < 15) {
		      std::cout << "Empty background mish for variable "
				<< var << " at " << iPos << ", " << jPos << ", " << kPos << std::endl;
		    } else if (emptybg.size() == 15) {
		      std::cout << "Too many empty mish points, will no longer report.\n";
		    }
		  }
		}
		if (configHash->value("qr_variable") == "dbz") {
		  if (bgU[bIndex + 6] > 0) {
		    real dbzavg = 10 * log10(bgU[bIndex + 6]);
		    bgU[bIndex + 6] = (dbzavg + 35.) * 0.1;
		  } else {
		    bgU[bIndex + 6] = 0.0;
		  }
		}
	      }
	    }
	  }
	}
      }
    }

    fillHoles(emptybg);
    
    PRINT_TIMER("Interpolation check", timeci);
  } else {
    std::cout << "No background observations loaded" << std::endl;
    return false;
  }

  std::cout << numbgObs << " background observations loaded" << std::endl;

  if (isTrue("debug_bgU")) {
    dumpBgU(0, uStateSize, bgU);
  }

  if (configHash->contains("debug_bgU_nc"))
    bgu2nc(configHash->value("debug_bgU_nc").toLatin1().data(), bgU);
  
  return true;
}
예제 #11
0
bool BkgdObsKDLoader::loadBkgdObs(QList<real> &bgIn)
{
  int time;
  real lat, lon, alt, u, v, w, t, qv, rhoa, qr;
  real Pi = acos(-1);

  KD_tree *kdTree;

  QDateTime startTime = frameVector.front().getTime();
  QDateTime endTime = frameVector.back().getTime();

  std::cout << "Start time: " << startTime.toTime_t() << " "
	    << startTime.toString("yyyy-MM-dd-HH:mm:ss").toLatin1().data() << std::endl;
  std::cout << "End  time:  " << endTime.toTime_t()  << " "
	    << endTime.toString("yyyy-MM-dd-HH:mm:ss").toLatin1().data() << std::endl;
  
  // background is in km, ROI is gridpoints
  // TODO that comment doesn't seem correct. These are set to 45.0 in the config file...
  
  iROI = configHash->value("i_background_roi").toFloat() / iincr;
  jROI = configHash->value("j_background_roi").toFloat() / jincr;

  maxGridDist = 3.0;
  
  int timeProblem = 0;
  int domainProblem = 0;

  int debugKd = 0;
  if (configHash->contains("debug_kd") ) {
    debugKd = configHash->value("debug_kd").toInt();
    std::cout << "*** dbugKD: " << debugKd << std::endl;    
  }

  int debugKdStep = 0;
  if (configHash->contains("debug_kd_step") ) {
    debugKdStep = configHash->value("debug_kd_step").toInt();
    std::cout << "*** Debug KD Step: " << debugKdStep << std::endl;
  }
  
  while( bkgdAdapter->next(time, lat, lon, alt, u, v, w, t, qv, rhoa, qr) ) {
    // Process the bkgdObs into Observations
    int tci;
    if (! timeCheck(time, startTime, endTime, tci)) {
      timeProblem++;
      continue;
    }
      
    real Um = frameVector[tci].getUmean();
    real Vm = frameVector[tci].getVmean();

    // Get the X, Y & Z
    real tcX, tcY, metX, metY;
    real referenceLon = configHash->value("ref_lon").toFloat();
    
    projection.Forward(referenceLon, frameVector[tci].getLat() , frameVector[tci].getLon(),
		       tcX, tcY);
    projection.Forward(referenceLon, lat, lon , metX, metY);
    bgX = (metX - tcX) / 1000.;
    bgY = (metY - tcY) / 1000.;

    real heightm = (alt > 10.0) ? alt : 10;	// don't want to take log of zero below...
    
    bgZ = heightm / 1000.;
    bgRadius = sqrt(bgX * bgX + bgY * bgY);
    bgTheta = 180.0 * atan2(bgY, bgX) / Pi;
    if (configHash->value("allow_negative_angles") != "true")
      if (bgTheta < 0)
	bgTheta += 360.0;

    // Make sure the ob is in the Interpolation domain
    
    if (runMode == RUN_MODE_XYZ) {
      if ((bgX < (imin - iincr - (iROI * iincr * maxGridDist))) or
	  (bgX > (imax + iincr + (iROI * iincr * maxGridDist))) or
	  (bgY < (jmin - jincr - (jROI * jincr * maxGridDist))) or
	  (bgY > (jmax + jincr + (jROI * jincr * maxGridDist))) or
	  (bgZ < kmin)) { //Allow for higher values for interpolation purposes
	domainProblem++;
	continue;
      }
    } else if (runMode == RUN_MODE_RTZ) {
      if ((bgRadius < (imin - iincr - (iROI * iincr * maxGridDist))) or
	  (bgRadius > (imax + iincr + (iROI * iincr * maxGridDist))) or
	  (bgTheta < jmin - jincr - (jROI * jincr * maxGridDist)) or
	  (bgTheta > jmax + jincr + (jROI * jincr * maxGridDist)) or
	  (bgZ < kmin)) { //Exceeding the Theta domain only makes sense for sectors
	domainProblem++;
	continue;
      }
      real cylUm = (Um * bgX + Vm * bgY) / bgRadius;
      real cylVm = (-Um * bgY + Vm * bgX) / bgRadius;
      Um = cylUm;
      Vm = cylVm;
    }

    // Reference states
    real rhoBar = refstate->getReferenceVariable(ReferenceVariable::rhoaref, heightm);
    real qBar = refstate->getReferenceVariable(ReferenceVariable::qvbhypref, heightm);
    real tBar = refstate->getReferenceVariable(ReferenceVariable::tempref, heightm);

    real rho = rhoa + rhoa * qv / 1000.;
    real rhou = rho * (u - Um);
    real rhov = rho * (v - Vm);
    real rhow = rho * w;
    real tprime = t - tBar;
    qv = refstate->bhypTransform(qv);
    real qvprime = qv - qBar;
    real rhoprime = (rhoa - rhoBar) * 100;
    real logZ = log(bgZ);

    if (configHash->value("qr_variable") == "qr")
      qr = refstate->bhypTransform(qr);
    
    // We assume here that the background precipitation field is always zero
    // real qr = 0.;

    if (runMode == RUN_MODE_XYZ) {
      bgIn << bgX << bgY << logZ << time << rhou << rhov << rhow << tprime << qvprime << rhoprime << qr ;
    } else if (runMode == RUN_MODE_RTZ)
      bgIn << bgRadius << bgTheta << logZ << time << rhou << rhov << rhow << tprime
	   << qvprime << rhoprime << qr;

  } // each obs

  std::cout << "timeProblem: " << timeProblem << ", domainProblem: " << domainProblem
            << std::endl;
  
  int numbgObs = bgIn.size() / 11; // 11 entries per ob
  
  if (numbgObs <= 0) {
    std::cout << "No background observations loaded" << std::endl;
    return false;
  }
  
  std::cout << numbgObs << " background observations loaded" << std::endl;
  
  if (isTrue("debug_bgIn"))
    dumpBgIn(0, numbgObs, bgIn);

  // All the obs are now loaded in bgIn. Build a KD tree
  
  kdTree = buildKDTree(bgIn);
  QVector<int> emptybg;
  
  KD_real *centerLoc = new KD_real[3];	// 3 dim
  int nbrMax  = configHash->value("bkgd_kd_num_neighbors").toInt();
  if (nbrMax <= 0) {
    std::cerr << "Number of neighbors must be greater than 0." << std::endl;
    return false;
  }
  float maxDist = configHash->value("bkgd_kd_max_distance").toFloat();
  // KD tree returns the square of the distance...
  maxDist *= maxDist;

  // For each point on the mish

  std::cout << "*** idim: " << idim << ", jdim: " << jdim << ", kdim: " << kdim << std::endl;
  
  if (debugKd)
    std::cout << "--- start of debug kd" << std::endl;
  
  for (int ii = -1; ii < (idim); ii++) {
    for (int imu = -1; imu <= 1; imu += 2) {
      real iPos = imin + iincr * (ii + (0.5 * sqrt(1. / 3.) * imu + 0.5));
	    
      for (int ji = -1; ji < (jdim); ji++) {
	for (int jmu = -1; jmu <= 1; jmu += 2) {
	  real jPos = jmin + jincr * (ji + (0.5 * sqrt(1. / 3.) * jmu + 0.5));
		
	  for (int ki = -1; ki < (kdim); ki++) {
	    for (int kmu = -1; kmu <= 1; kmu += 2) {
	      real kPos = kmin + kincr * (ki + (0.5 * sqrt(1. / 3.) * kmu + 0.5));
	
	      int bgI = (ii + 1) * 2 + (imu + 1) / 2;
	      int bgJ = (ji + 1) * 2 + (jmu + 1) / 2;
	      int bgK = (ki + 1) * 2 + (kmu + 1) / 2;

	      // std::cout << "iPos: " << iPos << ", jPos: " << jPos << ", kPos: " << kPos << std::endl;
	      // std::cout << "bgI: " << bgI << ", bgJ: " << bgJ << ", bgK " << bgK << std::endl;
	      // continue;
	      
	      // index into bgU (flat array)
	      int bIndex = numVars * (idim + 1) * 2 * (jdim + 1) * 2 * bgK
		+ numVars * (idim + 1) * 2 * bgJ + numVars * bgI;

	      // Do the KD tree here.
	      // give me the n nearest neighbors and average.

	      centerLoc[0] = iPos;
	      centerLoc[1] = jPos;
	      centerLoc[2] = kPos;

	      fillBguEntry(centerLoc, nbrMax, maxDist, bgIn, kdTree, bgU, bIndex, emptybg, debugKd);
	      if (debugKd > 0)
		debugKd -= debugKdStep;
	    }
	  }
	}
      }
    }
  }

  if (emptybg.size() > 0)
    std::cout << "** KD left " << emptybg.size() << " holes in bgU" << std::endl;
  
  if (debugKd)
    std::cout << "--- end of debug kd" << std::endl;

  if (configHash->contains("debug_bgU_overwrite"))
    overwriteBgu(configHash->value("debug_bgU_overwrite").toLatin1().data());
  
  if (isTrue("debug_bgU")) {
    dumpBgU(0, uStateSize, bgU);
  }
  
  if (configHash->contains("debug_bgU_nc"))
    bgu2nc(configHash->value("debug_bgU_nc").toLatin1().data(), bgU);
  
  return true;
}
예제 #12
0
bool BkgdObsFractlLoader::loadBkgdObs(QList<real> &bgIn)
{
  Nc3Error err(Nc3Error::verbose_nonfatal);
  // const char *fname = configHash->value("fractl_nc_file").toLatin1().data();  
  QString fname = configHash->value("fractl_nc_file");
  
  // Open the file.
  Nc3File dataFile(fname.toLatin1().data(), Nc3File::ReadOnly);
   
  // Check to see if the file was opened.
  if(!dataFile.is_valid()) {
    std::cout << "Failed to read FRACTL generated nc file " << fname.toLatin1().data()
	      << std::endl;
    return false;
  }

  // TODO The same size variables are also read in VarDriver3D::validateFractlGrid()
  //      Combine into common code?
   
  Nc3Dim *timeDim = dataFile.get_dim("time");
  if (! timeDim)
    return false;

  Nc3Dim *z0Dim = dataFile.get_dim("z0");
  if (! z0Dim)
    return false;

  Nc3Dim *y0Dim = dataFile.get_dim("y0");
  if (! y0Dim)
    return false;

  Nc3Dim *x0Dim = dataFile.get_dim("x0");
  if (! x0Dim)
    return false;

  long ntime = timeDim->size();
  long nz0 = z0Dim->size();
  long ny0 = y0Dim->size();
  long nx0 = x0Dim->size();

  Nc3Var *time0 = dataFile.get_var("time");
  if (! time0)
    return false;
   
  Nc3Var *z0 = dataFile.get_var("z0");
  if (! z0)
    return false;
   
  Nc3Var *y0 = dataFile.get_var("y0");
  if (! y0)
    return false;
  Nc3Var *x0 = dataFile.get_var("x0");
  if (! x0)
    return false;
  Nc3Var *lat0 = dataFile.get_var("lat0");
  if (! lat0)
    return false;
  Nc3Var *lon0 = dataFile.get_var("lon0");
  if (! lon0)
    return false;

  Nc3Var *upward_air_velocity = dataFile.get_var("W");
  if (! upward_air_velocity)
    return false;
  Nc3Var *northward_wind = dataFile.get_var("V");
  if (! northward_wind)
    return false;
  Nc3Var *eastward_wind = dataFile.get_var("U");
  if (! eastward_wind)
    return false;
  Nc3Var *meanNbrDbz = dataFile.get_var("DBZ");
  if (! meanNbrDbz)
    return false;

  Nc3Var *meanNeighborNcp = dataFile.get_var("NCP");
  if (! meanNeighborNcp)
    return false;

  Nc3Var *W_std = dataFile.get_var("W_std");
  if (! W_std)
    return false;
  Nc3Var *V_std = dataFile.get_var("V_std");
  if (! V_std)
    return false;
  Nc3Var *U_std = dataFile.get_var("U_std");
  if (! U_std)
    return false;
   
  long numBgObs = ntime * nz0 * ny0 * nx0;
   
  if (numBgObs <= 0) {
    std::cout << "No background observations loaded" << std::endl;
    return false;
  }
  std::cout << "Loading " << numBgObs << " background observations" << std::endl;
   
  // Allocate data arrays

  double *times = new double[ntime];
   
  double *lats = new double[nx0 * ny0];
  double *lons = new double[nx0 * ny0];
  double *alts = new double[nz0];

  double *upWind = new double[numBgObs];
  double *northWind = new double[numBgObs];
  double *eastWind = new double[numBgObs];
  double *meanDbz =  new double[numBgObs];

  double *wStd = new double[numBgObs];
  double *vStd = new double[numBgObs];
  double *uStd = new double[numBgObs];
   
  bool success = true;

  // Make sure table allocations worked.
  // alts was allocated last so if any are going to fail that would be the one.
   
  if (alts == NULL) {
    std::cout << "Failed to allocate altitude table." << std::endl;
    success = false;
  }
   
  // Get the time array

  if ( success && ! time0->get(times, 1, ntime) ) {
    std::cout << "Failed to read in the times." << std::endl;
    success = false;
  }
   
  // Get the heights in meter
   
  if ( success && ! z0->get(alts, nz0) ) {
    std::cout << "Failed to read in altitudes." << std::endl;
    success = false;
  }
   
  for (int rec = 0; rec < ntime; rec++) {
    if ( ! upward_air_velocity->set_cur(rec, 0, 0, 0)) {
      std::cout << "Failed to read in upward air velocity" << std::endl;
      success = false;
    }	 
    if ( success && ! upward_air_velocity->get(upWind, 1, nz0, ny0, nx0)) {
      std::cout << "Failed to read in upward air velocity" << std::endl;
      success = false;
    }

    if ( success && ! northward_wind->set_cur(rec, 0, 0, 0)) {
      std::cout << "Failed to read in northward air velocity" << std::endl;
      success = false;
    }
    if ( success && ! northward_wind->get(northWind, 1, nz0, ny0, nx0)) {
      std::cout << "Failed to read in northward air velocity" << std::endl;
      success = false;
    }
     
    if ( success && ! eastward_wind->set_cur(rec, 0, 0, 0)) {
      std::cout << "Failed to read in eastward air velocity" << std::endl;
      success = false;
    }
    if ( success && ! eastward_wind->get(eastWind, 1, nz0, ny0, nx0)) {
      std::cout << "Failed to read in eastward air velocity" << std::endl;
      success = false;
    }
     
    if ( success && ! meanNbrDbz->set_cur(rec, 0, 0, 0)) {
      std::cout << "Failed to read in mean dbZ" << std::endl;
      success = false;
    }
    if ( success && ! meanNbrDbz->get(meanDbz, 1, nz0, ny0, nx0)) {
      std::cout << "Failed to read in mean dbZ" << std::endl;
      success = false;
    }

    if ( success && ! W_std->set_cur(rec, 0, 0, 0)) {
      std::cout << "Failed to read in W_std" << std::endl;
      success = false;
    }
     
    if ( success && ! W_std->get(wStd, 1, nz0, ny0, nx0)) {
      std::cout << "Failed to read in W_std" << std::endl;
      success = false;
    }

    if ( success && ! V_std->set_cur(rec, 0, 0, 0)) {
      std::cout << "Failed to read in V_std" << std::endl;
      success = false;
    }
     
    if ( success && ! V_std->get(vStd, 1, nz0, ny0, nx0)) {
      std::cout << "Failed to read in V_std" << std::endl;
      success = false;
    }

    if ( success && ! U_std->set_cur(rec, 0, 0, 0)) {
      std::cout << "Failed to read in U_std" << std::endl;
      success = false;
    }
     
    if ( success && ! W_std->get(uStd, 1, nz0, ny0, nx0)) {
      std::cout << "Failed to read in U_std" << std::endl;
      success = false;
    }
     
  }

  double fillVal = 0.0;
  // double fillVal = std::nan(""); // testing. Quick 2 iteration 
  
  for (int t = 0; t < ntime; t++) {
    // double currentTime = times[t];
     
    for (int z = 0; z < nz0; z++) {
     
      float heightm = alts[z];	// TODO check unit
      float rho = refstate->getReferenceVariable(ReferenceVariable::rhoref, heightm);
      
      for (int y = 0; y < ny0; y++) {
	for (int x = 0; x < nx0; x++) {
	  int vIndex = x + nx0 * (y + ny0 * z);		// variables index
	  int bIndex = vIndex * numVars;		// index into bgU

	  double rhou = eastWind[vIndex] * rho;
	  if (std::isnan(rhou))
	    rhou = fillVal;
	  double rhov = northWind[vIndex] * rho;
	  if (std::isnan(rhov))
	    rhov = fillVal;
	  double rhow = upWind[vIndex] * rho;
	  if (std::isnan(rhow))
	    rhow = fillVal;
	  double dbz  = meanDbz[vIndex];
	  if (std::isnan(dbz))
	    dbz = -35.0;		// clear air.
	  
	  bgU[bIndex + 0] = rhou;
	  bgU[bIndex + 1] = rhov;
	  bgU[bIndex + 2] = rhow;
	  bgU[bIndex + 3] = 0.0;			// t'
	  bgU[bIndex + 4] = 0.0;			// qv'
	  bgU[bIndex + 5] = 0.0;			// rho'
	  bgU[bIndex + 6] = (dbz + 35.) * 0.1;		// transform to scaled value [0..7]
	  
	  // W_std, V_std, U_std are handled separatively in CostFunction3D
	}
      }
    }
  } // ntime
  
  if (isTrue("debug_bgU"))
    dumpBgU(0, uStateSize, bgU);
  
  if (configHash->contains("debug_bgU_nc"))
    bgu2nc(configHash->value("debug_bgU_nc").toLatin1().data(), bgU);
   
   delete[] lats;
   delete[] lons;
   delete[] alts;
   delete[] upWind;
   delete[] northWind;
   delete[] eastWind;
   delete[] meanDbz;

   delete[] wStd;
   delete[] vStd;
   delete[] uStd;

   return success;
}
예제 #13
0
bool CMakeCondition::evaluateCondition(QStringList::const_iterator itBegin, QStringList::const_iterator itEnd) const
{
    if(itBegin==itEnd)
    {
        return isTrue(*itBegin);
    }
    
    bool last = false, done=false;
    last = isTrue(*(prevOperator(itEnd, itBegin)+1));
    while(!done && itBegin!=itEnd)
    {
        QStringList::const_iterator it2;
        it2 = prevOperator(itEnd, itBegin);
        
        done=(itBegin==it2);
        conditionToken c = typeName(*it2);

//         qDebug() << "operator" << *it2 << done;
        QString cmd;
        
        switch(c)
        {
            case NOT:
                last = !last;
                itEnd=it2;
                break;
            case COMMAND:
#ifdef Q_OS_WIN
                cmd = CMakeProjectVisitor::findFile(*(it2+1),
                        CMakeProjectVisitor::envVarDirectories("Path"), QStringList(), CMakeProjectVisitor::Executable);
#else
                cmd = CMakeProjectVisitor::findFile(*(it2+1),
                        CMakeProjectVisitor::envVarDirectories("PATH"), QStringList(), CMakeProjectVisitor::Executable);
#endif
                last = !cmd.isEmpty();
                itEnd=it2-1;
                break;
            case EXISTS:
            {
                QString v=*(it2+1);
//                 kDebug(9042) << "EXISTS" << v << *it2;
                if(v.isEmpty())
                    kDebug(9042) << "error: no";
                else
                {
                    last=false;
                    QFileInfo f(v);
                    if(f.exists())
                    {
                        last=true;
                    }
                }
                itEnd=it2;
            }   break;
            case IS_DIRECTORY: {
                QFileInfo f(*(it2+1));
                last = f.isDir();
                itEnd=it2;
            }   break;
            case DEFINED:
                last=m_vars->contains(*(it2+1));
                itEnd=it2;
                break;
            case AND:
                return evaluateCondition(itBegin, it2-1) && last;
            case OR:
                return evaluateCondition(itBegin, it2-1) || last;
            case MATCHES: {
                QRegExp rx(*(it2+1));
                if(m_vars->contains(*(it2-1)))
                    rx.indexIn(m_vars->value(*(it2-1)).join(""));
                else
                    rx.indexIn(*(it2-1));
                last=rx.matchedLength()>0;
                itEnd=it2-1;
            }   break;
            case LESS: {
                QString strA=*(it2-1);
                QString strB=*(it2+1);
                if(m_vars->contains(strA))
                    strA=m_vars->value(strA).join(";");
                int a=strA.toInt(), b=strB.toInt();
                last= (a<b);
                itEnd=it2-1;
            }   break;
            case GREATER: {
                QString strA=*(it2-1);
                QString strB=*(it2+1);
                if(m_vars->contains(strA))
                    strA=m_vars->value(strA).join(";");
                int a=strA.toInt(), b=strB.toInt();
                last= (a>b);
                itEnd=it2-1;
            }   break;
            case EQUAL: {
                QString strA=*(it2-1);
                QString strB=*(it2+1);
                if(m_vars->contains(strA))
                    strA=m_vars->value(strA).join(";");
                int a=strA.toInt(), b=strB.toInt();
                last= (a==b);
                itEnd=it2-1;
            }   break;
            case STRLESS: {
                QString strA=*(it2-1);
                QString strB=*(it2+1);
                if(m_vars->contains(strA))
                    strA=m_vars->value(strA).join(";");
                last= (strA<strB);
                itEnd=it2-1;
            }   break;
            case STRGREATER: {
                QString strA=*(it2-1);
                QString strB=*(it2+1);
                if(m_vars->contains(strA))
                    strA=m_vars->value(strA).join(";");
                last= (strA>strB);
                itEnd=it2-1;
            }   break;
            case STREQUAL: {
                QString strA=*(it2-1);
                QString strB=*(it2+1);
                if(m_vars->contains(strA))
                    strA=m_vars->value(strA).join(";");
                last= (strA==strB);
                itEnd=it2-1;
            }   break;
            case IS_NEWER_THAN: {
                QFileInfo pathA(*(it2-1));
                QFileInfo pathB(*(it2+1));
//                 kDebug(9042) << "newer" << strA << strB;
                last= (pathA.lastModified()>pathB.lastModified());
                itEnd=it2-1;
            }
            /*default:
                kDebug(9042) << "no operator:" << *it2;
                break;*/
        }
    }
    return last;
}
예제 #14
0
		/*
			Test with file with audio and video
		*/
		void multiTest() {
			::toolkit::Inspector inspect("file://" + ::core::Path::current() + "/tests/multi.ogg");
			isTrue(inspect.audio());
			isTrue(inspect.video());
		}
예제 #15
0
void isAlive(std::vector<T> & v, std::function<void(typename toShared<T>::type &)> func){
	isTrue(v, func, &IAgent::isAlive);
}
예제 #16
0
파일: Logic.C 프로젝트: aehyvari/OpenSMT2
//
// This method is currently under development
//
lbool Logic::simplifyTree(PTRef tr)
{
    vec<pi> queue;
    Map<PTRef,bool,PTRefHash> processed;
    queue.push(pi(tr));
    lbool last_val = l_Undef;
    while (queue.size() != 0) {
        // First find a node with all children processed.
        int i = queue.size()-1;
        if (processed.contains(queue[i].x)) {
            queue.pop();
            continue;
        }
        bool unprocessed_children = false;
        if (queue[i].done == false) {
#ifdef SIMPLIFY_DEBUG
            cerr << "looking at term num " << queue[i].x.x << endl;
#endif
            Pterm& t = getPterm(queue[i].x);
            for (int j = 0; j < t.size(); j++) {
                PTRef cr = t[j];
                if (!processed.contains(cr)) {
                    unprocessed_children = true;
                    queue.push(pi(cr));
#ifdef SIMPLIFY_DEBUG
                    cerr << "pushing child " << cr.x << endl;
#endif
                }
            }
            queue[i].done = true;
        }
        if (unprocessed_children) continue;
#ifdef SIMPLIFY_DEBUG
        cerr << "Found a node " << queue[i].x.x << endl;
        cerr << "Before simplification it looks like " << term_store.printTerm(queue[i].x) << endl;
#endif
        // (1) Check if my children (potentially simplified now) exist in
        //     term store and if so, replace them with the term store
        //     representative
        // (2) Simplify in place
        // (3) See if the simplifications resulted in me changing, and if so,
        //     look up from the table whether I'm already listed somewhere and add
        //     a mapping to the canonical representative, or create a new entry for
        //     me in the map.
        Pterm& t = getPterm(queue[i].x);
        // (1)
#ifdef SIMPLIFY_DEBUG
        if (t.size() > 0)
            cerr << "Now looking into the children of " << queue[i].x.x << endl;
        else
            cerr << "The node " << queue[i].x.x << " has no children" << endl;
#endif
        for (int e = 0; e < t.size(); e++) {
            PTRef cr = t[e];
#ifdef SIMPLIFY_DEBUG
            cerr << "child n. " << e << " is " << cr.x << endl;
#endif
            assert(cr != queue[i].x);
            Pterm& c = getPterm(cr);
            PTLKey k;
            k.sym = c.symb();
            for (int j = 0; j < c.size(); j++)
                k.args.push(c[j]);
            if (!isBooleanOperator(k.sym)) {
                assert(term_store.cplx_map.contains(k));
#ifdef SIMPLIFY_DEBUG
                cerr << cr.x << " is not a boolean operator ";
                cerr << "and it maps to " << term_store.cplx_map[k].x << endl;
#endif
                t[e] = term_store.cplx_map[k];
                assert(t[e] != queue[i].x);
            } else {
                assert(term_store.bool_map.contains(k));
#ifdef SIMPLIFY_DEBUG
                cerr << cr.x << " is a boolean operator"
                     << " and it maps to " << term_store.bool_map[k].x << endl;
#endif
                t[e] = term_store.bool_map[k];
                assert(t[e] != queue[i].x);
            }
        }
#ifdef SIMPLIFY_DEBUG
        cerr << "After processing the children ended up with node " << term_store.printTerm(queue[i].x, true) << endl;
#endif
        // (2) Simplify in place
        PTRef orig = queue[i].x; // We need to save the original type in case the term gets simplified
        simplify(queue[i].x);
#ifdef SIMPLIFY_DEBUG
        cerr << "-> which was now simplified to " << term_store.printTerm(queue[i].x, true) << endl;
//      I don't seem to remember why this should be true or false?
//        if (orig != queue[i].x) {
//            assert(isTrue(queue[i].x) || isFalse(queue[i].x));
//            assert(isAnd(orig) || isOr(orig) || isEquality(orig) || isNot(orig));
//        }
#endif
        processed.insert(orig, true);
        // Make sure my key is in term hash
#ifdef SIMPLIFY_DEBUG
        cerr << "Making sure " << orig.x << " is in term_store hash" << endl;
        cerr << "Pushing symb " << t.symb().x << " to hash key" << endl;
#endif
        PTLKey k;
        k.sym = t.symb();
        for (int j = 0; j < t.size(); j++) {
#ifdef SIMPLIFY_DEBUG
            cerr << "Pushing arg " << t[j].x << " to hash key" << endl;
#endif
            k.args.push(t[j]);
        }
        if (!isBooleanOperator(k.sym)) {
            if (!term_store.cplx_map.contains(k)) {
                term_store.cplx_map.insert(k, queue[i].x);
#ifdef SIMPLIFY_DEBUG
                cerr << "sym " << k.sym.x << " args <";
                for (int j = 0; j < k.args.size(); j++) {
                    cerr << k.args[j].x << " ";
                }
                cerr << "> maps to " << term_store.cplx_map[k].x << endl;
#endif
            }
            PTRef l = term_store.cplx_map[k];
            // This is being kept on record in case the root term gets simplified
            if (isTrue(l)) last_val = l_True;
            else if (isFalse(l)) last_val = l_False;
            else last_val = l_Undef;
        } else {
            if (!term_store.bool_map.contains(k)) {
                term_store.bool_map.insert(k, queue[i].x);
#ifdef SIMPLIFY_DEBUG
                cerr << "sym " << k.sym.x << " args ";
                for (int j = 0; j < k.args.size(); j++) {
                    cerr << k.args[j].x << " ";
                }
                cerr << "maps to " << term_store.bool_map[k].x << endl;
#endif
            }
            PTRef l = term_store.bool_map[k];
            // This is being kept on record in case the root term gets simplified
            if (isTrue(l)) last_val = l_True;
            else if (isFalse(l)) last_val = l_False;
            else last_val = l_Undef;
        }
        queue.pop();
    }
    return last_val;
}
예제 #17
0
bool isValid(T & p){
	return isTrue(p, &IModel::isValid);
}
예제 #18
0
파일: Logic.C 프로젝트: aehyvari/OpenSMT2
//
// Sort a term if it commutes.
// The following simplifications implemented
// (should be refactored to separate methods?):
//  - `and':
//    - drop constant true terms
//    - convert an empty `and' to the constant term `true'
//    - convert an `and' containing `false' to a replicate `false'
//  - `or':
//    - drop constant false terms
//    - convert an empty `or' to a replicate `false' term
//    - convert an `or' containing `true' to a replicate `true'
//
//
void Logic::simplify(SymRef& s, vec<PTRef>& args) {
    // First sort it
#ifdef SORT_BOOLEANS
    if (sym_store[s].commutes())
#else
    if (sym_store[s].commutes() && !isAnd(s) && !isOr(s))
#endif
        sort(args, LessThan_PTRef());

    if (!isBooleanOperator(s) && !isEquality(s)) return;

    int dropped_args = 0;
    bool replace = false;
    if (s == getSym_and()) {
        int i, j;
        PTRef p = PTRef_Undef;
        for (i = j = 0; i < args.size(); i++) {
            if (args[i] == getTerm_false()) {
                args.clear();
                s = getSym_false();
#ifdef SIMPLIFY_DEBUG
                cerr << "and  -> false" << endl;
#endif
                return;
            } else if (args[i] != getTerm_true() && args[i] != p) {
                args[j++] = p = args[i];
            } else {
#ifdef SIMPLIFY_DEBUG
                cerr << "and -> drop" << endl;
#endif
            }
        }
        dropped_args = i-j;
        if (dropped_args == args.size()) {
            s = getSym_true();
            args.clear();
#ifdef SIMPLIFY_DEBUG
            cerr << "and -> true" << endl;
#endif
            return;
        } else if (dropped_args == args.size() - 1)
            replace = true;
        else if (dropped_args > 0)
            args.shrink(dropped_args);
    }
    if (s == getSym_or()) {
        int i, j;
        PTRef p = PTRef_Undef;
        for (i = j = 0; i < args.size(); i++) {
            if (args[i] == getTerm_true()) {
                args.clear();
                s = getSym_true();
#ifdef SIMPLIFY_DEBUG
                cerr << "or -> true" << endl;
#endif
                return;
            } else if (args[i] != getTerm_false() && args[i] != p) {
                args[j++] = p = args[i];
            } else {
#ifdef SIMPLIFY_DEBUG
                cerr << "or -> drop" << endl;
#endif
            }
        }
        dropped_args = i-j;
        if (dropped_args == args.size()) {
            s = getSym_false();
            args.clear();
#ifdef SIMPLIFY_DEBUG
            cerr << "or -> false" << endl;
#endif
            return;
        }
        else if (dropped_args == args.size() - 1)
            replace = true;
        else if (dropped_args > 0)
            args.shrink(dropped_args);
    }
    if (isEquality(s)) {
        assert(args.size() == 2);
        if (isBooleanOperator(s) && (args[0] == getTerm_true())) {
            Pterm& t = getPterm(args[1]);
            s = t.symb();
            args.clear();
            for (int i = 0; i < t.size(); i++)
                args.push(t[i]);
#ifdef SIMPLIFY_DEBUG
            cerr << "eq -> second" << endl;
#endif
            return;
        } else if (isBooleanOperator(s) && (args[0] == getTerm_false())) {
            PTRef old = args[1];
            PTRef tr = mkNot(args[1]);
            Pterm& t = getPterm(tr);
            s = t.symb();
            args.clear();
            args.push(old);
#ifdef SIMPLIFY_DEBUG
            cerr << "eq -> not second" << endl;
#endif
            return;
        } else if (isBooleanOperator(s) && (args[1] == getTerm_true())) {
            args.clear();
            Pterm& t = getPterm(args[0]);
            s = t.symb();
            args.clear();
            for (int i = 0; i < t.size(); i++)
                args.push(t[i]);
#ifdef SIMPLIFY_DEBUG
            cerr << "eq -> first" << endl;
#endif
            return;
        } else if (isBooleanOperator(s) && (args[1] == getTerm_false())) {
            PTRef old = args[0];
            PTRef tr = mkNot(args[0]);
            Pterm& t = getPterm(tr);
            s = t.symb();
            args.clear();
            args.push(old);
#ifdef SIMPLIFY_DEBUG
            cerr << "eq -> not first"<< endl;
#endif
            return;
        } else if (args[0] == args[1]) {
            args.clear();
            s = getSym_true();
#ifdef SIMPLIFY_DEBUG
            cerr << "eq -> true" << endl;
#endif
            return;
        } else if (isBooleanOperator(s) && (args[0] == mkNot(args[1]))) {
            args.clear();
            s = getSym_false();
#ifdef SIMPLIFY_DEBUG
            cerr << "eq -> false" << endl;
#endif
            return;
        }
    }
    if (isNot(s)) {
        if (isTrue(args[0])) {
            args.clear();
            s = getSym_false();
#ifdef SIMPLIFY_DEBUG
            cerr << "not -> false" << endl;
#endif
            return;
        }
        if (isFalse(args[0])) {
            args.clear();
            s = getSym_true();
#ifdef SIMPLIFY_DEBUG
            cerr << "not -> true" << endl;
#endif
            return;
        }
    }
    // Others, to be implemented:
    // - distinct
    // - implies
    // - xor
    // - ite
    if (replace) {
        // Return whatever is the sole argument
        Pterm& t = getPterm(args[0]);
        s = t.symb();
        args.clear();
        for (int i = 0; i < t.size(); i++)
            args.push(t[i]);
#ifdef SIMPLIFY_DEBUG
        cerr << " replace" << endl;
#endif
    }
}
예제 #19
0
void isValid(std::vector<T> & v, std::function<void(typename toShared<T>::type &)> func){
	isTrue(v, func, &IModel::isValid);
}
예제 #20
0
/*
  Returns the next token, if # was met.  This function interprets the
  preprocessor directive, skips over any #ifdef'd out tokens, and returns the
  token after all of that.
*/
int Tokenizer::getTokenAfterPreprocessor()
{
    yyCh = getChar();
    while (isspace(yyCh) && yyCh != '\n')
        yyCh = getChar();

    /*
      #directive condition
    */
    QString directive;
    QString condition;

    while (isalpha(yyCh)) {
        directive += QChar(yyCh);
        yyCh = getChar();
    }
    if (!directive.isEmpty()) {
        while (yyCh != EOF && yyCh != '\n') {
            if (yyCh == '\\') {
                yyCh = getChar();
                if (yyCh == '\r')
                    yyCh = getChar();
            }
            condition += yyCh;
            yyCh = getChar();
        }
        condition.remove(*comment);
        condition = condition.simplified();

        /*
          The #if, #ifdef, #ifndef, #elif, #else, and #endif
          directives have an effect on the skipping stack.  For
          instance, if the code processed so far is

              #if 1
              #if 0
              #if 1
              // ...
              #else

          the skipping stack contains, from bottom to top, false true
          true (assuming 0 is false and 1 is true).  If at least one
          entry of the stack is true, the tokens are skipped.

          This mechanism is simple yet hard to understand.
        */
        if (directive[0] == QChar('i')) {
            if (directive == QString("if"))
                pushSkipping(!isTrue(condition));
            else if (directive == QString("ifdef"))
                pushSkipping(!defines->exactMatch(condition));
            else if (directive == QString("ifndef"))
                pushSkipping(defines->exactMatch(condition));
        } else if (directive[0] == QChar('e')) {
            if (directive == QString("elif")) {
                bool old = popSkipping();
                if (old)
                    pushSkipping(!isTrue(condition));
                else
                    pushSkipping(true);
            } else if (directive == QString("else")) {
                pushSkipping(!popSkipping());
            } else if (directive == QString("endif")) {
                popSkipping();
            }
        } else if (directive == QString("define")) {
            if (versionX->exactMatch(condition))
                yyVersion = versionX->cap(1);
        }
    }

    int tok;
    do {
        /*
          We set yyLex now, and after getToken() this will be
          yyPrevLex. This way, we skip over the preprocessor
          directive.
        */
        qstrcpy(yyLex, yyPrevLex);

        /*
          If getToken() meets another #, it will call
          getTokenAfterPreprocessor() once again, which could in turn
          call getToken() again, etc. Unless there are 10,000 or so
          preprocessor directives in a row, this shouldn't overflow
          the stack.
        */
        tok = getToken();
    } while (yyNumPreprocessorSkipping > 0 && tok != Tok_Eoi);
    return tok;
}
예제 #21
0
	bool Config::isFalse(string key)
	{
		return !isTrue(key);
	}
예제 #22
0
/******************************************************************************
*                                                                             *
*       execExp/1                                                             *
*                                                                             *
*       This routine attempts to evaulate the string expression as if it was  *
*       an IF-THEN-FI execS expression. Take expression and generate an       *
*       if ( expression ) then $i=0 endif, give it to the parser , then use   *
*	execR() to evaluate it. 					      *
*       For single variable expressions 				      *
*	 if not present, expression is false				      *
*	 if real variable & inactive, expression is false		      *
*	 if string & null string value, expression is false		      *
*       For Multiple variable expressions				      *
*        if a variable is not present, Error is reported & error returned     *
*       Parser errors return -1					              *
*                                                                             *
*				Author: Greg Brissey 5/31/90		      *
******************************************************************************/
int execExp(const char *buffer)	
{  
   char *expbuf;
   int   explen;
   char *prevTempID;
   const char *oldbp;
   int   oldFromFile;
   int   oldFromString;
   node *oldcodeTree;
   int   returnCode=0;
   int   gocheckit;

   LPRINT0(1,"execExp: starting...\n");
   LPRINT1(1,"execExp: expression ='%s'\n",buffer);
   if ( (explen = strlen(buffer)) > 0)
   {
  
     expbuf = allocateWithId( (explen + 35) * sizeof(char), "execExp");
     if (expbuf == NULL)
     {
        Werrprintf("cannot allocate memory for expression string");
        ABORT;
     }
     /* for parser: 'if ( expression ) then statement endif'  */
     strcpy(expbuf,"if ( ");
     strcat(expbuf,buffer);
     strcat(expbuf," ) then $i=0 endif \n");
     LPRINT1(1,"execExp: parser expression ='%s'\n",expbuf);
   
      oldFromFile   = fromFile;		/* push existing file info */
      oldFromString = fromString;
      oldbp         = bp;
      oldcodeTree   = codeTree;

      fromFile      = 0;
      fromString    = 1;
      bp            = expbuf;
      codeTree      = NULL;

      prevTempID    = tempID; tempID = newTempName("tmpExecExpID");

      /* parse expression IF-THEN-FI */
      switch (yyparse())
      { case 0:
		LPRINT0(1,"execExp: ...parser gives code 0, go do it!\n");
#ifdef  DEBUG
		if ( 1 < Lflag)
                {
		  showTree(0,"execExp:    ",codeTree);
		  showFlavour(stderr,codeTree);
                }
#endif 
		switch(codeTree->flavour)
		{
		   case THEN:  	/* It has to be this or something is real wrong. */
			{ 
			    char    *name;
                            int      shouldFree;
                            varInfo *v;
  			    pair p;

			    /* was it a single variable expression ?*/
			    /* if not flavour,  will be an operator not ID or LB */
                            gocheckit = 0;
                            v = NULL;
                            if ((codeTree->Lson->flavour == ID) ||
				(codeTree->Lson->flavour == LB) )
			    {
                              if ( (name=execN(codeTree->Lson->Lson,&shouldFree,NULL)) )
			      {
                                if ( (v=findVar(name)) )
				{
                                  gocheckit = 2; /* variable present, check active */
				}
                                else
                                { 
                                  gocheckit = 0; /* variable not present */
                                }
			      }
                              if (shouldFree)
                              {
                                LPRINT1(3,"execExp: ...releasing name %s\n",name);
                                release(name);
                              }
			    }
                            else
                              gocheckit = 1;	/* two variable expression */


			   if (gocheckit)
			   {
                            if (execR(codeTree->Lson,&p, NULL))
			    {
			       if((gocheckit > 1) && (p.T.basicType == T_REAL)	)
			       {
				  if (!v->active)
				  {
			             returnCode = 0;
                            	     cleanPair(&p);
				     break;
				  }	
			       }
			       if((gocheckit > 1) && (p.T.basicType == T_STRING)	)
			       {
				  if (strcmp(p.R->v.s,"n") == 0)
				  {
			             returnCode = 0;
                            	     cleanPair(&p);
				     break;
				  }	
			       }
                               if (isTrue(&p))
                               {
                                 LPRINT0(1,"execExp: IF-THEN-FI exp is true\n");
                                 returnCode = 1;
                               }
                               else
                               {   
                                LPRINT0(1,"execExp: IF-THEN-FI exp is false\n");
                                returnCode = 0;
                               }
			    }
                            else
                            {   
                               LPRINT0(1,"execExp: IF-THEN-FI exp failed\n");
                               returnCode = -1;
                            }
                            cleanPair(&p);
			   }
			   else
			     returnCode = 0;	/* variable not present */
                         }
			break;
                   default:
		        WerrprintfWithPos(
		         "BUG! execExp has a bad flavour (=%d)",codeTree->flavour);
                        returnCode = -1;
			break;
         	}
		break;
	case 1:
		LPRINT0(1,"execExp: ...parser gives code 1, drop everything!\n");
		ignoreEOL  = 0;		/* had a syntax error, drop it */
		returnCode = -1;
		break;
	case 2:
		LPRINT0(1,"execExp: ...parser gives code 2, incomplete expression, abort\n");
		ignoreEOL  = 0;		/* had a syntax error, drop it       */
		returnCode = -1;
		break;
      }
      codeTree = NULL;

      releaseWithId(tempID); free(tempID); tempID = prevTempID;

      fromFile   = oldFromFile;		/*  restore old file/kbd/string state*/
      fromString = oldFromString;
      bp         = oldbp;
      codeTree   = oldcodeTree;
      releaseAllWithId("execExp");
      LPRINT0(1,"execExp: finishing...\n");
   }
   else
   {  fprintf(stderr,"execExp: string (=\"%s\") is null.\n",buffer);
      returnCode = -1;
   }
   return(returnCode);
}