Ejemplo n.º 1
0
void BooksDBUtil::addTag(shared_ptr<Book> book, shared_ptr<Tag> tag) {
	if (book->addTag(tag)) {
		BooksDB::Instance().saveTags(book);
	}
}
Ejemplo n.º 2
0
   bool
   PersistentRuleCriteria::ReadObject(shared_ptr<RuleCriteria> pRuleCriteria, shared_ptr<DALRecordset> pRS)
   {
      if (pRS->IsEOF())
         return false;

      pRuleCriteria->SetID(pRS->GetLongValue("criteriaid"));
      pRuleCriteria->SetRuleID(pRS->GetLongValue("criteriaruleid"));
      pRuleCriteria->SetMatchValue(pRS->GetStringValue("criteriamatchvalue"));
      pRuleCriteria->SetPredefinedField((RuleCriteria::PredefinedField) pRS->GetLongValue("criteriapredefinedfield"));
      pRuleCriteria->SetMatchType((RuleCriteria::MatchType) pRS->GetLongValue("criteriamatchtype"));
      pRuleCriteria->SetHeaderField(pRS->GetStringValue("criteriaheadername"));
      pRuleCriteria->SetUsePredefined(pRS->GetLongValue("criteriausepredefined") ? true : false);

      return true;
   }
int feature_extraction_pipeline(int argc, char** argv) {
  ::google::InitGoogleLogging(argv[0]);
  const int num_required_args = 7;
  if (argc < num_required_args) {
    LOG(ERROR)<<
    "This program takes in a trained network and an input data layer, and then"
    " extract features of the input data produced by the net.\n"
    "Usage: extract_features  pretrained_net_param"
    "  feature_extraction_proto_file  extract_feature_blob_name1[,name2,...]"
    "  save_feature_dataset_name1[,name2,...]  num_mini_batches  db_type"
    "  [CPU/GPU] [DEVICE_ID=0]\n"
    "Note: you can extract multiple features in one pass by specifying"
    " multiple feature blob names and dataset names seperated by ','."
    " The names cannot contain white space characters and the number of blobs"
    " and datasets must be equal.";
    return 1;
  }
  int arg_pos = num_required_args;

  arg_pos = num_required_args;
  if (argc > arg_pos && strcmp(argv[arg_pos], "GPU") == 0) {
    LOG(ERROR)<< "Using GPU";
    uint device_id = 0;
    if (argc > arg_pos + 1) {
      device_id = atoi(argv[arg_pos + 1]);
      CHECK_GE(device_id, 0);
    }
    LOG(ERROR) << "Using Device_id=" << device_id;
    Caffe::SetDevice(device_id);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(ERROR) << "Using CPU";
    Caffe::set_mode(Caffe::CPU);
  }

  arg_pos = 0;  // the name of the executable
  std::string pretrained_binary_proto(argv[++arg_pos]);

  // Expected prototxt contains at least one data layer such as
  //  the layer data_layer_name and one feature blob such as the
  //  fc7 top blob to extract features.
  /*
   layers {
     name: "data_layer_name"
     type: DATA
     data_param {
       source: "/path/to/your/images/to/extract/feature/images_leveldb"
       mean_file: "/path/to/your/image_mean.binaryproto"
       batch_size: 128
       crop_size: 227
       mirror: false
     }
     top: "data_blob_name"
     top: "label_blob_name"
   }
   layers {
     name: "drop7"
     type: DROPOUT
     dropout_param {
       dropout_ratio: 0.5
     }
     bottom: "fc7"
     top: "fc7"
   }
   */
  std::string feature_extraction_proto(argv[++arg_pos]);
  shared_ptr<Net<Dtype> > feature_extraction_net(
      new Net<Dtype>(feature_extraction_proto, caffe::TEST));
  feature_extraction_net->CopyTrainedLayersFrom(pretrained_binary_proto);

  std::string extract_feature_blob_names(argv[++arg_pos]);
  std::vector<std::string> blob_names;
  caffe::string_split(&blob_names, extract_feature_blob_names, ",");

  std::string save_feature_dataset_names(argv[++arg_pos]);
  std::vector<std::string> dataset_names;
  caffe::string_split(&dataset_names, save_feature_dataset_names, ",");
  CHECK_EQ(blob_names.size(), dataset_names.size()) <<
      " the number of blob names and dataset names must be equal";
  size_t num_features = blob_names.size();

  for (size_t i = 0; i < num_features; i++) {
    CHECK(feature_extraction_net->has_blob(blob_names[i]))
        << "Unknown feature blob name " << blob_names[i]
        << " in the network " << feature_extraction_proto;
  }

  int num_mini_batches = atoi(argv[++arg_pos]);

  std::vector<shared_ptr<db::DB> > feature_dbs;
  std::vector<shared_ptr<db::Transaction> > txns;
  const char* db_type = argv[++arg_pos];
  for (size_t i = 0; i < num_features; ++i) {
    LOG(INFO)<< "Opening dataset " << dataset_names[i];
    shared_ptr<db::DB> db(db::GetDB(db_type));
    db->Open(dataset_names.at(i), db::NEW);
    feature_dbs.push_back(db);
    shared_ptr<db::Transaction> txn(db->NewTransaction());
    txns.push_back(txn);
  }

  LOG(ERROR)<< "Extacting Features";

  Datum datum;
  const int kMaxKeyStrLength = 100;
  char key_str[kMaxKeyStrLength];
  std::vector<Blob<float>*> input_vec;
  std::vector<int> image_indices(num_features, 0);
  for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index) {
    feature_extraction_net->Forward(input_vec);
    for (int i = 0; i < num_features; ++i) {
      const shared_ptr<Blob<Dtype> > feature_blob = feature_extraction_net
          ->blob_by_name(blob_names[i]);
      int batch_size = feature_blob->num();
      int dim_features = feature_blob->count() / batch_size;
      const Dtype* feature_blob_data;
      for (int n = 0; n < batch_size; ++n) {
        datum.set_height(feature_blob->height());
        datum.set_width(feature_blob->width());
        datum.set_channels(feature_blob->channels());
        datum.clear_data();
        datum.clear_float_data();
        feature_blob_data = feature_blob->cpu_data() +
            feature_blob->offset(n);
        for (int d = 0; d < dim_features; ++d) {
          datum.add_float_data(feature_blob_data[d]);
        }
        int length = snprintf(key_str, kMaxKeyStrLength, "%010d",
            image_indices[i]);
        string out;
        CHECK(datum.SerializeToString(&out));
        txns.at(i)->Put(std::string(key_str, length), out);
        ++image_indices[i];
        if (image_indices[i] % 1000 == 0) {
          txns.at(i)->Commit();
          txns.at(i).reset(feature_dbs.at(i)->NewTransaction());
          LOG(ERROR)<< "Extracted features of " << image_indices[i] <<
              " query images for feature blob " << blob_names[i];
        }
      }  // for (int n = 0; n < batch_size; ++n)
    }  // for (int i = 0; i < num_features; ++i)
  }  // for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index)
  // write the last batch
  for (int i = 0; i < num_features; ++i) {
    if (image_indices[i] % 1000 != 0) {
      txns.at(i)->Commit();
    }
    LOG(ERROR)<< "Extracted features of " << image_indices[i] <<
        " query images for feature blob " << blob_names[i];
    feature_dbs.at(i)->Close();
  }

  LOG(ERROR)<< "Successfully extracted the features!";
  return 0;
}
Ejemplo n.º 4
0
 bool operator== (int num) {
   std::unique_lock<std::mutex> lck(*mtx_);
   cv_->wait(lck, [this, num]()->bool { return *count_ == num; });
   *count_ = 0;
   return true;
 }
Ejemplo n.º 5
0
/*! Constitutive law */
void FCPM::go(shared_ptr<IGeom>& _geom, shared_ptr<IPhys>& _phys, Interaction* I){

	
	const ScGeom& geom=*static_cast<ScGeom*>(_geom.get());
	FreshConcretePhys& phys=*static_cast<FreshConcretePhys*>(_phys.get());

	const int id1 = I->getId1();
	const int id2 = I->getId2();
	
	const BodyContainer& bodies = *scene->bodies;

	const State& de1 = *static_cast<State*>(bodies[id1]->state.get());
	const State& de2 = *static_cast<State*>(bodies[id2]->state.get());

//Calculation of the max penetretion and the radius of the overlap area 
	Sphere* s1=dynamic_cast<Sphere*>(bodies[id1]->shape.get());
	Sphere* s2=dynamic_cast<Sphere*>(bodies[id2]->shape.get());

	Real dist;
	Real contactRadius;
	Real OverlapRadius;

	if (s1 and s2) {
		phys.maxPenetration=s1->radius * phys.Penetration1 + s2->radius * phys.Penetration2;
		dist = s1->radius + s2->radius - geom.penetrationDepth;
		OverlapRadius = pow(((4 * pow(dist,2) * pow(s1->radius,2) - pow((pow(dist,2) - pow(s2->radius,2) + pow(s1->radius,2)),2)) / (4 * pow(dist,2))),(1.0/2.0));
		//contactRadius = (pow(s1->radius,2) + pow(s2->radius,2))/(s1->radius + s2->radius);
		contactRadius = s1->radius;
	} else if (s1 and not(s2)) {
		phys.maxPenetration=s1->radius * phys.Penetration1;
		dist = s1->radius - geom.penetrationDepth;
		OverlapRadius =pow((pow(s1->radius,2) - pow(dist,2)),(1.0/2.0));
		contactRadius = s1->radius;
	} else {
		phys.maxPenetration=s2->radius * phys.Penetration2;
		dist = s2->radius - geom.penetrationDepth;
		OverlapRadius = pow((pow(s2->radius,2) - pow(dist,2)),(1.0/2.0));
		contactRadius = s2->radius;
	}


	Vector3r& shearForce = phys.shearForce;
	if (I->isFresh(scene)) shearForce=Vector3r(0,0,0);
	const Real& dt = scene->dt;
	shearForce = geom.rotate(shearForce);


	// Handle periodicity.
	const Vector3r shift2 = scene->isPeriodic ? scene->cell->intrShiftPos(I->cellDist): Vector3r::Zero(); 
	const Vector3r shiftVel = scene->isPeriodic ? scene->cell->intrShiftVel(I->cellDist): Vector3r::Zero(); 

	const Vector3r c1x = (geom.contactPoint - de1.pos);
	const Vector3r c2x = (geom.contactPoint - de2.pos - shift2);
	
	const Vector3r relativeVelocity = (de1.vel+de1.angVel.cross(c1x)) - (de2.vel+de2.angVel.cross(c2x)) + shiftVel;
	const Real normalVelocity	= geom.normal.dot(relativeVelocity);
	const Vector3r shearVelocity	= relativeVelocity-normalVelocity*geom.normal;

//Normal Force
	
	Real OverlapArea;
	Real MaxArea;

	OverlapArea = 3.1415 * pow(OverlapRadius,2);
	MaxArea = 3.1415 * pow(contactRadius,2);

	Real Mult;
	if(OverlapRadius < contactRadius){
		Mult = OverlapArea / MaxArea;
	}
	else{
		Mult = 1;
	}
	
	Real Fn;
	if(geom.penetrationDepth>=0){
//Compression
		if(normalVelocity>=0){
			if (geom.penetrationDepth >= phys.maxPenetration){
				Fn = phys.knI * (geom.penetrationDepth - phys.previousun) + phys.previousElasticN + phys.cnI * normalVelocity;
				phys.previousElasticN += phys.knI * (geom.penetrationDepth - phys.previousun);
				phys.normalForce = Fn * geom.normal;
				phys.t = 0; phys.t2 = 0;
				//phys.previousElasticTensionN = 0;
			} 
			else{
				Fn = Mult * phys.kn * (geom.penetrationDepth - phys.previousun) + Mult * phys.previousElasticN + phys.cn * normalVelocity;
				phys.previousElasticN += Mult * phys.kn * (geom.penetrationDepth - phys.previousun);
				phys.finalElasticN += Mult * phys.kn * (geom.penetrationDepth - phys.previousun);
				phys.normalForce = Fn * geom.normal;
				phys.t = 0; phys.t2 = 0;
				//phys.previousElasticTensionN = 0;
			}
		}
//Tension
		else if(normalVelocity<0){
			if(phys.t == 0){
				phys.maxNormalComp = - phys.finalElasticN;
				//printf("------> %E \n", phys.maxNormalComp);
				phys.RupOverlap = phys.previousun;
				//throw runtime_error("STOP");
				phys.t = 1;
			}
			
			Real MaxTension = phys.maxNormalComp * 0.25;
			Real FnTension = phys.previousElasticTensionN + Mult * phys.kn * dt * normalVelocity;
			//printf("===:: %E \n", MaxTension);
			//printf("===:: %E \n", FnTension);
			if (FnTension > MaxTension && phys.t2 == 0){
				Fn = phys.previousElasticTensionN + Mult * phys.kn * dt * normalVelocity;
				phys.previousElasticTensionN = Fn;
				phys.normalForce = Fn * geom.normal;
				phys.RupOverlap = geom.penetrationDepth;
				//phys.previousElasticN = 0;
				//printf("===-- %E \n", Fn);
			}
			else{
				//phys.DamageTension = geom.penetrationDepth / (phys.maxPenetration - phys.maxPenetration * phys.RupTension);
				//phys.previousElasticTensionN -= phys.DamageTension * Mult * phys.kn * dt * normalVelocity;
				phys.t2 = 1;
				Fn = MaxTension * geom.penetrationDepth / phys.RupOverlap;
				phys.normalForce = Fn * geom.normal;
				//printf("===// %E \n", Fn);
				//throw runtime_error("STOP");
			}
		}
	}
	else{
		Fn = 0;
		phys.normalForce = Fn * geom.normal;
		phys.finalElasticN = 0;
	}

	
	phys.previousun = geom.penetrationDepth;

//Shear Force
	shearForce += phys.ks*dt*shearVelocity;
	Vector3r shearForceVisc = Vector3r::Zero();

	const Real maxFs = phys.normalForce.squaredNorm() * std::pow(phys.tangensOfFrictionAngle,2);
	if( shearForce.squaredNorm() > maxFs ){
		// Then Mohr-Coulomb is violated (so, we slip), 
		// we have the max value of the shear force, so 
		// we consider only friction damping.
		const Real ratio = sqrt(maxFs) / shearForce.norm();
		shearForce *= ratio;
	} 
	else{
		// Then no slip occurs we consider friction damping + viscous damping.
		shearForceVisc = phys.cs*shearVelocity; 
	}

	if (I->isActive) {
		const Vector3r f = phys.normalForce + shearForce + shearForceVisc;
		addForce (id1,-f,scene);
		addForce (id2, f,scene);
		addTorque(id1,-c1x.cross(f),scene);
		addTorque(id2, c2x.cross(f),scene);
	}
}
Ejemplo n.º 6
0
void UI::Push(const shared_ptr<Panel> &panel)
{
	panel->SetUI(this);
	toPush.push_back(panel);
}
Ejemplo n.º 7
0
 SinkCounter() {
   cv_.reset(new condition_variable);
   mtx_.reset(new mutex);
   count_.reset(new int(0));
 }
Ejemplo n.º 8
0
void ServicesDbReader::_addTagsToElement(shared_ptr<Element> element)
{
  bool ok;
  Tags& tags = element->getTags();

  if (tags.contains("hoot:status"))
  {
    QString statusStr = tags.get("hoot:status");
    bool ok;
    const int statusInt = statusStr.toInt(&ok);
    Status status = static_cast<Status::Type>(statusInt);
    if (ok && status.getEnum() >= Status::Invalid && status.getEnum() <= Status::Conflated)
    {
      element->setStatus(status);
    }
    else
    {
      LOG_WARN("Invalid status: " + statusStr + " for element with ID: " +
               QString::number(element->getId()));
    }
    tags.remove("hoot:status");
  }

  if (tags.contains("type"))
  {
    Relation* r = dynamic_cast<Relation*>(element.get());
    if (r)
    {
      r->setType(tags["type"]);
      tags.remove("type");
    }
  }

  if (tags.contains("error:circular"))
  {
    element->setCircularError(tags.get("error:circular").toDouble(&ok));
    if (!ok)
    {
      try
      {
        double tv = tags.getLength("error:circular").value();
        element->setCircularError(tv);
        ok = true;
      }
      catch (const HootException& e)
      {
        ok = false;
      }

      if (!ok)
      {
        LOG_WARN("Error parsing error:circular.");
      }
    }
    tags.remove("error:circular");
  }
  else if (tags.contains("accuracy"))
  {
    element->setCircularError(tags.get("accuracy").toDouble(&ok));

    if (!ok)
    {
      try
      {
        double tv = tags.getLength("accuracy").value();
        element->setCircularError(tv);
        ok = true;
      }
      catch (const HootException& e)
      {
        ok = false;
      }

      if (!ok)
      {
        LOG_WARN("Error parsing accuracy.");
      }
    }
    tags.remove("accuracy");
  }
}
Ejemplo n.º 9
0
ContainerFrame::ContainerFrame(const Point& pos, shared_ptr<ResourceCtl> res, const std::string& title, shared_ptr<Inventory> inv)
	                           : UIFrame(pos, inv->getSize().modMul(INVENTORY_ICON_SIZE).modAdd(20, 20), res, title) {
	
	_inv = inv;
	_contArea = make_shared<ContainerArea>(Point(10, 10 + _titleHeight), _inv->getSize(), this);
}
Ejemplo n.º 10
0
void ServicesDbReader::_readBounded(shared_ptr<OsmMap> map, const ElementType& elementType)
{
  LOG_DEBUG("IN ServicesDbReader::readBounded(,)...");
  long long lastId = LLONG_MIN;
  shared_ptr<Element> element;
  QStringList tags;
  bool firstElement = true;
  QStringList bboxParts = _bbox.split(",");

  double minLat = bboxParts[1].toDouble();
  double minLon = bboxParts[0].toDouble();
  double maxLat = bboxParts[3].toDouble();
  double maxLon = bboxParts[2].toDouble();

  // determine is Services or Osm Api DB
  ServicesDb::DbType connectionType = _database.getDatabaseType();

  // contact the DB and select all
  shared_ptr<QSqlQuery> elementResultsIterator = _database.selectBoundedElements(_osmElemId, elementType, _bbox);

  // split the reading of Services and Osm Api DB upfront to avoid extra inefficiency of if-else calls
  //   inside the isActive loop
  switch ( connectionType )
  {
    case ServicesDb::DBTYPE_SERVICES:
      //need to check isActive, rather than next() here b/c resultToElement actually calls next() and
      //it will always return an extra null node at the end, unfortunately (see comments in
      //ServicesDb::resultToElement)
      while (elementResultsIterator->isActive())
      {
        shared_ptr<Element> element =
          _resultToElement(*elementResultsIterator, elementType, *map );
        //this check is necessary due to an inefficiency in ServicesDb::resultToElement
        if (element.get())
        {
          if (_status != Status::Invalid) { element->setStatus(_status); }
          map->addElement(element);
        }
      }
      break;

    case ServicesDb::DBTYPE_OSMAPI:
      // check if db active or not
      assert(elementResultsIterator->isActive());

      switch (elementType.getEnum())
      {
        ///////////////////////////////////////////////////////////////////
        // NODES
        ///////////////////////////////////////////////////////////////////
        case ElementType::Node:
          while( elementResultsIterator->next() )
          {
            long long id = elementResultsIterator->value(0).toLongLong();
            if( lastId != id )
            {
              // process the complete element only after the first element created
              if(!firstElement)
              {
                if(tags.size()>0)
                {
                  element->setTags( ServicesDb::unescapeTags(tags.join(", ")) );
                  _addTagsToElement( element );
                }

                if (_status != Status::Invalid) { element->setStatus(_status); }
                map->addElement(element);
                tags.clear();
              }

              // extract the node contents except for the tags
              element = _resultToNode_OsmApi(*elementResultsIterator, *map);

              lastId = id;
              firstElement = false;
            }

            // read the tag for as many rows as there are tags
            // need to get into form "key1"=>"val1", "key2"=>"val2", ...

            QString result = _database.extractTagFromRow_OsmApi(elementResultsIterator, elementType.getEnum());
            if(result != "") tags << result;
          }
          // process the last complete element only if an element has been created
          if(!firstElement)
          {
            if(tags.size()>0)
            {
              element->setTags( ServicesDb::unescapeTags(tags.join(", ")) );
              _addTagsToElement( element );
            }
            if (_status != Status::Invalid) { element->setStatus(_status); }
            map->addElement(element);
            tags.clear();
          }
          break;

        ///////////////////////////////////////////////////////////////////
        // WAYS
        ///////////////////////////////////////////////////////////////////
        case ElementType::Way:
          while( elementResultsIterator->next() )
          {
            long long wayId = elementResultsIterator->value(0).toLongLong();
            shared_ptr<QSqlQuery> nodeInfoIterator = _database.selectNodesForWay( wayId );
            bool foundOne = false;
            while( nodeInfoIterator->next() && !foundOne)
            {
              // do the bounds check
              double lat = nodeInfoIterator->value(ServicesDb::NODES_LATITUDE).toLongLong()/(double)ServicesDb::COORDINATE_SCALE;
              double lon = nodeInfoIterator->value(ServicesDb::NODES_LONGITUDE).toLongLong()/(double)ServicesDb::COORDINATE_SCALE;
              if(lat >= minLat && lat <= maxLat && lon >= minLon && lon <= maxLon) foundOne = true; // ToDo: process boundary condition
            }
            if( foundOne )
            {
              // we have a polygon, so now you have to do some work; else go on to the next way_id

              // process the way into a data structure
              shared_ptr<Element> element = _resultToWay_OsmApi(*elementResultsIterator, *map);

              // get the way tags
              shared_ptr<QSqlQuery> wayTagIterator = _database.selectTagsForWay_OsmApi( wayId );
              while( wayTagIterator->next() )
              {
                // test for blank tag
                QString val1 = wayTagIterator->value(1).toString();
                QString val2 = wayTagIterator->value(2).toString();
                QString tag = "";
                if(val1!="" || val2!="") tag = "\""+val1+"\"=>\""+val2+"\"";
                if(tag != "") tags << tag;
              }
              if(tags.size()>0)
              {
                element->setTags( ServicesDb::unescapeTags(tags.join(", ")) );
                _addTagsToElement( element );
              }

              if (_status != Status::Invalid) { element->setStatus(_status); }
              map->addElement(element);
              tags.clear();
            }
          }
          break;

        ///////////////////////////////////////////////////////////////////
        // RELATIONS
        ///////////////////////////////////////////////////////////////////
        case ElementType::Relation:
          while( elementResultsIterator->next() )
          {
            _processRelation(*elementResultsIterator, *map);
          }
          break;

        default:
          throw HootException(QString("Unexpected element type: %1").arg(elementType.toString()));
      }
      break;

    default:
      throw HootException("_read cannot operate on unsupported database type");
      break;
  }
  LOG_DEBUG("LEAVING ServicesDbReader::_read...");
}
Ejemplo n.º 11
0
void ServicesDbReader::_read(shared_ptr<OsmMap> map, const ElementType& elementType)
{
  LOG_DEBUG("IN ServicesDbReader::read(,)...");
  long long lastId = LLONG_MIN;
  shared_ptr<Element> element;
  QStringList tags;
  bool firstElement = true;

  // determine is Services or Osm Api DB
  ServicesDb::DbType connectionType = _database.getDatabaseType();

  // contact the DB and select all
  shared_ptr<QSqlQuery> elementResultsIterator = _database.selectAllElements(_osmElemId, elementType);

  // split the reading of Services and Osm Api DB upfront to avoid extra inefficiency of if-else calls
  //   inside the isActive loop
  switch ( connectionType )
  {
    case ServicesDb::DBTYPE_SERVICES:
      //need to check isActive, rather than next() here b/c resultToElement actually calls next() and
      //it will always return an extra null node at the end, unfortunately (see comments in
      //ServicesDb::resultToElement)
      while (elementResultsIterator->isActive())
      {
        shared_ptr<Element> element =
          _resultToElement(*elementResultsIterator, elementType, *map );
        //this check is necessary due to an inefficiency in ServicesDb::resultToElement
        if (element.get())
        {
          if (_status != Status::Invalid) { element->setStatus(_status); }
          map->addElement(element);
        }
      }
      break;

    case ServicesDb::DBTYPE_OSMAPI:
      // check if db active or not
      assert(elementResultsIterator->isActive());

      while( elementResultsIterator->next() )
      {
        long long id = elementResultsIterator->value(0).toLongLong();
        if( lastId != id )
        {
          // process the complete element only after the first element created
          if(!firstElement)
          {
            if(tags.size()>0)
            {
              element->setTags( ServicesDb::unescapeTags(tags.join(", ")) );
              _addTagsToElement( element );
            }

            if (_status != Status::Invalid) { element->setStatus(_status); }
            map->addElement(element);
            tags.clear();
          }

          // extract the node contents except for the tags
          switch (elementType.getEnum())
          {
            case ElementType::Node:
              element = _resultToNode_OsmApi(*elementResultsIterator, *map);
              break;

            case ElementType::Way:
              element = _resultToWay_OsmApi(*elementResultsIterator, *map);
              break;

            case ElementType::Relation:
              element = _resultToRelation_OsmApi(*elementResultsIterator, *map);
              break;

            default:
              throw HootException(QString("Unexpected element type: %1").arg(elementType.toString()));
          }
          lastId = id;
          firstElement = false;
        }

        // read the tag for as many rows as there are tags
        // need to get into form "key1"=>"val1", "key2"=>"val2", ...

        QString result = _database.extractTagFromRow_OsmApi(elementResultsIterator, elementType.getEnum());
        if(result != "") tags << result;
      }

      // process the last complete element only if an element has been created
      if(!firstElement)
      {
        if(tags.size()>0)
        {
          element->setTags( ServicesDb::unescapeTags(tags.join(", ")) );
          _addTagsToElement( element );
        }
        if (_status != Status::Invalid) { element->setStatus(_status); }
        map->addElement(element);
        tags.clear();
      }
      break;

    default:
      throw HootException("_read cannot operate on unsupported database type");
      break;
  }
  LOG_DEBUG("LEAVING ServicesDbReader::_read...");
}
Ejemplo n.º 12
0
//从撤单中生成新的报单
void Trader::generateOrderFromCanceledOrder(const shared_ptr<Order> &order){
	shared_ptr<Order> newOrder = make_shared<Order>();
	newOrder->moveToThread(QCoreApplication::instance()->thread());
	newOrder->setInvestorId(order->getInvestorId());
	newOrder->setStrategyId(order->getStrategyId());
	newOrder->setInstructionId(order->getInstructionId());
	newOrder->setInstrumentId(order->getInstrumentId());
	newOrder->setDirection(order->getDirection());
	newOrder->setOpenCloseFlag(order->getOpenCloseFlag());
	double price = order->getPrice();
	//获得该合约的最小价格变动单位,如果买则买价增加,如果卖则卖价减小
	auto instruments = BackgroundTrader::getInstance()->getInstruments();
	auto &info = instruments[order->getInstrumentId()];
	double minPrice = info->getMinimumUnit();
	if (order->getDirection() == 'b'){
		price += minPrice;
	}
	else{
		price -= minPrice;
	}
	newOrder->setPrice(price);
	newOrder->setOriginalVolume(order->getRestVolume());
	newOrder->setTradedVolume(0);
	newOrder->setRestVolume(newOrder->getOriginalVolume());
	newOrder->setOpenCloseFlag(order->getOpenCloseFlag());
	newOrder->setOrderStatus('a');
	if (newOrder->getOpenCloseFlag() == '1'){
		//当收到平仓字段时对合约进行判断,如果是上海期货的合约则自动平今
		if (info->getExchangeId() == "SHFE"){
			splitSHFEOrder(newOrder, "0");			//限价单标志0
			return;
		}
	}
	//执行指令
	executeOrder(newOrder, "0");
}
Ejemplo n.º 13
0
void BooksDBUtil::removeAllTags(shared_ptr<Book> book) {
	book->removeAllTags();
}
Ejemplo n.º 14
0
void BooksDBUtil::cloneTag(shared_ptr<Book> book, shared_ptr<Tag> from, shared_ptr<Tag> to, bool includeSubTags) {
	if (book->cloneTag(from, to, includeSubTags)) {
		BooksDB::Instance().saveTags(book);
	}
}
Ejemplo n.º 15
0
void print_trigger_effs(const shared_ptr<ProcessHistograms> & ph, const string & selection){
    auto h = ph->get_histogram(selection, "lepton_trigger");
    cout << "lepton trigger efficiency (w.r.t. offline lepton selection): " << h.histo->GetBinContent(2) /  (h.histo->GetBinContent(1) + h.histo->GetBinContent(2)) << endl;
    h = ph->get_histogram(selection, "lepton_triggermatch");
    cout << "lepton trigger matching efficiency (after offline selection and trigger): " << h.histo->GetBinContent(2) /  (h.histo->GetBinContent(1) + h.histo->GetBinContent(2))<< endl;
}
Ejemplo n.º 16
0
void UIFrame::addElement(shared_ptr<UIElement> el) {
	el->setParent(this);
	el->setZlevel(_zlevel + 1);
	_elements.push_back(el);
}
Ejemplo n.º 17
0
void dump_histo(const shared_ptr<ProcessHistograms> & ph, const string & selection, const string & hname){
    auto h = ph->get_histogram(selection, hname);
    for(int i=1; i<=h.histo->GetNbinsX(); ++i){
        cout << i << " (" << h.histo->GetXaxis()->GetBinLowEdge(i) << "--" << h.histo->GetXaxis()->GetBinUpEdge(i) << ")" << h.histo->GetBinContent(i) << endl;
    }
}
Ejemplo n.º 18
0
			//----------
			shared_ptr<NodeHost> Patch::addNewNode(shared_ptr<BaseFactory> factory, const ofRectangle & bounds) {
				auto newNode = factory->makeUntyped();
				newNode->init();
				return this->addNode(newNode, bounds);
			}
Ejemplo n.º 19
0
void DecodeTrace::create_decoder_form(int index,
	shared_ptr<data::decode::Decoder> &dec, QWidget *parent,
	QFormLayout *form)
{
	const GSList *l;

	assert(dec);
	const srd_decoder *const decoder = dec->decoder();
	assert(decoder);

	const bool decoder_deletable = index > 0;

	pv::widgets::DecoderGroupBox *const group =
		new pv::widgets::DecoderGroupBox(
			QString::fromUtf8(decoder->name), nullptr, decoder_deletable);
	group->set_decoder_visible(dec->shown());

	if (decoder_deletable) {
		delete_mapper_.setMapping(group, index);
		connect(group, SIGNAL(delete_decoder()), &delete_mapper_, SLOT(map()));
	}

	show_hide_mapper_.setMapping(group, index);
	connect(group, SIGNAL(show_hide_decoder()),
		&show_hide_mapper_, SLOT(map()));

	QFormLayout *const decoder_form = new QFormLayout;
	group->add_layout(decoder_form);

	// Add the mandatory channels
	for (l = decoder->channels; l; l = l->next) {
		const struct srd_channel *const pdch =
			(struct srd_channel *)l->data;
		QComboBox *const combo = create_channel_selector(parent, dec, pdch);
		connect(combo, SIGNAL(currentIndexChanged(int)),
			this, SLOT(on_channel_selected(int)));
		decoder_form->addRow(tr("<b>%1</b> (%2) *")
			.arg(QString::fromUtf8(pdch->name))
			.arg(QString::fromUtf8(pdch->desc)), combo);

		const ChannelSelector s = {combo, dec, pdch};
		channel_selectors_.push_back(s);
	}

	// Add the optional channels
	for (l = decoder->opt_channels; l; l = l->next) {
		const struct srd_channel *const pdch =
			(struct srd_channel *)l->data;
		QComboBox *const combo = create_channel_selector(parent, dec, pdch);
		connect(combo, SIGNAL(currentIndexChanged(int)),
			this, SLOT(on_channel_selected(int)));
		decoder_form->addRow(tr("<b>%1</b> (%2)")
			.arg(QString::fromUtf8(pdch->name))
			.arg(QString::fromUtf8(pdch->desc)), combo);

		const ChannelSelector s = {combo, dec, pdch};
		channel_selectors_.push_back(s);
	}

	// Add the options
	shared_ptr<binding::Decoder> binding(
		new binding::Decoder(decoder_stack_, dec));
	binding->add_properties_to_form(decoder_form, true);

	bindings_.push_back(binding);

	form->addRow(group);
	decoder_forms_.push_back(group);
}
void MVLobbyState::render(shared_ptr<MVPlayer> player) const
{
	player->writeLine(MVEnum::messageToString(MVEnum::WAITING_FOR_PLAYER));
}
Ejemplo n.º 21
0
 int operator++ () {
   std::unique_lock<std::mutex> lck(*mtx_);
   ++(*count_);
   cv_->notify_all();
 }
Ejemplo n.º 22
0
 regex_byref_matcher(shared_ptr<regex_impl<BidiIter> > const &impl)
   : wimpl_(impl)
   , pimpl_(impl.get())
 {
     BOOST_ASSERT(this->pimpl_);
 }
Ejemplo n.º 23
0
/*! Iphys functor */
void Ip2_FreshConcreteMat_FreshConcreteMat_FreshConcretePhys::go( const shared_ptr<Material>& b1
		 , const shared_ptr<Material>& b2
		 , const shared_ptr<Interaction>& interaction){
	if(interaction->phys) return;
	FreshConcreteMat* mat1 = static_cast<FreshConcreteMat*>(b1.get());
	FreshConcreteMat* mat2 = static_cast<FreshConcreteMat*>(b2.get());
	Real mass1 = 1.0;
	Real mass2 = 1.0;
	
	mass1=Body::byId(interaction->getId1())->state->mass;
	mass2=Body::byId(interaction->getId2())->state->mass;

//Rheological parameters for the external core
	const Real kn1 = mat1->kn*mass1; const Real cn1 = mat1->cn*mass1;
	const Real ks1 = mat1->ks*mass1; const Real cs1 = mat1->cs*mass1;
	const Real kn2 = mat2->kn*mass2; const Real cn2 = mat2->cn*mass2;
	const Real ks2 = mat2->ks*mass2; const Real cs2 = mat2->cs*mass2;
//Rheological parameters for the inner core
	const Real knI1 = mat1->knI*mass1; const Real cnI1 = mat1->cnI*mass1;
	const Real ksI1 = mat1->ksI*mass1; const Real csI1 = mat1->csI*mass1;
	const Real knI2 = mat2->knI*mass2; const Real cnI2 = mat2->cnI*mass2;
	const Real ksI2 = mat2->ksI*mass2; const Real csI2 = mat2->csI*mass2;

	FreshConcretePhys* phys = new FreshConcretePhys();

//Rheological parameters for the external core
	if ((kn1>0) or (kn2>0)) {
		phys->kn = 1/( ((kn1>0)?1/kn1:0) + ((kn2>0)?1/kn2:0) );
	} else {
		phys->kn = 0;
	}
	if ((ks1>0) or (ks2>0)) {
		phys->ks = 1/( ((ks1>0)?1/ks1:0) + ((ks2>0)?1/ks2:0) );
	} else {
		phys->ks = 0;
	} 

	phys->cn = (cn1?1/cn1:0) + (cn2?1/cn2:0); phys->cn = phys->cn?1/phys->cn:0;
	phys->cs = (cs1?1/cs1:0) + (cs2?1/cs2:0); phys->cs = phys->cs?1/phys->cs:0;

	phys->tangensOfFrictionAngle = std::tan(std::min(mat1->frictionAngle, mat2->frictionAngle));
	phys->shearForce = Vector3r(0,0,0);

//Rheological parameters for the inner core
	if ((knI1>0) or (knI2>0)) {
		phys->knI = 1/( ((knI1>0)?1/knI1:0) + ((knI2>0)?1/knI2:0) );
	} else {
		phys->knI = 0;
	}
	if ((ksI1>0) or (ksI2>0)) {
		phys->ksI = 1/( ((ksI1>0)?1/ksI1:0) + ((ksI2>0)?1/ksI2:0) );
	} else {
		phys->ksI = 0;
	} 

	phys->cnI = (cnI1?1/cnI1:0) + (cnI2?1/cnI2:0); phys->cnI = phys->cnI?1/phys->cnI:0;
	phys->csI = (csI1?1/csI1:0) + (csI2?1/csI2:0); phys->csI = phys->csI?1/phys->csI:0;
 
	phys->tangensOfFrictionAngleI = std::tan(std::min(mat1->frictionAngleI, mat2->frictionAngleI));
	phys->shearForceI = Vector3r(0,0,0);

	phys->Penetration1=mat1->SecPhaseThickness;
	phys->Penetration2=mat2->SecPhaseThickness;

	interaction->phys = shared_ptr<FreshConcretePhys>(phys);
}
Ejemplo n.º 24
0
 void
 TimelineLayoutHelper::apply_drop_to_modelTree (TimelineLayoutHelper::DropPoint const& drop)
 {
   if(drop.relation == None) return;
   
   
   const shared_ptr<model::Sequence> sequence = get_sequence();
   
   // Freeze the timeline widget - it must be done manually later
   timelineWidget.freeze_update_tracks();
   
   // Get the tracks
   shared_ptr<model::Track> &dragging_track = *draggingTrackIter;
   REQUIRE(dragging_track);
   REQUIRE(dragging_track != sequence);
   
   shared_ptr<model::Track> &target_track = *drop.target;
   REQUIRE(target_track);
   REQUIRE(target_track != sequence);
   
   // Detach the track from the old parent
   shared_ptr<model::ParentTrack> old_parent =
      sequence->find_descendant_track_parent(dragging_track);
   REQUIRE(old_parent);  // The track must have a parent
   old_parent->get_child_track_list().remove(dragging_track);
   
   if (drop.relation == Before || drop.relation == After)
     {
       // Find the new parent track
       shared_ptr<model::ParentTrack> new_parent =
         sequence->find_descendant_track_parent(target_track);
       REQUIRE(new_parent);  // The track must have a parent
       
       // Find the destination point
       observable_list< shared_ptr<model::Track> > &dest =
         new_parent->get_child_track_list();
       list< shared_ptr<model::Track> >::iterator iter;
       for (iter = dest.begin(); iter != dest.end(); iter++)
         {
           if(*iter == target_track)
             break;
         }
       REQUIRE(iter != dest.end());  // The target must be
                                     // in the destination
       
       // We have to jump on 1 if we want to insert after
       if(drop.relation == After)
         iter++;
       
       // Insert at this point
       dest.insert(iter, dragging_track);
     }
   else
   if (drop.relation == FirstChild || drop.relation == LastChild)
     {
       shared_ptr<model::ParentTrack> new_parent =
         dynamic_pointer_cast<model::ParentTrack, model::Track>(
           target_track);
       REQUIRE(new_parent);  // The track must have a parent
       
       if (drop.relation == FirstChild)
         new_parent->get_child_track_list().push_front(dragging_track);
       else
       if (drop.relation == LastChild)
         new_parent->get_child_track_list().push_back(dragging_track);
     }
   else ASSERT(0); // Unexpected value of relation
   
   // Thaw the timeline widget
   timelineWidget.thaw_update_tracks();
 }
Ejemplo n.º 25
0
//--------------------------------------------------------------
static bool shouldRemove(shared_ptr<ofxBox2dBaseShape>shape) {
    return !ofRectangle(0, -400, ofGetWidth(), ofGetHeight()+400).inside(shape->getPosition());
}
Ejemplo n.º 26
0
void get_handler( const shared_ptr< Session > session )
{
    session->close( OK, "OK", { { "Connection", "close" } } );
}
Ejemplo n.º 27
0
void error_handler( const int, const exception&, const shared_ptr< Session > session )
{
    session->close( 0, "I see nothing!", { { "Content-Length", "14" } } );
}
Ejemplo n.º 28
0
void head_handler( const shared_ptr< Session >& session )
{
    session->close( 200, "Hello, World!", { { "Content-Length", "13" }, { "Connection", "close" } } );
}
Ejemplo n.º 29
0
   bool 
   SignatureAdder::SetSignature(shared_ptr<Message> pMessage, 
      shared_ptr<const Domain> pSenderDomain, 
      shared_ptr<const Account> pSenderAccount,
      shared_ptr<MessageData> &pMessageData)
   //---------------------------------------------------------------------------()
   // DESCRIPTION:
   // Sets the signature of the message, based on the signature in the account
   // settings and domain settings.
   //---------------------------------------------------------------------------()
   {  
      if (!pMessage)
      {
         // Input error
         return false;
      }

      if (!pSenderDomain)
      {
         // Not a local sender - nothing to do.
         return false;
      }

      if (!pSenderDomain->GetAddSignaturesToLocalMail() && _GetMessageIsLocal(pMessage))
      {
         // The message is local, but we have configured
         // the server not to add signatures to local email.
         return false;
      }

      String sSignaturePlainText;
      String sSignatureHTML;

      // First check if an account signature has been specified.
      if (pSenderAccount && pSenderAccount->GetEnableSignature())
      {
         sSignaturePlainText = pSenderAccount->GetSignaturePlainText();
         sSignatureHTML = pSenderAccount->GetSignatureHTML();

         if (!sSignaturePlainText.IsEmpty() && sSignatureHTML.IsEmpty())
         {
            // Plain text specified but not HTML. Copy plain text to HTML.
            sSignatureHTML = sSignaturePlainText;
            sSignatureHTML.Replace(_T("\r\n"), _T("<br>\r\n"));
         }
      }

      if (pSenderDomain->GetEnableSignature())
      {
         String sDomainPlainText = pSenderDomain->GetSignaturePlainText();
         String sDomainHTML = pSenderDomain->GetSignatureHTML();

         if (!sDomainPlainText.IsEmpty() && sDomainHTML.IsEmpty())
         {
            // Plain text specified but not HTML. Copy plain text to HTML.
            sDomainHTML = sDomainPlainText;
            sDomainHTML.Replace(_T("\r\n"), _T("<br>\r\n"));
         }

         // Check if we should overwrite the account signature with the 
         // domain signature, if we should append it, or if we just should
         // keep it.
         if (pSenderDomain->GetSignatureMethod() == HM::Domain::SMSetIfNotSpecifiedInAccount)
         {
            if (sSignaturePlainText.IsEmpty()) 
               sSignaturePlainText = sDomainPlainText;
            if (sSignatureHTML.IsEmpty())
               sSignatureHTML = sDomainHTML;
         }
         else if (pSenderDomain->GetSignatureMethod() == HM::Domain::SMAppendToAccountSignature)
         {
            sSignaturePlainText += "\r\n\r\n" + sDomainPlainText;
            sSignatureHTML += "<br><br>" + sDomainHTML;
         }
         else if (pSenderDomain->GetSignatureMethod() == HM::Domain::SMOverwriteAccountSignature)
         {
            sSignaturePlainText = sDomainPlainText;
            sSignatureHTML = sDomainHTML;
         }            
      }

      if (sSignaturePlainText.IsEmpty() && sSignatureHTML.IsEmpty())  
      {
         // No signature should be created.
         return false;
      }

      // A signature should be created.
      if (!pMessageData)
      {
         pMessageData = shared_ptr<MessageData>(new MessageData());
         shared_ptr<Account> emptyAccount;
         if (!pMessageData->LoadFromMessage(emptyAccount, pMessage))
            return false;
      }

      if (!pSenderDomain->GetAddSignaturesToReplies() && _GetMessageIsReply(pMessageData))
      {
         // The message is a reply, but we have configured the
         // server not to add signatures to replies
         return false;
      }

      String sCurrentBodyPlainText = pMessageData->GetBody();
      String sCurrentBodyHTML = pMessageData->GetHTMLBody();

      if (!sSignaturePlainText.IsEmpty())
         sCurrentBodyPlainText += "\r\n" + sSignaturePlainText;

      if (!sCurrentBodyHTML.IsEmpty() && !sSignatureHTML.IsEmpty())
         sCurrentBodyHTML += "<br>" + sSignatureHTML;

      if (pSenderAccount)
      {
         sCurrentBodyPlainText.ReplaceNoCase(_T("%User.FirstName%"), pSenderAccount->GetPersonFirstName());
         sCurrentBodyPlainText.ReplaceNoCase(_T("%User.LastName%"), pSenderAccount->GetPersonLastName());

         sCurrentBodyHTML.ReplaceNoCase(_T("%User.FirstName%"), pSenderAccount->GetPersonFirstName());
         sCurrentBodyHTML.ReplaceNoCase(_T("%User.LastName%"), pSenderAccount->GetPersonLastName());
      }

      if (!sCurrentBodyPlainText.IsEmpty() && pMessageData->GetHasBodyType("text/plain"))
         pMessageData->SetBody(sCurrentBodyPlainText);

      if (!sCurrentBodyHTML.IsEmpty() && pMessageData->GetHasBodyType("text/html"))
         pMessageData->SetHTMLBody(sCurrentBodyHTML);

      return true;      


   }
Ejemplo n.º 30
0
void io_chain_t::push_back(const shared_ptr<io_data_t> &element)
{
    // Ensure we never push back NULL
    assert(element.get() != NULL);
    std::vector<shared_ptr<io_data_t> >::push_back(element);
}