Ejemplo n.º 1
0
void
Sector::write(lisp::Writer& writer)
{
  writer.write_string("name", name);
  writer.write_float("gravity", gravity);
  writer.write_string("music", music);

  // write spawnpoints
  for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
      ++i) {
    SpawnPoint* spawn = *i;
    writer.start_list("spawn-points");
    writer.write_string("name", spawn->name);
    writer.write_float("x", spawn->pos.x);
    writer.write_float("y", spawn->pos.y);
    writer.end_list("spawn-points");
  }

  // write objects
  for(GameObjects::iterator i = gameobjects.begin();
      i != gameobjects.end(); ++i) {
    Serializable* serializable = dynamic_cast<Serializable*> (*i);
    if(serializable)
      serializable->write(writer);
  }
}
Ejemplo n.º 2
0
void
ESEnumerableModifyWnd::SetEnumerableObject(EnumerableObject<Serializable>* pEnumerable){
	ASSERT(pEnumerable);
	if( !pEnumerable ) return;

	ESChildControlList* pList = (ESChildControlList*)GetChildControl(1000);
	if( pList ){
		Serializable* pObject = pEnumerable->CreateSerializableObject();
		ASSERT(pObject);
		VariableInfo* pInfo = pObject->GetThisInfo();

		MercuryGUI*	pGUI		= MercuryGUI::GetInstance();
		_Size		szText(0, 0);
		_string		sTitle;

		int nLoop = 1;
		while( pInfo[nLoop].m_sAttributeName.length() > 0 ){
			if( !pInfo[nLoop].m_bComplexType ){
				sTitle = pInfo[nLoop].m_sDbFieldName;
				pGUI->header.m_fontItemText.GetTextSize(&sTitle, szText);
				if( szText.cx <= 0 )
					szText.cx = 80;
				pList->AddColumn(pInfo[nLoop].m_sDbFieldName, pInfo[nLoop].m_sAttributeName, HAlignment::HAlignement_Left, szText.cx + 5, szText.cx + 5);
				szText.cx = 0;
				}
			nLoop ++;
			}

		VirtualRowSet* pRowSet	= Serializable::SerializableObjectToVRowSet(pEnumerable);
		m_pListRowSet			= pRowSet;
		m_pEnumerable			= pEnumerable;
		pList->SetRowSet(pRowSet, true, true);
		delete pObject;
		}
	}
Ejemplo n.º 3
0
void test()
{
	Deserializer::d()["TestSerializable"] = TestSerializable::returnNew;

	TestSerializable testSerializable("important stuff");

	ptree serial = testSerializable.serialize();

	stringstream ss;
	write_xml(ss, serial);
	cout << "TestSerializable.serialize() to string:" << endl << ss.str() << endl;

	Serializable * deserializedUncast = newDeserialize(serial);
	//Serializable * deserializedUncast = Deserializer::d()["TestSerializable"]();

	ptree serial2 = deserializedUncast->serialize();

	stringstream ss2;
	write_xml(ss2, serial2);
	cout << "deserializedUncast->serialize() *post-returned* to string:" << endl << ss2.str() << endl;

	TestSerializable * deserialized = dynamic_cast<TestSerializable *>(deserializedUncast);
	
	cout << "deserialized->data: " << deserialized->data << endl;
}
Ejemplo n.º 4
0
Serializable * newDeserialize(ptree serial)
{
#if VERBOSE
	cout << "registered types:" << endl;
	for(map<string, Serializable * (*)()>::iterator iterator = Deserializer::d().begin(); iterator != Deserializer::d().end(); iterator++) {
		cout << iterator->first << endl;
	}
#endif

	string type = serial.get<std::string>("type");

	map<string, Serializable * (*)()>::iterator it = Deserializer::d().find(type);

	if(it != Deserializer::d().end())
	{
		Serializable * toReturn = Deserializer::d()[type]();
		toReturn->deserialize(serial);
		
	#if VERBOSE
		stringstream ss2;
		write_xml(ss2, toReturn->serialize());
		cout << "newDeserialize()->serialize() *pre-returned* to string:" << endl << ss2.str() << endl;
	#endif

		return toReturn;
	}
	else
	{
		cout<<"ERROR! No compatible deserialization function for " << type; //In case someone forgets to add a deserializer
		throw 319;
	}
}
Ejemplo n.º 5
0
void Pololu::Usc::Usb::SetSpeed::read(std::istream& stream) {
  Serializable<unsigned char> servo;
  Serializable<unsigned short> value;

  setServo(servo.read(stream));
  setValue(value.read(stream));
}
Ejemplo n.º 6
0
  RobotConfiguration* readLog(std::vector<BaseSensorData*>& sensorDatas, Deserializer& des){
    
    RobotConfiguration* conf = 0;
    Serializable *o;
    int numObjects=0;
    while( (! conf && (o=des.readObject())) ){
      cerr << o->className() << endl;
      numObjects++;
      if (! conf) {
	conf = dynamic_cast<RobotConfiguration*>(o);
	if (conf) {
	  cerr << "got config" << endl;
	  if (! conf->isReady()){
	    cerr << "conf failure" << endl;
	    return 0;
	  }
	}
	continue;
      }
    }

    if (!conf) {
      cerr << "unable to read robot configuration, aborting" << endl;
      return 0;
    }

    while( (o=des.readObject()) ){
      BaseSensorData* sensorData=dynamic_cast<BaseSensorData*>(o);
      if(sensorData)
	sensorDatas.push_back(sensorData);
    }
    return conf;
  }
  void init(bool deserialize) {
    LOG(debug) << "global.min_gamma_shape="
               << options.get<double>("global.min_gamma_shape");
    layer_size = options.get<int>("layer.size");
    lf = get_link_function(options.get<string>("lf"));
    min_gamma_sample = options.get<double>("global.min_gamma_sample");
    wshape.set_size(layer_size, n_examples);
    wscale.set_size(layer_size, n_examples);

    ScoreFunction score_shape = [=](double z, arma::uword i, arma::uword j) {
      auto shape0 = wshape(i,j);
      auto shape = lf->f(shape0);
      auto scale = lf->f(wscale(i,j));
      return lf->g(shape0) * (- gsl_sf_psi(shape) - log(scale) + log(z));
    };
    register_param(&wshape, score_shape, deserialize);

    ScoreFunction score_scale = [=](double z, arma::uword i, arma::uword j) {
      auto shape = lf->f(wshape(i,j));
      auto scale0 = wscale(i,j);
      auto scale = lf->f(scale0);
      return lf->g(scale0) * (- shape/scale + z/scale/scale);
    };
    register_param(&wscale, score_scale, deserialize);
  }
Ejemplo n.º 8
0
	Serializable *Serializable::DeserializeNew (shared_ptr <Stream> stream)
	{
		string name = Serializable::DeserializeHeader (stream);
		Serializable *serializable = SerializerFactory::GetNewSerializable (name);
		serializable->Deserialize (stream);

		return serializable;
	}
  virtual void truncate(const ExampleIds& example_ids) {
    auto min_shape0 = lf->f_inv(options.get<double>("global.min_gamma_shape"));
    auto min_scale0 = lf->f_inv(options.get<double>("global.min_gamma_scale"));

    for(auto j : example_ids) {
      wshape.col(j).transform([=](double v) { return max(v, min_shape0); });
      wscale.col(j).transform([=](double v) { return max(v, min_scale0); });
    }
  }
Ejemplo n.º 10
0
bool OutXmlSerializer::save(Stream& stream)
{
	XmlDocument doc;

	XmlDeclaration* decl = zenic_new XmlDeclaration;
	decl->setValue("xml");
	decl->setAttribute("version","1.0");
	decl->setAttribute("encoding","ISO-8859-1");
	doc.addChild(decl);

	XmlComment* comment = new XmlComment;
	comment->setValue(" Cell XML Object Graph ");
	doc.addChild(comment);

	// add initial objects

	for (uint i = 0, n = count(); i < n; ++i)
	{
		Serializable* initial = (*this)[i];
		uint j,m;
		for (j = 0, m = m_objects.count(); j < m; ++j)
		{
			if (m_objects[j] == initial)
				break;
		}

		if (j == m_objects.count())
			m_objects.pushBack(initial);
	}

	// build xml tree

	XmlElement* root = new XmlElement;
	root->setValue("zenic");

	for (uint i = 0; i < m_objects.count(); ++i)
	{
		Serializable* object = m_objects[i];
		ZENIC_ASSERT(object);

		m_current = 0;
		m_currentIndex = i;
		object->serialize(*this);

		ZENIC_ASSERT(m_current);
		root->addChild(m_current);
	}

	doc.addChild(root);

	// write tree to stream
	if (!doc.save(stream))
		return false;

	return true;
}
Ejemplo n.º 11
0
void Database::Statement::write(const Serializable &s)
{
	if(mOutputLevel == 0 || s.isInlineSerializable()) s.serialize(*this);
	else {
		String tmp;
		JsonSerializer serializer(&tmp);
		s.serialize(serializer);
		write(tmp);
	}
}
Ejemplo n.º 12
0
bool Database::Statement::read(Serializable &s)
{
	if(mInputLevel == 0 || s.isInlineSerializable()) return s.deserialize(*this);
	else {
		String tmp;
		if(!read(tmp)) return false;
		JsonSerializer serializer(&tmp);
		s.deserialize(serializer);
		return true;
	}
}
Ejemplo n.º 13
0
bool JsonSerializer::input(Serializable &s)
{
	if(s.isInlineSerializable() && !s.isNativeSerializable())
	{
		String str;
		if(!input(str)) return false;
		s.fromString(str);
		return true;
	}
	else return s.deserialize(*this);
}
Ejemplo n.º 14
0
void 
SerializedInstanceTest::testSerialized(){
  toTest->addSerializable( getTestSerializable() );

  Serializable *returned = toTest->getSerializable();

  CPPUNIT_ASSERT( returned != 0 );
  CPPUNIT_ASSERT( returned->getDataType() == getTestSerializable()->getDataType() );

  delete returned;
}
Ejemplo n.º 15
0
void BlinkM::ScriptLine::read(std::istream& stream) {
  Serializable<unsigned char> durationTicks;
  Serializable<std::string> typeName;

  this->durationTicks = durationTicks.read(stream);
  typeName.read(stream);

  request = Singleton<Protocol>::getInstance().createRequest(
    typeName.read(stream));
  request->read(stream);
}
bool RangeProfilePlotManager::deserialize(SessionItemDeserializer& deserializer)
{
   XmlReader reader(NULL, false);
   DOMElement* pRootElement = deserializer.deserialize(reader, "RangeProfilePlotManager");
   if (pRootElement)
   {
      std::string viewId = A(pRootElement->getAttribute(X("viewId")));
      mpView = dynamic_cast<PlotView*>(Service<SessionManager>()->getSessionItem(viewId));

      mpPlot = Service<DesktopServices>()->createPlotWidget(getName(), CARTESIAN_PLOT);
      VERIFY(mpPlot);
      Serializable* pPlotSer = dynamic_cast<Serializable*>(mpPlot); // The imp side is serializable
      VERIFY(pPlotSer);
      if (!pPlotSer->fromXml(findChildNode(pRootElement, "plot"), reader.VERSION))
      {
         return false;
      }

      mpView = mpPlot->getPlot();
      VERIFY(mpView);
      Serializable* pPlotViewSer = dynamic_cast<Serializable*>(mpView); // The imp side is serializable
      VERIFY(pPlotViewSer);
      if (!pPlotViewSer->fromXml(findChildNode(pRootElement, "plotView"), reader.VERSION))
      {
         return false;
      }

      std::list<PlotObject*> objects;
      mpView->getObjects(POINT_SET, objects);
      FOR_EACH_DOMNODE(pRootElement, pChild)
      {
         if (XMLString::equals(pChild->getNodeName(), X("signature")))
         {
            DOMElement* pChldElmnt = static_cast<DOMElement*>(pChild);
            std::string sigId = A(pChldElmnt->getAttribute(X("sigId")));
            std::string pointSetName = A(pChldElmnt->getAttribute(X("pointSetName")));
            Signature* pSignature = static_cast<Signature*>(Service<SessionManager>()->getSessionItem(sigId));
            if (pSignature == NULL)
            {
               return false;
            }
            mSigPointSets[pSignature] = pointSetName;
            pSignature->attach(SIGNAL_NAME(Subject, Deleted), Slot(this, &RangeProfilePlotManager::signatureDeleted));
            pSignature->getDataDescriptor()->attach(SIGNAL_NAME(DataDescriptor, Renamed),
               Slot(this, &RangeProfilePlotManager::signatureRenamed));
         }
      }
      deserializer.nextBlock();
      return DockWindowShell::deserialize(deserializer);
   }
   return false;
}
Ejemplo n.º 17
0
            boost::shared_ptr<Serializable <PDXRecord> > PDXFileReader<FileEnumeratorType>::read() {
                using namespace std;
                using namespace boost;

                Serializable <PDXRecord>* newRecord;

                // open the next file to read.
                if (!curFile.is_open()) {
                    if (this->fIt == this->fEnum.end()) {
                        // Don't bother, no more files.
                        return shared_ptr<Serializable <PDXRecord> >();
                    }

                    const char* filename = (this->fIt)->file_string().c_str();
                    curFile.open(filename, ios::in | ios::binary);

                    if (curFile.fail()) {
                        this->_error = true;
                        this->_errorMsg = string(" Failed to open file ") + filename;

                        return shared_ptr<Serializable <PDXRecord> >();
                    }

                    arl_file_hdr_t header;

                    curFile.read((char*) (&header), sizeof (arl_file_hdr_t));

                    header.base_date = ntohl(header.base_date);

                    this->base_time.set(header.base_date, 0);
                    this->fIt++;
                }

                //do the reading.
                newRecord = new PDXRecord(&(this->base_time));

                char record[sizeof (pidx_data_t)];
                string dataStr;

                curFile.read(record, sizeof (record));

                if (curFile.eof()) {
                    curFile.close();

                    return this->read();
                } else {
                    newRecord->unserialize(dataStr.insert(0, record, sizeof (record)));
                }

                return shared_ptr<Serializable <PDXRecord> >(newRecord);
            }
Ejemplo n.º 18
0
//
// read_network_attributes
//
void ClientSidePrediction::read_network_attributes(Serializable& object, Deserializer& source)
{
    const auto attributes = object.GetNetworkAttributes();
    if (!attributes)
        return;

    unsigned numAttributes = attributes->Size();

    for (unsigned i = 0; i < numAttributes && !source.IsEof(); ++i)
    {
        const auto& attr = attributes->At(i);
        object.OnSetAttribute(attr, source.ReadVariant(attr.type_));
    }
}
Ejemplo n.º 19
0
void Deserializer::deserialize(const std::string& key, Serializable& sObj) {
    try {
        NodeSwitch ns(*this, key);
        sObj.deserialize(*this);
    } catch (TxException&) {
    }
}
Ejemplo n.º 20
0
void Html::object(const Serializable &s)
{
	// TODO
	open("span");
	mStream->write(escape(s.toString()));
	close("span");
}
Ejemplo n.º 21
0
//
// write_network_attributes
//
void ClientSidePrediction::write_network_attributes(Serializable& object, Serializer& dest)
{
    const auto attributes = object.GetNetworkAttributes();
    if (!attributes)
        return;

    auto numAttributes = attributes->Size();
    Variant value;

    for (unsigned i = 0; i < numAttributes; ++i)
    {
        const auto& attr = attributes->At(i);
        value.Clear();
        object.OnGetAttribute(attr, value);
        dest.WriteVariantData(value);
    }
}
bool RangeProfilePlotManager::serialize(SessionItemSerializer& serializer) const
{
   XMLWriter writer("RangeProfilePlotManager");
   writer.addAttr("viewId", mpView->getId());

#pragma message(__FILE__ "(" STRING(__LINE__) ") : warning : We should be able to save the plot's session id and restore " \
"using that but the PlotWidget is not really part of the session. The following code is a work around and should be changed " \
"when OPTICKS-542 is implemented. (tclarke)")

   writer.pushAddPoint(writer.addElement("plot"));
   Serializable* pPlotSer = dynamic_cast<Serializable*>(mpPlot); // The imp side is serializable
   VERIFY(pPlotSer);
   if (!pPlotSer->toXml(&writer))
   {
      return false;
   }
   writer.popAddPoint();
   writer.pushAddPoint(writer.addElement("plotView"));
   Serializable* pPlotViewSer = dynamic_cast<Serializable*>(mpView); // The imp side is serializable
   VERIFY(pPlotViewSer);
   if (!pPlotViewSer->toXml(&writer))
   {
      return false;
   }
   writer.popAddPoint();

   for (std::map<Signature*, std::string>::const_iterator sig = mSigPointSets.begin();
      sig != mSigPointSets.end(); ++sig)
   {
      writer.pushAddPoint(writer.addElement("signature"));
      writer.addAttr("sigId", sig->first->getId());
      writer.addAttr("pointSetName", sig->second);
      writer.popAddPoint();
   }

   if (!serializer.serialize(writer))
   {
      return false;
   }
   serializer.endBlock();
   return DockWindowShell::serialize(serializer);
}
Ejemplo n.º 23
0
bool Serializer::writeObject(Serializable& instance) {
  ObjectData* data=new ObjectData();
  instance.serialize(*data,*this);

  processDataForWrite(data,*this);

  if (!_datastream) {
    string str=_dataFileName;
    replaceEnvTags(str,_envMap);
    create_directories(path(str).parent_path());
    _datastream=new ofstream(str.c_str());
  }
  if (*_datastream) {
    _objectWriter->writeObject(*_datastream,instance.className(),*data);
    //TODO Change writer to get status flag
    return true;
  }
  return false;

}
Ejemplo n.º 24
0
void 
SerializedInstanceTest::testComplex2(){
  const int myInt = 1264;
  const unsigned int myUnsigned = 172;
  const string myString = "always estimate the power of denial";

  toTest->addInt( myInt );
  toTest->addString( myString );
  toTest->addSerializable( getTestSerializable() );
  toTest->addUnsigned( myUnsigned );

  CPPUNIT_ASSERT( myInt == toTest->getInt() );
  CPPUNIT_ASSERT( myString == toTest->getString() );

  Serializable *returned = toTest->getSerializable();

  CPPUNIT_ASSERT( returned != 0 );
  CPPUNIT_ASSERT( getTestSerializable()->getDataType() == returned->getDataType() );
  delete returned;
  CPPUNIT_ASSERT( myUnsigned == toTest->getUnsigned() );
}
Ejemplo n.º 25
0
Serializable *const Deserializer::Read(std::istream &stream)
{
    Serializable *pSerializable = 0;

    BEGIN_CODE_BLOCK
    {
        // Read the first Object's type
        std::string objectType;
        if( !ParseVariable( stream, "begin", objectType ) )
            break;

        // Create the object
        pSerializable = ObjectFactory<Serializable>::Create( objectType );
        if( !pSerializable )
        {
            std::cout << "Error: Unknown Object found: " << objectType << std::endl;
            EXIT_CODE_BLOCK;
        }

        // Load the object
        if( !pSerializable->Read( stream ) )
        {
            SAFE_DELETE_SCALAR( pSerializable );
            EXIT_CODE_BLOCK;
        }

        // Restore all pointers
        if( !RestoreAllPointers() )
        {
            SAFE_DELETE_SCALAR( pSerializable );
            EXIT_CODE_BLOCK;
        }
    }
    END_CODE_BLOCK;

    return pSerializable;
}
Ejemplo n.º 26
0
Buffer::Pointer
Buffer::write( const Serializable &object ) {
    Buffer::Pointer thisptr = shared_from_this();
    object.save(thisptr);
    return thisptr;
}
void SerializerStream::full_serialization(const Serializable &obj, bool include_typehashes){
	auto node = obj.get_object_node();
#ifdef LOG
	std::clog << "Traversing reference graph...\n";
#endif
	std::set<std::uint32_t> used_types;
	objectid_t root_object = 0;
	{
		std::vector<decltype(node)> stack, temp_stack;
		this->id_map[0] = 0;

		auto id = this->save_object(node.get_address());
		assert(id);
		root_object = id;
		this->node_map[id] = node;
		used_types.insert(node.get_typeid());
		stack.push_back(node);

		while (stack.size()){
			auto top = stack.back();
			stack.pop_back();
			if (!top.get_address())
				continue;
			top.get_children(temp_stack);
			for (auto &i : temp_stack){
				id = this->save_object(i.get_address());
				if (!id)
					continue;
				this->node_map[id] = i;
				used_types.insert(i.get_typeid());
				stack.push_back(i);
			}
			temp_stack.clear();
		}
	}
	if (include_typehashes){
#ifdef LOG
		std::clog <<
			"Travesal found " << this->node_map.size() << " objects.\n"
			"Serializing type hashes...\n";
#endif
		auto list = obj.get_metadata()->get_known_types();
		std::map<decltype(list[0].first), decltype(list[0].second) *> typemap;
		for (auto &i : list)
			typemap[i.first] = &i.second;
		this->serialize((std::uint32_t)used_types.size());
		for (auto &t : used_types){
			this->serialize(t);
			this->serialize_array(typemap[t]->digest);
		}
	}
#ifdef LOG
	std::clog << "Remapping object IDs...\n";
#endif

	{
		std::map<std::uint32_t, std::vector<objectid_t>> remap;
		for (auto &n : this->node_map)
			remap[n.second.get_typeid()].push_back(n.first);
		
		this->next_object_id = 1;
		decltype(this->node_map) temp;
		bool root_set = false;
		this->id_map.clear();
		this->id_map[0] = 0;
		for (auto &r : remap){
			for (auto i : r.second){
				auto &node = this->node_map[i];
				if (!node.get_address())
					continue;
				auto oid = this->save_object(node.get_address());
				if (!root_set && i == root_object){
					root_object = oid;
					root_set = true;
				}
				temp[oid] = node;
			}
		}
		this->node_map = temp;
	}

#ifdef LOG
	std::clog << "Serializing node map...\n";
#endif

	{
		std::vector<std::pair<std::uint32_t, objectid_t>> type_map;
		for (auto &n : this->node_map){
			auto type = n.second.get_typeid();
			if (!type)
				throw InternalErrorException();
			if (!type_map.size() || type != type_map.back().first){
				type_map.push_back(std::make_pair(type, n.first));
				continue;
			}
			type_map.back().second = std::max(type_map.back().second, n.first);
		}
		this->serialize((wire_size_t)type_map.size());
		for (auto &i : type_map){
			this->serialize(i.first);
			this->serialize(i.second);
		}
		this->serialize(root_object);
	}

#ifdef LOG
	std::clog << "Serializing nodes...\n";
#endif
	for (auto &n : this->node_map)
		n.second.serialize(*this);
#ifdef LOG
	std::clog << "Serialization done!\n";
#endif
}
Ejemplo n.º 28
0
bool BinaryFileStream::Save(const Serializable & val)
{
	val.Serialize(*this);
	return true;
}
Ejemplo n.º 29
0
void Serializer::serialize(const std::string& key, const Serializable& sObj) {
    auto newNode = util::make_unique<TxElement>(key);
    rootElement_->LinkEndChild(newNode.get());
    NodeSwitch nodeSwitch(*this, newNode.get());
    sObj.serialize(*this);
}
Ejemplo n.º 30
0
void Pololu::Usc::Usb::RestartScriptAt::read(std::istream& stream) {
  Serializable<unsigned char> subroutine;
  setSubroutine(subroutine.read(stream));
}