Example #1
2
//! initMembers
void Object::init(EScript::Namespace & globals) {
	Type * typeObject = getTypeObject();
	typeObject->allowUserInheritance(true);
	initPrintableName(typeObject,getClassName());

	declareConstant(&globals,getClassName(),typeObject);

	//! [ESMF] Object new Object
	ES_CTOR(typeObject,0,0,new Object(thisType))

	//! [ESMF] Object Object.clone()
	ES_FUN(typeObject,"clone",0,0,thisEObj->clone())

	//! [ESMF] Number Object.toNumber()
	ES_FUN(typeObject,"toNumber",0,0,thisEObj->toDouble())

	//! [ESMF] String Object.toString()
	ES_FUN(typeObject,"toString",0,0,thisEObj->toString())

	//! [ESMF] String Object.toDbgString()
	ES_FUN(typeObject,"toDbgString",0,0,thisEObj->toDbgString())

	//! [ESMF] Bool Object.isA(Object o)
	ES_FUN(typeObject,"isA",1,1,thisEObj->isA(parameter[0].castTo<Type>()))

	//! [ESMF] Bool Object ---|> Object
	ES_FUN(typeObject,"---|>",1,1,thisEObj->isA(parameter[0].castTo<Type>()))

	/*!	[ESMF] Bool Object.!=(Object o)
		\note Uses isEqual(...) which calls "=="-Operator
	*/
	ES_FUN(typeObject,"!=",1,1,!thisEObj->isEqual(rt,parameter[0]) )

	/*!	[ESMF] Bool Object.==(Object o)
		\note this is probably the only place where rt_isEqual(...) is called directly.	*/
	ES_FUN(typeObject,"==",1,1,thisEObj->rt_isEqual(rt,parameter[0]))

	//! [ESMF] Bool Object.===(Object o)
	ES_FUN(typeObject,"===",1,1,thisEObj->isIdentical(rt,parameter[0]))

	//! [ESMF] Bool Object.!==(Object o)
	ES_FUN(typeObject,"!==",1,1,!thisEObj->isIdentical(rt,parameter[0]))

	//! [ESMF] Bool !Object()
	ES_FUN(typeObject,"!_pre",0,0,!thisEObj->toBool())

	//! [ESMF] string Object.getTypeName()
	ES_FUN(typeObject,"getTypeName",0,0,thisEObj->getTypeName())

	//! [ESMF] Object Object.getType()
	ES_FUN(typeObject,"getType",0,0,thisEObj->getType())

	//! [ESMF] int Object.hash()
	ES_FUN(typeObject,"hash",0,0,thisEObj->hash().getValue())

	//! [ESMF] Object Object.getAttribute(key)
	ES_FUN(typeObject,"getAttribute",1,1,thisEObj->getAttribute(parameter[0].toString()).getValue())

	//! [ESMF] Object Object.getAttributeProperties(key)
	ES_FUN(typeObject,"getAttributeProperties",1,1,
				static_cast<unsigned int>(thisEObj->getAttribute(parameter[0].toString()).getProperties()))

	//! [ESMF] Object Object.getLocalAttribute(key)
	ES_FUN(typeObject,"getLocalAttribute",1,1,thisEObj->getLocalAttribute(parameter[0].toString()).getValue())

	//! [ESMF] Bool Object.isSet(key)
	ES_FUN(typeObject,"isSet",1,1,!thisEObj->getAttribute(parameter[0].toString()).isNull())

	//! [ESMF] Bool Object.isSetLocally(key)
	ES_FUN(typeObject,"isSetLocally",1,1,!thisEObj->getLocalAttribute(parameter[0].toString()).isNull())

	//! [ESMF] Bool Object.setAttribute(key,value(,flags = ATTR_NORMAL_ATTRIBUTE))
	ES_FUN(typeObject,"setAttribute",2,3,
				thisEObj->setAttribute(parameter[0].toString(),
													Attribute(parameter[1],
													static_cast<Attribute::flag_t>(parameter[2].to<int>(rt)))))

	//! [ESMF] Bool Object.assignAttribute(key,value)
	ES_FUN(typeObject,"assignAttribute",2,2,rt.assignToAttribute(thisEObj,parameter[0].toString(),parameter[1]))

	typedef std::unordered_map<StringId,Object *> attrMap_t; // has to be defined here, due to compiler (gcc) bug.

	//! Map Object._getAttributes()
	ES_FUNCTION(typeObject,"_getAttributes",0,0,{
		attrMap_t attrs;
		thisEObj->collectLocalAttributes(attrs);
		return Map::create(attrs);
	})
  CalibrationUtilityBill::CalibrationUtilityBill(const std::string& name, const FuelType& fuelType, const InstallLocationType& meterInstallLocation,
    boost::optional<std::string> meterSpecificInstallLocation, boost::optional<EndUseCategoryType> meterEndUseCategory, 
    boost::optional<std::string> meterSpecificEndUse, std::string consumptionUnit, double consumptionUnitConversionFactor,
    boost::optional<std::string> peakDemandUnit, boost::optional<double> peakDemandUnitConversionFactor,
    boost::optional<unsigned> timestepsInPeakDemandWindow, boost::optional<double> minutesInPeakDemandWindow,
    boost::optional<unsigned> numberBillingPeriodsInCalculations, boost::optional<double> CVRMSE, boost::optional<double> NMBE)
    : m_attribute(CalibrationUtilityBill::attributeName(), std::vector<openstudio::Attribute>(), boost::none)
  {
    std::vector<Attribute> values;

    values.push_back(Attribute("name", name));
    values.push_back(Attribute("fuelType", fuelType.valueName()));
    values.push_back(Attribute("meterInstallLocation", meterInstallLocation.valueName()));
    if (meterSpecificInstallLocation){
      values.push_back(Attribute("meterSpecificInstallLocation", *meterSpecificInstallLocation));
    }
    if (meterEndUseCategory){
      values.push_back(Attribute("meterEndUseCategory", meterEndUseCategory->valueName()));
    }
    if (meterSpecificEndUse){
      values.push_back(Attribute("meterSpecificEndUse", *meterSpecificEndUse));
    }
    values.push_back(Attribute("consumptionUnit", consumptionUnit));
    values.push_back(Attribute("consumptionUnitConversionFactor", consumptionUnitConversionFactor));
    if (peakDemandUnit){
      values.push_back(Attribute("peakDemandUnit", *peakDemandUnit));
    }
    if (peakDemandUnitConversionFactor){
      values.push_back(Attribute("peakDemandUnitConversionFactor", *peakDemandUnitConversionFactor));
    }
    if (timestepsInPeakDemandWindow){
      values.push_back(Attribute("timestepsInPeakDemandWindow", *timestepsInPeakDemandWindow));
    }
    if (minutesInPeakDemandWindow){
      values.push_back(Attribute("minutesInPeakDemandWindow", *minutesInPeakDemandWindow));
    }
    if (numberBillingPeriodsInCalculations){
      values.push_back(Attribute("numberBillingPeriodsInCalculations", *numberBillingPeriodsInCalculations));
    }
    if (CVRMSE){
      values.push_back(Attribute("cvrmse", *CVRMSE));
    }
    if (NMBE){
      values.push_back(Attribute("nmbe", *NMBE));
    }

    values.push_back(Attribute("billingPeriods", std::vector<Attribute>()));

    m_attribute.setValue(values);
  }
Example #3
0
void GumbelDistribution::setBeta(double value) {
  impl()->setAttribute(Attribute("betas",value),false);
}
Example #4
0
 Attribute Object::createAttribute (const std::string& name, const DataType& type, const DataSpace& space, AttributeCreatePropList acpl, /*AttributeAccess*/PropList aapl) const {
   return Attribute (Exception::check ("H5Acreate2", H5Acreate2 (handle (), name.c_str (), type.handle (), space.handle (), acpl.handleOrDefault (), aapl.handleOrDefault ())));
 }
void BufferGeometry::computeVertexNormals( bool areaWeighted ) {

  auto positionsP = attributes.get( AttributeKey::position() );
  auto indicesP   = attributes.get( AttributeKey::index() );
  if ( positionsP && indicesP ) {

    const auto& indices = positionsP->array;
    const auto& positions = indicesP->array;

    const auto nVertexElements = ( int )positions.size();

    if ( auto normalsP = attributes.get( AttributeKey::normal() ) ) {

      // reset existing normals to zero

      auto& normals = normalsP->array;
      for ( size_t i = 0, il = normals.size(); i < il; i ++ ) {

        normals[ i ] = 0;

      }

    } else {

      attributes.add( AttributeKey::normal(), Attribute( THREE::v3, nVertexElements ) );

    }

    auto& normals = attributes[ AttributeKey::normal() ].array;

    Vector3 pA, pB, pC, cb, ab;

    for ( size_t j = 0, jl = offsets.size(); j < jl; ++ j ) {

      const auto start = offsets[ j ].start;
      const auto count = offsets[ j ].count;
      const auto index = offsets[ j ].index;

      for ( auto i = start, il = start + count; i < il; i += 3 ) {

        const auto vA = index + ( int )indices[ i ];
        const auto vB = index + ( int )indices[ i + 1 ];
        const auto vC = index + ( int )indices[ i + 2 ];

        auto x = positions[ vA * 3 ];
        auto y = positions[ vA * 3 + 1 ];
        auto z = positions[ vA * 3 + 2 ];
        pA.set( x, y, z );

        x = positions[ vB * 3 ];
        y = positions[ vB * 3 + 1 ];
        z = positions[ vB * 3 + 2 ];
        pB.set( x, y, z );

        x = positions[ vC * 3 ];
        y = positions[ vC * 3 + 1 ];
        z = positions[ vC * 3 + 2 ];
        pC.set( x, y, z );

        cb.subVectors( pC, pB );
        ab.subVectors( pA, pB );
        cb.cross( ab );

        normals[ vA * 3 ] += cb.x;
        normals[ vA * 3 + 1 ] += cb.y;
        normals[ vA * 3 + 2 ] += cb.z;

        normals[ vB * 3 ] += cb.x;
        normals[ vB * 3 + 1 ] += cb.y;
        normals[ vB * 3 + 2 ] += cb.z;

        normals[ vC * 3 ] += cb.x;
        normals[ vC * 3 + 1 ] += cb.y;
        normals[ vC * 3 + 2 ] += cb.z;

      }

    }

    // normalize normals

    for ( size_t i = 0, il = normals.size(); i < il; i += 3 ) {

      Vector3 xyz( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );

      auto n = 1.0f / xyz.length();

      normals[ i ] *= n;
      normals[ i + 1 ] *= n;
      normals[ i + 2 ] *= n;

    }

    normalsNeedUpdate = true;

  }

}
void LognormalDistribution::setUpperBound(double value) {
  impl()->setAttribute(Attribute("upper_bounds",value),false);
}
 QuadEdgeEffect(GrColor color, const SkMatrix& localMatrix)
     : INHERITED(color, SkMatrix::I(), localMatrix) {
     this->initClassID<QuadEdgeEffect>();
     fInPosition = &this->addVertexAttrib(Attribute("inPosition", kVec2f_GrVertexAttribType));
     fInQuadEdge = &this->addVertexAttrib(Attribute("inQuadEdge", kVec4f_GrVertexAttribType));
 }
Example #8
0
/*
* Create a PKCS #10 certificate request
*/
PKCS10_Request create_cert_req(const X509_Cert_Options& opts,
                               const Private_Key& key,
                               const std::string& hash_fn,
                               RandomNumberGenerator& rng)
   {
   AlgorithmIdentifier sig_algo;
   X509_DN subject_dn;
   AlternativeName subject_alt;

   opts.sanity_check();

   std::vector<byte> pub_key = X509::BER_encode(key);
   std::unique_ptr<PK_Signer> signer(choose_sig_format(key, hash_fn, sig_algo));
   load_info(opts, subject_dn, subject_alt);

   const size_t PKCS10_VERSION = 0;

   Extensions extensions;

   extensions.add(
      new Cert_Extension::Basic_Constraints(opts.is_CA, opts.path_limit));
   extensions.add(
      new Cert_Extension::Key_Usage(
         opts.is_CA ? Key_Constraints(KEY_CERT_SIGN | CRL_SIGN) :
                      find_constraints(key, opts.constraints)
         )
      );
   extensions.add(
      new Cert_Extension::Extended_Key_Usage(opts.ex_constraints));
   extensions.add(
      new Cert_Extension::Subject_Alternative_Name(subject_alt));

   DER_Encoder tbs_req;

   tbs_req.start_cons(SEQUENCE)
      .encode(PKCS10_VERSION)
      .encode(subject_dn)
      .raw_bytes(pub_key)
      .start_explicit(0);

   if(opts.challenge != "")
      {
      ASN1_String challenge(opts.challenge, DIRECTORY_STRING);

      tbs_req.encode(
         Attribute("PKCS9.ChallengePassword",
                   DER_Encoder().encode(challenge).get_contents_unlocked()
            )
         );
      }

   tbs_req.encode(
      Attribute("PKCS9.ExtensionRequest",
                DER_Encoder()
                   .start_cons(SEQUENCE)
                      .encode(extensions)
                   .end_cons()
               .get_contents_unlocked()
         )
      )
      .end_explicit()
      .end_cons();

   const std::vector<byte> req =
      X509_Object::make_signed(signer.get(), rng, sig_algo,
                               tbs_req.get_contents());

   return PKCS10_Request(req);
   }
Example #9
0
float XMLNode::AttributeFloat( const std::string& name , float defaultVar )
{
    XMLAttributePtr attr = Attribute(name);
    return attr ? attr->ValueFloat() : defaultVar;
}
Example #10
0
uint32_t XMLNode::AttributeUInt( const std::string& name , uint32_t defaultVar  )
{
    XMLAttributePtr attr = Attribute(name);
    return attr ? attr->ValueUInt() : defaultVar;
}
Example #11
0
File: Map.cpp Project: noam-c/EDEn
void Map::parseNPCGroup(const TiXmlElement* npcGroupElement)
{
   DEBUG("Loading NPC layer.");
   if(npcGroupElement != nullptr)
   {
      geometry::Point2D topLeft;
      geometry::Size size;
      int width;
      int height;
      std::string npcName;
      std::string spritesheet;
      geometry::Direction direction;

      const TiXmlElement* objectElement = npcGroupElement->FirstChildElement("object");
      while(objectElement != nullptr)
      {
         objectElement->Attribute("x", &topLeft.x);
         objectElement->Attribute("y", &topLeft.y);

         // Attribute doesn't support unsigned ints, so we need to cast explicitly.
         objectElement->Attribute("width", &width);
         objectElement->Attribute("height", &height);
         size =
         {
            static_cast<unsigned int>(std::max(width, 0)),
            static_cast<unsigned int>(std::max(height, 0))
         };

         npcName = objectElement->Attribute("name");
         direction = geometry::Direction::DOWN;
         
         const auto propertiesElement = objectElement->FirstChildElement("properties");
         auto propertyElement = propertiesElement->FirstChildElement("property");
         while(propertyElement != nullptr)
         {
            if(std::string(propertyElement->Attribute("name")) == "spritesheet")
            {
               spritesheet = propertyElement->Attribute("value");
               break;
            }
            else if(std::string(propertyElement->Attribute("name")) == "direction")
            {
               direction = geometry::toDirection(propertyElement->Attribute("value"));
               if(direction == geometry::Direction::NONE)
               {
                  direction = geometry::Direction::DOWN;
               }
            }
            
            propertyElement = propertyElement->NextSiblingElement("property");
         }
         
         DEBUG("Found NPC %s at %d,%d with spritesheet %s, width %d and height %d.",
               npcName.c_str(), topLeft.x, topLeft.y, spritesheet.c_str(), size.width, size.height);

         if(size.width > 0 &&
            size.height > 0 &&
            !npcName.empty() &&
            !spritesheet.empty())
         {
            m_npcsToSpawn.emplace_back(NPCSpawnMarker{npcName, spritesheet, topLeft, size, direction});
         }

         objectElement = objectElement->NextSiblingElement("object");
      }
   }
}
Example #12
0
PlanContext LogicalAggregation::GetPlanContext() {
  lock_->acquire();
  if (NULL != plan_context_) {
    lock_->release();
    return *plan_context_;
  }
  PlanContext ret;
  const PlanContext child_context = child_->GetPlanContext();

  ChangeAggAttrsForAVG();
  // initialize expression of group_by_attrs and aggregation_attrs
  Schema* input_schema = GetSchema(child_context.attribute_list_);
  map<string, int> column_to_id;
  GetColumnToId(child_context.attribute_list_, column_to_id);
  for (int i = 0; i < group_by_attrs_.size(); ++i) {
    group_by_attrs_[i]->InitExprAtLogicalPlan(group_by_attrs_[i]->actual_type_,
                                              column_to_id, input_schema);
  }
  for (int i = 0; i < aggregation_attrs_.size(); ++i) {
    aggregation_attrs_[i]->InitExprAtLogicalPlan(
        aggregation_attrs_[i]->actual_type_, column_to_id, input_schema);
  }

  if (CanOmitHashRepartition(child_context)) {
    aggregation_style_ = kLocalAgg;
    LOG(INFO) << "Aggregation style: kLocalAgg" << std::endl;
  } else {  // as for the kLocalAggReparGlobalAgg style is optimal
            // to kReparAndGlobalAgg so it's set to be default.
    aggregation_style_ = kLocalAggReparGlobalAgg;
    LOG(INFO) << "Aggregation style: kLocalAggReparGlobalAgg" << std::endl;
  }
  switch (aggregation_style_) {
    case kLocalAgg: {
      ret.attribute_list_ = GetAttrsAfterAgg();
      ret.commu_cost_ = child_context.commu_cost_;
      ret.plan_partitioner_ = child_context.plan_partitioner_;
      Attribute partition_key =
          child_context.plan_partitioner_.get_partition_key();
      partition_key.table_id_ = INTERMEIDATE_TABLEID;
      ret.plan_partitioner_.set_partition_key(partition_key);
      for (unsigned i = 0; i < ret.plan_partitioner_.GetNumberOfPartitions();
           i++) {
        const unsigned cardinality =
            ret.plan_partitioner_.GetPartition(i)->get_cardinality();
        ret.plan_partitioner_.GetPartition(i)
            ->set_cardinality(EstimateGroupByCardinality(child_context) /
                              ret.plan_partitioner_.GetNumberOfPartitions());
      }
      break;
    }
    default: {
      /**
       * repartition aggregation is currently simplified.
       */

      // TODO(FZH): ideally, the partition properties (especially the the number
      // of partitions and partition style) after repartition aggregation should
      // be decided by the partition property enforcement.
      ret.attribute_list_ = GetAttrsAfterAgg();
      ret.commu_cost_ =
          child_context.commu_cost_ + child_context.GetAggregatedDatasize();
      ret.plan_partitioner_.set_partition_func(
          child_context.plan_partitioner_.get_partition_func());
      // set partition key
      if (group_by_attrs_.empty()) {
        ret.plan_partitioner_.set_partition_key(Attribute());
      } else {
        int id = 0;
        // if there is column in groupby attributes, so move it to the front, in
        // order to get partition by one column not one expression
        for (int i = 0; i < group_by_attrs_.size(); ++i) {
          if (group_by_attrs_[i]->expr_node_type_ == t_qcolcumns) {
            id = i;
            break;
          }
        }
        std::swap(group_by_attrs_[0], group_by_attrs_[id]);
        ret.plan_partitioner_.set_partition_key(
            group_by_attrs_[0]->ExprNodeToAttr(0));
      }

      NodeID location = 0;
      int64_t data_cardinality = EstimateGroupByCardinality(child_context);
      PartitionOffset offset = 0;
      PlanPartitionInfo par(offset, data_cardinality, location);
      std::vector<PlanPartitionInfo> partition_list;
      partition_list.push_back(par);
      ret.plan_partitioner_.set_partition_list(partition_list);
      break;
    }
  }
  plan_context_ = new PlanContext();
  *plan_context_ = ret;
  lock_->release();
  return ret;
}
void NormalDistribution::setLowerBound(double value) {
  impl()->setAttribute(Attribute("lower_bounds",value),false);
}
void NormalDistribution::setMean(double value) {
  impl()->setAttribute(Attribute("means",value),false);
}
Example #15
0
OSResult::OSResult(const QDomElement& element) {
  if (element.isNull()) {
    LOG_AND_THROW("Cannot construct OSResult from null QDomElement.");
  }
  if (element.tagName() != QString::fromStdString("OSResult")) {
    LOG_AND_THROW("Cannot construct OSResult from element named " << toString(element.tagName())
                  << " rather than OSResult.");
  }

  QDomElement valueElement = element.firstChildElement(QString::fromStdString("Value"));
  QDomElement errorsElement = element.firstChildElement(QString::fromStdString("Errors"));
  QDomElement warningsElement = element.firstChildElement(QString::fromStdString("Warnings"));
  QDomElement infoElement = element.firstChildElement(QString::fromStdString("Info"));
  QDomElement initialConditionElement = element.firstChildElement(QString::fromStdString("InitialCondition"));
  QDomElement finalConditionElement = element.firstChildElement(QString::fromStdString("FinalCondition"));
  QDomElement attributesElement = element.firstChildElement(QString::fromStdString("Attributes"));

  if (valueElement.isNull()) {
    LOG_AND_THROW("valueElement is null.");
  }

  m_value = OSResultValue(valueElement.firstChild().nodeValue().toStdString());

  if (!errorsElement.isNull()) {
    QDomNodeList childNodes = errorsElement.childNodes();
    for (int i = 0; i < childNodes.count(); ++i) {
      QDomElement childElement = childNodes.at(i).toElement();
      m_errors.push_back(logMessageFromXML(Error,childElement));
    }
  }

  if (!warningsElement.isNull()) {
    QDomNodeList childNodes = warningsElement.childNodes();
    for (int i = 0; i < childNodes.count(); ++i) {
      QDomElement childElement = childNodes.at(i).toElement();
      m_warnings.push_back(logMessageFromXML(Warn,childElement));
    }
  }

  if (!infoElement.isNull()) {
    QDomNodeList childNodes = infoElement.childNodes();
    for (int i = 0; i < childNodes.count(); ++i) {
      QDomElement childElement = childNodes.at(i).toElement();
      m_info.push_back(logMessageFromXML(Info,childElement));
    }
  }

  if (!initialConditionElement.isNull()) {
    QDomNodeList childNodes = initialConditionElement.childNodes();
    int n = childNodes.count();
    OS_ASSERT(n < 2);
    if (n > 0) {
      QDomElement childElement = childNodes.at(0).toElement();
      m_initialCondition = logMessageFromXML(Info,childElement);
    }
  }

  if (!finalConditionElement.isNull()) {
    QDomNodeList childNodes = finalConditionElement.childNodes();
    int n = childNodes.count();
    OS_ASSERT(n < 2);
    if (n > 0) {
      QDomElement childElement = childNodes.at(0).toElement();
      m_finalCondition = logMessageFromXML(Info,childElement);
    }
  }

  if (!attributesElement.isNull()) {
    QDomNodeList childNodes = attributesElement.childNodes();
    for (int i = 0; i < childNodes.count(); ++i) {
      QDomElement childElement = childNodes.at(i).toElement();
      m_attributes.push_back(Attribute(childElement));
    }
  }
}
Example #16
0
std::string XMLNode::AttributeString( const std::string& name , std::string defaultVar )
{
    XMLAttributePtr attr = Attribute(name);
    return attr ? attr->ValueString() : defaultVar;
}
  void OpenStudioPostProcessJob::startImpl(const std::shared_ptr<ProcessCreator> &)
  {
    QWriteLocker l(&m_mutex);

    JobErrors errors;
    errors.result = ruleset::OSResultValue::Success;
    
    try {
      m_sql = sqlFile();
      m_osm = osmFile();
      resetFiles(m_files, m_sql, m_osm);
    } catch (const std::exception &e) {
      JobErrors error;
      error.result = ruleset::OSResultValue::Fail;
      error.addError(ErrorType::Error, e.what());
      errors = error;
    }


    if (m_sql)
    {
      LOG(Info, "OpenStudioPostProcess starting, filename: " << toString(m_sql->fullPath));
    }

    LOG(Info, "OpenStudioPostProcess starting, outdir: " << toString(outdir()));

    l.unlock();

    emitStatusChanged(AdvancedStatus(AdvancedStatusEnum::Starting));

    emitStarted();
    emitStatusChanged(AdvancedStatus(AdvancedStatusEnum::Processing));

    if (errors.result == ruleset::OSResultValue::Fail)
    {
      setErrors(errors);
      return;
    }

    try {
      SqlFile sqlFile(m_sql->fullPath);

      boost::optional<openstudio::model::Model> model = model::Model::load(m_osm->fullPath);

      if (!model)
      {
        throw std::runtime_error("Unable to load model file from " + openstudio::toString(m_osm->fullPath));
      }

      model->setSqlFile(sqlFile);

      boost::filesystem::create_directories(outdir(true));

      std::vector<Attribute> attributes = PostProcessReporting::go(sqlFile,"OpenStudioPostProcess");

      // ETH@20140219 - Not great to add an object here either, but needed for
      // Facility, and Building is really the same case. (If get this far with 
      // simulation, no harm in accessing data through Building, which has 
      // smart defaults for all fields.)
      model::Building building = model->getUniqueModelObject<model::Building>();
      LOG(Debug,"Extracting attributes from model::Building.");
      boost::optional<Attribute> attribute;
      
      boost::optional<double> value = building.floorArea();
      if (value){
        attribute = Attribute("floorArea", *value, "m^2");
        attribute->setDisplayName("Floor Area");
        attributes.push_back(*attribute);
        attributes.back().setSource("OpenStudioPostProcess");
      }

      value = building.conditionedFloorArea();
      if (value){
        attribute = Attribute("conditionedFloorArea", *value, "m^2");
        attribute->setDisplayName("Conditioned Floor Area");
        attributes.push_back(*attribute);
        attributes.back().setSource("OpenStudioPostProcess");
      }

      // ETH@20140218 - Not great to add an object here, but otherwise, do not get 
      // calibration results table in PAT.
      model::Facility facility = model->getUniqueModelObject<model::Facility>();
      LOG(Debug,"Extracting attributes from model::Facility.");     

      value = facility.economicsCapitalCost();
      if (value){
        attribute = Attribute("economicsCapitalCost", *value, "$");
        attribute->setDisplayName("Capital Cost");
        attributes.push_back(*attribute);
        attributes.back().setSource("OpenStudioPostProcess");
      }

      value = facility.economicsTLCC();
      if (value){
        attribute = Attribute("economicsTLCC", *value, "$");
        attribute->setDisplayName("Total Life Cycle Cost");
        attributes.push_back(*attribute);
        attributes.back().setSource("OpenStudioPostProcess");
      }

      value = facility.annualWaterTotalCost();
      if (value){
        attribute = Attribute("annualWaterTotalCost", *value, "$");
        attribute->setDisplayName("Annual Water Total Cost");
        attributes.push_back(*attribute);
        attributes.back().setSource("OpenStudioPostProcess");
      }

      attribute = facility.endUsesAttribute();
      if (attribute){
        attributes.push_back(*attribute);
        attributes.back().setSource("OpenStudioPostProcess");
      }

      attribute = facility.calibrationResultAttribute();
      if (attribute){
        attributes.push_back(*attribute);
        attributes.back().setSource("OpenStudioPostProcess");
      }

      if (attributes.empty())
      {
        LOG(Warn, "No attributes loaded for report");
      }

      Attribute report("Report", attributes);
      bool result = report.saveToXml(outdir() / openstudio::toPath("report.xml"));
      if (!result){
        LOG_AND_THROW("Failed to write report.xml");
      }

    } catch (const std::exception &e) {
      LOG(Error, "Error with OpenStudioPostProcessJob: " + std::string(e.what()));
      errors.addError(ErrorType::Error, "Error with OpenStudioPostProcessJob: " + std::string(e.what()));
      errors.result = ruleset::OSResultValue::Fail;
    }

    // Change this to whatever output files you generate
    emitOutputFileChanged(RunManager_Util::dirFile(outdir() / openstudio::toPath("report.xml")));
    setErrors(errors);
  }
Example #18
0
static void query_select_fzh() {
  /*
   * select sum(a+1)+count(a),b
   * from T
   * group by b
   *
   * notation: p a p s
   * */
  unsigned long long int start = curtick();
  TableDescriptor* table =
      Environment::getInstance()->getCatalog()->getTable("LINEITEM");
  //===========================scan===========================
  LogicalOperator* scan = new LogicalScan(table->getProjectoin(0));

  //==========================project=========================
  vector<vector<ExpressionItem> > expr_list1;

  vector<ExpressionItem> expr1;
  vector<ExpressionItem> expr2;
  vector<ExpressionItem> expr3;
  vector<ExpressionItem> expr4;
  vector<ExpressionItem> expr5;
  vector<ExpressionItem> expr6;
  vector<ExpressionItem> expr7;
  vector<ExpressionItem> expr8;
  vector<ExpressionItem> expr9;
  vector<ExpressionItem> expr10;
  vector<ExpressionItem> expr11;
  vector<ExpressionItem> expr12;
  vector<ExpressionItem> expr13;
  vector<ExpressionItem> expr14;
  vector<ExpressionItem> expr15;
  vector<ExpressionItem> expr16;
  vector<ExpressionItem> expr17;

  ExpressionItem ei1;
  ExpressionItem ei1_1;
  ExpressionItem ei1_2;
  ExpressionItem ei1_3;
  ExpressionItem ei1_4;
  ExpressionItem ei1_5;
  ExpressionItem ei1_6;
  ExpressionItem ei1_7;
  ExpressionItem ei1_8;
  ExpressionItem ei1_9;
  ExpressionItem ei2;
  ExpressionItem ei3;
  ExpressionItem ei4;
  ExpressionItem ei5;
  ExpressionItem ei6;
  ExpressionItem ei7;
  ExpressionItem ei8;
  ExpressionItem ei9;
  ExpressionItem ei10;
  ExpressionItem ei11;
  ExpressionItem ei12;
  ExpressionItem ei13;
  ExpressionItem ei14;
  ExpressionItem ei15;
  ExpressionItem ei16;
  ExpressionItem ei17;

  ei1_1.setVariable("LINEITEM.row_id");
  //	ei1_2.setVariable("LINEITEM.L_ORDERKEY");
  ei1_2.setIntValue("1");
  ei1_3.setOperator("+");

  expr1.push_back(ei1_1);
  expr1.push_back(ei1_2);
  expr1.push_back(ei1_3);

  expr_list1.push_back(expr1);

  LogicalOperator* project1 = new LogicalProject(scan, expr_list1);

  //========================aggregation=======================
  std::vector<Attribute> group_by_attributes;
  group_by_attributes.push_back(table->getAttribute("L_RETURNFLAG"));
  group_by_attributes.push_back(table->getAttribute("L_LINESTATUS"));
  std::vector<Attribute> aggregation_attributes;
  aggregation_attributes.push_back(table->getAttribute("L_QUANTITY"));
  aggregation_attributes.push_back(table->getAttribute("L_EXTENDEDPRICE"));
  aggregation_attributes.push_back(table->getAttribute("L_DISCOUNT"));
  aggregation_attributes.push_back(Attribute(ATTRIBUTE_ANY));

  std::vector<PhysicalAggregation::State::Aggregation> aggregation_function;

  aggregation_function.push_back(PhysicalAggregation::State::kSum);
  aggregation_function.push_back(PhysicalAggregation::State::kSum);
  aggregation_function.push_back(PhysicalAggregation::State::kSum);
  aggregation_function.push_back(PhysicalAggregation::State::kCount);
  LogicalOperator* aggregation =
      new LogicalAggregation(group_by_attributes, aggregation_attributes,
                             aggregation_function, project1);

  //==========================project=========================
  vector<vector<ExpressionItem> > expr_list2;

  ExpressionItem ei21_1;
  ei21_1.setVariable("LINEITEM.row_id+1");
  vector<ExpressionItem> expr21;
  expr21.push_back(ei21_1);
  expr_list2.push_back(expr21);
  LogicalOperator* project2 = new LogicalProject(project1, expr_list2);
  //===========================root===========================
  LogicalOperator* root =
      new LogicalQueryPlanRoot(0, project2, LogicalQueryPlanRoot::PRINT);

  cout << "performance is ok!" << endl;
  PhysicalOperatorBase* physical_iterator_tree =
      root->GetPhysicalPlan(64 * 1024);
  //	physical_iterator_tree->print();
  physical_iterator_tree->Open();
  while (physical_iterator_tree->Next(0))
    ;
  physical_iterator_tree->Close();
  printf("Q1: execution time: %4.4f second.\n", getSecond(start));
}
	AttributeText<EscapeStream::Attribute> EscapeStream::flush(char numchar)
	{
		string s = ss.str();
		AttributeText<Attribute> rtn;

		for (size_t i = 0; i < s.size(); i++)
		{
			if (isprint(s[i]))
			{
				rtn.push_back(s[i]);
			}
			else
			{
				if (string("\n\r\t\b\x7f\a\x5").find(s[i]) != string::npos)
				{
					rtn.push_back(0, Attribute(string(1, s[i])));
				}
				else if (s[i] == '\033')
				{
					i++;
					if (i >= s.size())
					{
						break;
					}
					else if (s[i] != '[')
					{
						continue;
					}

					i++;
					if (i >= s.size())
					{
						break;
					}

					if (string("ABCDEFGJKSTmsu").find(s[i]) != string::npos)
					{
						rtn.push_back(0, Attribute(string("\033[")+s[i]));
					}
					else if (s[i] == 'i')
					{
						i++;
						if (i >= s.size())
						{
							break;
						}
						else if (s[i] != '@')
						{
							continue;
						}

						int j = 0;
						while(s[i+1+j] != '@' && i+1+j < s.size())
							j++;

						if (i+1+j >= s.size())
						{
							break;
						}
						else if (j == 0)
						{
							i++;
							continue;
						}
						else
						{
							rtn.push_back(0, Attribute(string("\033[i@"+s.substr(i+1, j)+"@")));
						}
					}
					else if (s[i] == '?')
					{
						int j = 0;
						while(isdigit(s[i+1+j]) && i+1+j < s.size())
							j++;

						if (i+1+j >= s.size())
						{
							break;
						}
						else if (j == 0)
						{
							i++;
							continue;
						}
						else
						{
							Attribute a;
							a.i1 = atoi(s.substr(i+1, j).c_str());
							i += 1+j;

							if (s[i] == 'l' || s[i] == 'h')
							{
								a.escape = string("\033[?")+s.substr(i-j-1, j)+s[i];
								rtn.push_back(0, a);
							}
						}
					}
					else
					{
						int j = 0;
						while (isdigit(s[i+1+j]) && i+1+j < s.size())
							j++;

						if (i+1+j >= s.size())
						{
							break;
						}
						else if (j == 0)
						{
							i++;
							continue;
						}
						else
						{
							Attribute a;
							string s1 = s.substr(i+1, j);
							a.i1 = atoi(s1.c_str());
							i += 1+j;

							if (string("ABCDEFGJKSTnm").find(s[i]) != string::npos)
							{
								a.escape = string("\033[")+s1+s[i];
								rtn.push_back(0, a);
							}
							else if (s[i] == ';')
							{
								int k = 0;
								while(isdigit(s[i+1+k]) && i+1+k < s.size())
									k++;

								if (i+1+k >= s.size())
								{
									break;
								}
								else if (k == 0)
								{
									i++;
									continue;
								}
								else
								{
									string s2 = s.substr(i+1, k);
									a.i2 = atoi(s2.c_str());
									i += 1+k;

									if (string("Hfm").find(s[i]) != string::npos)
									{
										a.escape = string("\033[")+s1+";"+s2+s[i];
										rtn.push_back(0, a);
									}
								}
							}
						}
					}
				}
			}
		}

		ss.str("");
		return rtn;
	}
Example #20
0
    SpriteAnimDefinition* SpriteAnimDefinition::createFromFile(const std::string& filename, onut::ContentManager* pContentManager)
    {
        SpriteAnimDefinition* pRet = new SpriteAnimDefinition();

        pRet->m_filename = pContentManager->find(filename);
        if (pRet->m_filename.empty())
        {
            pRet->m_filename = filename;
        }

        tinyxml2::XMLDocument doc;
        doc.LoadFile(pRet->m_filename.c_str());
        auto pXMLSheet = doc.FirstChildElement("sheet");
        assert(pXMLSheet);
        std::string textureName = pXMLSheet->Attribute("texture");
        onut::Texture* pTexture = pContentManager->getResource<onut::Texture>(textureName);
        assert(pTexture);
        int spriteW = pTexture->getSize().x;
        int spriteH = pTexture->getSize().y;
        int originX = 0;
        int originY = 0;
        pXMLSheet->QueryAttribute("spriteWidth", &spriteW);
        pXMLSheet->QueryAttribute("spriteHeight", &spriteH);
        pXMLSheet->QueryAttribute("originX", &originX);
        pXMLSheet->QueryAttribute("originY", &originY);
        Vector2 origin((float)originX / (float)spriteW, (float)originY / (float)spriteH);
        for (auto pXMLAnim = pXMLSheet->FirstChildElement("anim"); pXMLAnim; pXMLAnim = pXMLAnim->NextSiblingElement("anim"))
        {
            std::string name = pXMLAnim->Attribute("name");
            auto& anim = pRet->m_anims[name];
            int fps = 30;
            pXMLAnim->QueryAttribute("fps", &fps);
            pXMLAnim->QueryAttribute("loop", &anim.loop);
            Frame frame;
            frame.pTexture = pTexture;
            frame.origin = origin;
            for (auto pXMLFrame = pXMLAnim->FirstChildElement("frame"); pXMLFrame; pXMLFrame = pXMLFrame->NextSiblingElement("frame"))
            {
                int repeat = 1;
                int id = 0;
                pXMLFrame->QueryAttribute("id", &id);
                pXMLFrame->QueryAttribute("repeat", &repeat);
                int col = id % (pTexture->getSize().x / spriteW);
                int row = id / (pTexture->getSize().x / spriteW);
                col *= spriteW;
                row *= spriteH;
                frame.UVs = Vector4(
                    (float)col / (float)pTexture->getSize().x,
                    (float)row / (float)pTexture->getSize().y,
                    (float)(col + spriteW) / (float)pTexture->getSize().x,
                    (float)(row + spriteH) / (float)pTexture->getSize().y);
                for (auto i = 0; i < repeat; ++i)
                {
                    anim.frames.push_back(frame);
                }
            }
            anim.frames.push_back(frame); // Repeat last frame
            anim.duration = (float)anim.frames.size() / (float)fps;
        }

        return pRet;
    }
void LognormalDistribution::setLambda(double value) {
  impl()->setAttribute(Attribute("lambdas",value),false);
}
Example #22
0
void 
XmlElement::addAttribute( std::string attributeName,
                          std::string value  )
{
  m_attributes.push_back( Attribute( attributeName, value ) );
}
Example #23
0
 inline void 
 construct(Attribute& attr, Iterator const& first, Iterator const& last)
 {
     attr = Attribute(first, last);
 }
Example #24
0
Character::Character(const appearance &appearance) : effects(this), waypoints(this), _world(World::get()), _appearance(appearance), attributes(ATTRIBUTECOUNT) {
    setAlive(true);
    for (int i = 0; i < MAX_BODY_ITEMS + MAX_BELT_SLOTS; ++i) {
        characterItems[ i ].reset();
    }

    attributes[strength] = Attribute(0, MAXATTRIB);
    attributes[dexterity] = Attribute(0, MAXATTRIB);
    attributes[constitution] = Attribute(0, MAXATTRIB);
    attributes[agility] = Attribute(0, MAXATTRIB);
    attributes[intelligence] = Attribute(0, MAXATTRIB);
    attributes[perception] = Attribute(0, MAXATTRIB);
    attributes[willpower] = Attribute(0, MAXATTRIB);
    attributes[essence] = Attribute(0, MAXATTRIB);
    attributes[hitpoints] = Attribute(0, MAXHPS);
    attributes[mana] = Attribute(0, MAXMANA);
    attributes[foodlevel] = Attribute(0, MAXFOOD);
    attributes[sex] = Attribute(0);
    attributes[age] = Attribute(0);
    attributes[weight] = Attribute(0);
    attributes[height] = Attribute(0);
    attributes[attitude] = Attribute(0);
    attributes[luck] = Attribute(0);

    backPackContents = nullptr;

    magic.type = MAGE;
    magic.flags[ MAGE ] = 0x00000000;
    magic.flags[ PRIEST ] = 0x00000000;
    magic.flags[ BARD ] = 0x00000000;
    magic.flags[ DRUID ] = 0x00000000;
}
void BufferGeometry::computeTangents() {

  // based on http://www.terathon.com/code/tangent.html
  // (per vertex tangents)

  if ( !attributes.contains( AttributeKey::index() ) ||
       !attributes.contains( AttributeKey::position() ) ||
       !attributes.contains( AttributeKey::normal() ) ||
       !attributes.contains( AttributeKey::uv() ) ) {

    console().warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
    return;

  }

  const auto& indices   = attributes[ AttributeKey::index() ].array;
  const auto& positions = attributes[ AttributeKey::position() ].array;
  const auto& normals   = attributes[ AttributeKey::normal() ].array;
  const auto& uvs       = attributes[ AttributeKey::uv() ].array;

  const auto nVertices = ( int )positions.size() / 3;

  if ( !attributes.contains( AttributeKey::tangent() ) ) {
    const auto nTangentElements = 4 * nVertices;
    attributes[ AttributeKey::tangent() ] = Attribute( THREE::v4, nTangentElements );
  }

  auto& tangents = attributes[ AttributeKey::tangent() ].array;

  std::vector<Vector3> tan1( nVertices ), tan2( nVertices );

  float xA, yA, zA,
        xB, yB, zB,
        xC, yC, zC,

        uA, vA,
        uB, vB,
        uC, vC,

        x1, x2, y1, y2, z1, z2,
        s1, s2, t1, t2, r;

  Vector3 sdir, tdir;

  auto handleTriangle = [&]( size_t a, size_t b, size_t c ) {

    xA = positions[ a * 3 ];
    yA = positions[ a * 3 + 1 ];
    zA = positions[ a * 3 + 2 ];

    xB = positions[ b * 3 ];
    yB = positions[ b * 3 + 1 ];
    zB = positions[ b * 3 + 2 ];

    xC = positions[ c * 3 ];
    yC = positions[ c * 3 + 1 ];
    zC = positions[ c * 3 + 2 ];

    uA = uvs[ a * 2 ];
    vA = uvs[ a * 2 + 1 ];

    uB = uvs[ b * 2 ];
    vB = uvs[ b * 2 + 1 ];

    uC = uvs[ c * 2 ];
    vC = uvs[ c * 2 + 1 ];

    x1 = xB - xA;
    x2 = xC - xA;

    y1 = yB - yA;
    y2 = yC - yA;

    z1 = zB - zA;
    z2 = zC - zA;

    s1 = uB - uA;
    s2 = uC - uA;

    t1 = vB - vA;
    t2 = vC - vA;

    r = 1.0f / ( s1 * t2 - s2 * t1 );

    sdir.set(
      ( t2 * x1 - t1 * x2 ) * r,
      ( t2 * y1 - t1 * y2 ) * r,
      ( t2 * z1 - t1 * z2 ) * r
    );

    tdir.set(
      ( s1 * x2 - s2 * x1 ) * r,
      ( s1 * y2 - s2 * y1 ) * r,
      ( s1 * z2 - s2 * z1 ) * r
    );

    tan1[ a ].add( sdir );
    tan1[ b ].add( sdir );
    tan1[ c ].add( sdir );

    tan2[ a ].add( tdir );
    tan2[ b ].add( tdir );
    tan2[ c ].add( tdir );

  };

  for ( size_t j = 0, jl = offsets.size(); j < jl; ++ j ) {

    const auto start = offsets[ j ].start;
    const auto count = offsets[ j ].count;
    const auto index = offsets[ j ].index;

    for ( auto i = start, il = start + count; i < il; i += 3 ) {

      const auto iA = index + ( int )indices[ i ];
      const auto iB = index + ( int )indices[ i + 1 ];
      const auto iC = index + ( int )indices[ i + 2 ];

      handleTriangle( iA, iB, iC );

    }

  }

  Vector3 tmp, tmp2;
  Vector3 n, n2;

  auto handleVertex = [&]( size_t v ) {

    n.x = normals[ v * 3 ];
    n.y = normals[ v * 3 + 1 ];
    n.z = normals[ v * 3 + 2 ];

    n2.copy( n );

    const auto& t = tan1[ v ];

    // Gram-Schmidt orthogonalize

    tmp.copy( t );
    tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();

    // Calculate handedness

    tmp2.crossVectors( n2, t );
    const auto test = tmp2.dot( tan2[ v ] );
    const auto w = ( test < 0.0f ) ? -1.0f : 1.0f;

    tangents[ v * 4 ]     = tmp.x;
    tangents[ v * 4 + 1 ] = tmp.y;
    tangents[ v * 4 + 2 ] = tmp.z;
    tangents[ v * 4 + 3 ] = w;

  };

  for ( size_t j = 0, jl = offsets.size(); j < jl; ++ j ) {

    const auto start = offsets[ j ].start;
    const auto count = offsets[ j ].count;
    const auto index = offsets[ j ].index;

    for ( auto i = start, il = start + count; i < il; i += 3 ) {

      const auto iA = index + ( int )indices[ i ];
      const auto iB = index + ( int )indices[ i + 1 ];
      const auto iC = index + ( int )indices[ i + 2 ];

      handleVertex( iA );
      handleVertex( iB );
      handleVertex( iC );

    }

  }

  hasTangents = true;
  tangentsNeedUpdate = true;

}
 SequentialSearchOptions_Impl::SequentialSearchOptions_Impl(int objectiveToMinimizeFirst)
   : AlgorithmOptions_Impl()
 {
   saveOption(Attribute("objectiveToMinimizeFirst",objectiveToMinimizeFirst));
 }
Example #27
0
 Attribute Object::openAttribute (const std::string& name, /*AttributeAccess*/PropList aapl) const {
   return Attribute (Exception::check ("H5Aopen", H5Aopen (handle (), name.c_str (), aapl.handleOrDefault ())));
 }
Example #28
0
boost::optional<openstudio::BCLMeasure> BCLMeasureDialog::createMeasure()
{
  openstudio::path userMeasuresDir = BCLMeasure::userMeasuresDir();

  if (isNetworkPath(userMeasuresDir) && !isNetworkPathAvailable(userMeasuresDir)) {
    QMessageBox::information(this, "Cannot Create Measure", "Your My Measures Directory appears to be on a network drive that is not currently available.\nYou can change your specified My Measures Directory using 'Preferences->Change My Measures Directory'.", QMessageBox::Ok);
    return boost::optional<openstudio::BCLMeasure>();
  }

  std::string name = toString(m_nameLineEdit->text());
  std::string className = BCLMeasure::makeClassName(name);
  std::string lowerClassName = toUnderscoreCase(className);
  std::string description = toString(m_descriptionTextEdit->toPlainText());
  std::string modelerDescription = toString(m_modelerDescriptionTextEdit->toPlainText());

  std::string measureTypeStr = toString(m_measureTypeComboBox->currentText());
  MeasureType measureType;
  if ( measureTypeStr == "OpenStudio Measure"){
    measureType = MeasureType::ModelMeasure;
  }else if ( measureTypeStr == "EnergyPlus Measure"){
    measureType = MeasureType::EnergyPlusMeasure;
  }else if ( measureTypeStr == "Utility Measure"){
    measureType = MeasureType::UtilityMeasure;
  }else if ( measureTypeStr == "Reporting Measure"){
    measureType = MeasureType::ReportingMeasure;
  }

  QString folderName = toQString(lowerClassName).append("/");
  openstudio::path measureDir = userMeasuresDir / toPath(folderName);

  // prompt user ???
  if (openstudio::filesystem::exists(measureDir)){
    int i = 1;
    while (openstudio::filesystem::exists(measureDir)){
      folderName = toQString(lowerClassName).append(" ").append(QString::number(i)).append("/");
      measureDir = userMeasuresDir / toPath(folderName);
      ++i;
    }
    // DLM: do we want to alter the class name to indicate this copy?
    //className = className + toString(QString::number(i));
    //lowerClassName = lowerClassName + toString(QString::number(i));
  }

  QStringList taxonomyParts;
  QString taxonomyFirstLevel = m_taxonomyFirstLevelComboBox->currentText();
  QString taxonomySecondLevel = m_taxonomySecondLevelComboBox->currentText();
  taxonomyParts << taxonomyFirstLevel;
  if (!taxonomySecondLevel.isEmpty()){
    taxonomyParts << taxonomySecondLevel;
  }
  std::string taxonomyTag = toString(taxonomyParts.join("."));

  std::vector<Attribute> attributes;

  QList<QListWidgetItem *> items = m_intendedSoftwareToolListWidget->findItems(".*", Qt::MatchRegExp);
  for (QListWidgetItem * item : items){
    if (item->checkState() == Qt::Checked){
      std::string intendedSoftwareTool = toString(item->text());
      attributes.push_back(Attribute("Intended Software Tool", intendedSoftwareTool));
    }
  }

  items = m_intendedUseCaseListWidget->findItems(".*", Qt::MatchRegExp);
  for (QListWidgetItem * item : items){
    if (item->checkState() == Qt::Checked){
      std::string intendedUseCase = toString(item->text());
      attributes.push_back(Attribute("Intended Use Case", intendedUseCase));
    }
  }

  boost::optional<BCLMeasure> result;
  if (m_bclMeasureToCopy){
    // have measure to copy, use clone
    result = m_bclMeasureToCopy->clone(measureDir);
    if (result){
      result->changeUID();

      // change the files on disk
      result->updateMeasureScript(m_bclMeasureToCopy->measureType(), measureType,
                                  m_bclMeasureToCopy->className(), className,
                                  name, description, modelerDescription);

      result->updateMeasureTests(m_bclMeasureToCopy->className(), className);

      result->checkForUpdatesFiles();

      // change the xml
      std::string lowerClassName = toUnderscoreCase(className);

      result->setName(lowerClassName);
      result->setClassName(className);
      result->setDisplayName(name);
      result->setDescription(description);
      result->setModelerDescription(modelerDescription);
      result->setArguments(m_bclMeasureToCopy->arguments());
      result->setTaxonomyTag(taxonomyTag);
      result->setMeasureType(measureType);

      // xml checksum is out of date

      for (const Attribute& attribute : attributes){
        result->addAttribute(attribute);
      }

      result->save();
    }
  }else{
    try{
    // starting new measure
    result = BCLMeasure(name, className, measureDir, taxonomyTag, measureType, description, modelerDescription);

    for (const Attribute& attribute : attributes){
      result->addAttribute(attribute);
    }

    result->save();
    }catch(std::exception&){
    }
  }

  return result;
}
Example #29
0
bool TmxTileset::parseElement(void* p, const std::string& path)
{
    _terrainTypes.clear();
    _tiles.clear();

    auto element = static_cast<tinyxml2::XMLElement*>(p);

    if(!element)
    {
        return false;
    }

    _path = "";

    tinyxml2::XMLDocument tsxDocument;

    if(element->Attribute("source"))
    {
        _source = element->Attribute("source");

        std::string tsxPath = path + _source;

        if(tsxDocument.LoadFile(tsxPath.c_str())
                != tinyxml2::XML_NO_ERROR)
        {
            return false;
        }

        element = tsxDocument.FirstChildElement("tileset");

        auto separatorPos = tsxPath.find_last_of("/\\");

        if (separatorPos != std::string::npos)
        {
            _path = tsxPath.substr(0, separatorPos + 1);
        }
    }
    else
    {
        _source = "";
    }

    if(element->Attribute("name"))
    {
        _name = element->Attribute("name");
    }
    else
    {
        _name = "";
    }

    _firstGid = 1;
    _tileWidth = 0;
    _tileHeight = 0;
    _spacing = 0;
    _margin = 0;
    _offsetX = 0;
    _offsetY = 0;
    _tileCount = 0;

    element->QueryIntAttribute("firstgid", &_firstGid);
    element->QueryIntAttribute("tilewidth", &_tileWidth);
    element->QueryIntAttribute("tileheight", &_tileHeight);
    element->QueryIntAttribute("spacing", &_spacing);
    element->QueryIntAttribute("margin", &_margin);
    element->QueryIntAttribute("tilecount", &_tileCount);

    auto propertiesElement = element->FirstChildElement("properties");
    auto imageElement = element->FirstChildElement("image");
    auto terrainTypesElement = element->FirstChildElement("terraintypes");
    auto tileElement = element->FirstChildElement("tile");
    auto tileOffsetElement = element->FirstChildElement("tileoffset");

    if(tileOffsetElement)
    {
        tileOffsetElement->QueryIntAttribute("x", &_offsetX);
        tileOffsetElement->QueryIntAttribute("y", &_offsetY);
    }

    _image.parseElement(imageElement);
    _properties.parseElement(propertiesElement);

    while(tileElement)
    {
        _tiles.push_back(TmxTilesetTile());
        _tiles.back().parseElement(tileElement);

        tileElement = tileElement->NextSiblingElement("tile");
    }

    if(terrainTypesElement)
    {
        auto terrainTypeElement = terrainTypesElement->FirstChildElement("terrain");

        while(terrainTypeElement)
        {
            _terrainTypes.push_back(TmxTerrainType());
            _terrainTypes.back().parseElement(terrainTypeElement);

            terrainTypeElement = terrainTypeElement->NextSiblingElement("terraintype");
        }
    }

    return true;
}
Example #30
0
	char* XMLElement::ParseAttributes(char* p)
	{
		const char* start = p;
		XMLAttribute* prevAttribute = 0;

		// Read the attributes.
		while (p)
		{
			p = XMLUtil::SkipWhiteSpace(p);
			if (!p || !(*p))
			{
				_document->SetError(XML_ERROR_PARSING_ELEMENT, start, Name());
				return 0;
			}

			// attribute.
			if (XMLUtil::IsNameStartChar(*p))
			{
				XMLAttribute* attrib = new (_document->_attributePool.Alloc()) XMLAttribute();
				attrib->_memPool = &_document->_attributePool;
				attrib->_memPool->SetTracked();

				p = attrib->ParseDeep(p, _document->ProcessEntities());
				if (!p || Attribute(attrib->Name()))
				{
					DeleteAttribute(attrib);
					_document->SetError(XML_ERROR_PARSING_ATTRIBUTE, start, p);
					return 0;
				}
				// There is a minor bug here: if the attribute in the source xml
				// document is duplicated, it will not be detected and the
				// attribute will be doubly added. However, tracking the 'prevAttribute'
				// avoids re-scanning the attribute list. Preferring performance for
				// now, may reconsider in the future.
				if (prevAttribute)
				{
					prevAttribute->_next = attrib;
				}
				else
				{
					_rootAttribute = attrib;
				}
				prevAttribute = attrib;
			}
			// end of the tag
			else if (*p == '/' && *(p + 1) == '>')
			{
				_closingType = CLOSED;
				return p + 2;	// done; sealed element.
			}
			// end of the tag
			else if (*p == '>')
			{
				++p;
				break;
			}
			else
			{
				_document->SetError(XML_ERROR_PARSING_ELEMENT, start, p);
				return 0;
			}
		}
		return p;
	}