Ejemplo n.º 1
0
static void updateHelper (SLE::ref entry,
    boost::unordered_set< uint256 >& seen,
    boost::unordered_map< currencyIssuer_t, std::vector<OrderBook::pointer> >& destMap,
    boost::unordered_map< currencyIssuer_t, std::vector<OrderBook::pointer> >& sourceMap,
    boost::unordered_set< currencyIssuer_t >& XRPBooks,
    int& books)
{
    if ((entry->getType () == ltDIR_NODE) && (entry->isFieldPresent (sfExchangeRate)) &&
            (entry->getFieldH256 (sfRootIndex) == entry->getIndex()))
    {
        const uint160& ci = entry->getFieldH160 (sfTakerPaysCurrency);
        const uint160& co = entry->getFieldH160 (sfTakerGetsCurrency);
        const uint160& ii = entry->getFieldH160 (sfTakerPaysIssuer);
        const uint160& io = entry->getFieldH160 (sfTakerGetsIssuer);

        uint256 index = Ledger::getBookBase (ci, ii, co, io);

        if (seen.insert (index).second)
        {
            // VFALCO TODO Reduce the clunkiness of these parameter wrappers
            OrderBook::pointer book = boost::make_shared<OrderBook> (boost::cref (index),
                                      boost::cref (ci), boost::cref (co), boost::cref (ii), boost::cref (io));

            sourceMap[currencyIssuer_ct (ci, ii)].push_back (book);
            destMap[currencyIssuer_ct (co, io)].push_back (book);
            if (co.isZero())
                XRPBooks.insert(currencyIssuer_ct (ci, ii));
            ++books;
        }
    }
}
Ejemplo n.º 2
0
void MixMaterial::AddReferencedMaterials(boost::unordered_set<const Material *> &referencedMats) const {
	Material::AddReferencedMaterials(referencedMats);

	referencedMats.insert(matA);
	matA->AddReferencedMaterials(referencedMats);

	referencedMats.insert(matB);
	matB->AddReferencedMaterials(referencedMats);
}
Ejemplo n.º 3
0
Archivo: CGUI.cpp Proyecto: 2asoft/0ad
void CGUI::Xeromyces_ReadScript(XMBElement Element, CXeromyces* pFile, boost::unordered_set<VfsPath>& Paths)
{
	// Check for a 'file' parameter
	CStrW file(Element.GetAttributes().GetNamedItem(pFile->GetAttributeID("file")).FromUTF8());

	// If there is a file specified, open and execute it
	if (!file.empty())
	{
		Paths.insert(file);
		try
		{
			m_ScriptInterface->LoadGlobalScriptFile(file);
		}
		catch (PSERROR_Scripting& e)
		{
			LOGERROR("GUI: Error executing script %s: %s", utf8_from_wstring(file), e.what());
		}
	}

	// If it has a directory attribute, read all JS files in that directory
	CStrW directory(Element.GetAttributes().GetNamedItem(pFile->GetAttributeID("directory")).FromUTF8());
	if (!directory.empty())
	{
		VfsPaths pathnames;
		vfs::GetPathnames(g_VFS, directory, L"*.js", pathnames);
		for (const VfsPath& path : pathnames)
		{
			// Only load new files (so when the insert succeeds)
			if (Paths.insert(path).second)
				try
				{
					m_ScriptInterface->LoadGlobalScriptFile(path);
				}
				catch (PSERROR_Scripting& e)
				{
					LOGERROR("GUI: Error executing script %s: %s", path.string8(), e.what());
				}
		}
	}

	// Execute inline scripts
	try
	{
		CStr code(Element.GetText());
		if (!code.empty())
			m_ScriptInterface->LoadGlobalScript(L"Some XML file", code.FromUTF8());
	}
	catch (PSERROR_Scripting& e)
	{
		LOGERROR("GUI: Error executing inline script: %s", e.what());
	}
}
Ejemplo n.º 4
0
    inline void ObservableSettings::registerDeferredObservers(boost::unordered_set<Observer*>& observers) {
        if (updatesDeferred())
	{
		QL_TRACE("adding " << observers.size() << " observers to the deferred list");
        	deferredObservers_.insert(observers.begin(), observers.end());
	}
    }
Ejemplo n.º 5
0
void CGUI::Xeromyces_ReadScript(XMBElement Element, CXeromyces* pFile, boost::unordered_set<VfsPath>& Paths)
{
	// Check for a 'file' parameter
	CStrW file (Element.GetAttributes().GetNamedItem( pFile->GetAttributeID("file") ).FromUTF8());

	// If there is a file specified, open and execute it
	if (! file.empty())
	{
		Paths.insert(file);
		try
		{
			m_ScriptInterface->LoadGlobalScriptFile(file);
		}
		catch (PSERROR_Scripting& e)
		{
			LOGERROR(L"GUI: Error executing script %ls: %hs", file.c_str(), e.what());
		}
	}

	// Execute inline scripts
	try
	{
		CStr code (Element.GetText());
		if (! code.empty())
			m_ScriptInterface->LoadGlobalScript(L"Some XML file", code.FromUTF8());
	}
	catch (PSERROR_Scripting& e)
	{
		LOGERROR(L"GUI: Error executing inline script: %hs", e.what());
	}
}
Ejemplo n.º 6
0
void VNode::collect_vnodes(boost::unordered_set<Node*>& nodes,uint& total)
{
	total++;
	boost::unordered_set<Node*>::iterator it = nodes.find(this);
	if(it==nodes.end())
		nodes.insert(this);
}
Ejemplo n.º 7
0
void CPrivilagedInfoCallback::getAllTiles (boost::unordered_set<int3, ShashInt3> &tiles, int Player/*=-1*/, int level, int surface ) const
{
	if(Player >= GameConstants::PLAYER_LIMIT)
	{
		tlog1 << "Illegal call to getAllTiles !\n";
		return;
	}
	bool water = surface == 0 || surface == 2,
		land = surface == 0 || surface == 1;

	std::vector<int> floors;
	if(level == -1)
	{
		for(int b = 0; b < (gs->map->twoLevel ? 2 : 1); ++b)
		{
			floors.push_back(b);
		}
	}
	else
		floors.push_back(level);

	for (std::vector<int>::const_iterator i = floors.begin(); i!= floors.end(); i++)
	{
		register int zd = *i;
		for (int xd = 0; xd < gs->map->width; xd++)
		{
			for (int yd = 0; yd < gs->map->height; yd++)
			{
				if ((getTile (int3 (xd,yd,zd))->terType == 8 && water)
					|| (getTile (int3 (xd,yd,zd))->terType != 8 && land))
					tiles.insert(int3(xd,yd,zd));
			}
		}
	}
}
Ejemplo n.º 8
0
void CPrivilagedInfoCallback::getTilesInRange( boost::unordered_set<int3, ShashInt3> &tiles, int3 pos, int radious, int player/*=-1*/, int mode/*=0*/ ) const
{
	if(player >= GameConstants::PLAYER_LIMIT)
	{
		tlog1 << "Illegal call to getTilesInRange!\n";
		return;
	}
	if (radious == -1) //reveal entire map
		getAllTiles (tiles, player, -1, 0);
	else
	{
		const TeamState * team = gs->getPlayerTeam(player);
		for (int xd = std::max<int>(pos.x - radious , 0); xd <= std::min<int>(pos.x + radious, gs->map->width - 1); xd++)
		{
			for (int yd = std::max<int>(pos.y - radious, 0); yd <= std::min<int>(pos.y + radious, gs->map->height - 1); yd++)
			{
				double distance = pos.dist2d(int3(xd,yd,pos.z)) - 0.5;
				if(distance <= radious)
				{
					if(player < 0
						|| (mode == 1  && team->fogOfWarMap[xd][yd][pos.z]==0)
						|| (mode == -1 && team->fogOfWarMap[xd][yd][pos.z]==1)
					)
						tiles.insert(int3(xd,yd,pos.z));
				}
			}
		}
	}
}
Ejemplo n.º 9
0
Archivo: CGUI.cpp Proyecto: 2asoft/0ad
/**
 * @callgraph
 */
void CGUI::LoadXmlFile(const VfsPath& Filename, boost::unordered_set<VfsPath>& Paths)
{
	Paths.insert(Filename);

	CXeromyces XeroFile;
	if (XeroFile.Load(g_VFS, Filename, "gui") != PSRETURN_OK)
		return;

	XMBElement node = XeroFile.GetRoot();

	CStr root_name(XeroFile.GetElementString(node.GetNodeName()));
	try
	{
		if (root_name == "objects")
		{
			Xeromyces_ReadRootObjects(node, &XeroFile, Paths);

			// Re-cache all values so these gets cached too.
			//UpdateResolution();
		}
		else if (root_name == "sprites")
			Xeromyces_ReadRootSprites(node, &XeroFile);
		else if (root_name == "styles")
			Xeromyces_ReadRootStyles(node, &XeroFile);
		else if (root_name == "setup")
			Xeromyces_ReadRootSetup(node, &XeroFile);
		else
			debug_warn(L"CGUI::LoadXmlFile error");
	}
	catch (PSERROR_GUI& e)
	{
		LOGERROR("Errors loading GUI file %s (%u)", Filename.string8(), e.getCode());
		return;
	}
}
Ejemplo n.º 10
0
 inline std::pair<boost::unordered_set<boost::shared_ptr<Observable> >::iterator, bool>
 Observer::registerWith(const boost::shared_ptr<Observable>& h) {
     if (h) {
         h->registerObserver(this);
         return observables_.insert(h);
     }
     return std::make_pair(observables_.end(), false);
 }
Ejemplo n.º 11
0
void cluster_machine::dfs(const size_t curr, boost::unordered_set<size_t> &vis)
{
    vis.insert(curr);
    for (size_t e = first_[curr]; e != -1; e = next_[e]) {
        if ( vis.find(v_[e]) == vis.end() )
            dfs(v_[e], vis);
    }
}
Ejemplo n.º 12
0
PNS_NODE::PNS_NODE()
{
    // printf("MakeNode [%p, total = %d]\n", this, allocNodes.size());
    m_root = this;
    m_parent = NULL;
    m_maxClearance = 800000;    // fixme: depends on how thick traces are.
    m_index = new PNS_INDEX;
    allocNodes.insert( this );
}
Ejemplo n.º 13
0
void sanity_checks() {
 ASSERT_TRUE(cm.begin() == cm.end());

  for (size_t i = 0;i < NINS; ++i) {
    um.insert(17 * i);
  }
  
  graphlab::thread_group thrgroup;
  for (size_t i = 0; i < 10; ++i) {
    thrgroup.launch(boost::bind(parallel_inserter, 
                                i * NINS/10, 
                                (i + 1) * NINS / 10));

  }

  thrgroup.join();
   
  std::cout << "Size: " << cm.size() << std::endl;
  std::cout << "Capacity: " << cm.capacity() << std::endl;
  std::cout << "Load Factor: " << cm.load_factor() << std::endl;

  for (size_t i = 0;i < NINS; ++i) {
    if (cm.get_sync(17 * i).first == false) {
      std::cout << cm.count(17 * i) << "\n";
      std::cout << "Failure on: " << 17 * i << std::endl;
      assert(cm.get_sync(17 * i).first == true);
    }
    assert(um.count(17 * i) == 1);
  }
  assert(cm.size() == NINS);
  assert(um.size() == NINS);

  for (size_t i = 0;i < NINS; i+=2) {
    um.erase(17*i);
  }

  for (size_t i = 0; i < 10; ++i) {
    thrgroup.launch(boost::bind(parallel_erase, 
                                i * NINS/10, 
                                (i + 1) * NINS / 10));
  }

  thrgroup.join();
   

  for (size_t i = 0;i < NINS; i+=2) {
    assert(cm.get_sync(17*i).first == (bool)(i % 2));
    assert(um.count(17*i) == i % 2);
  }

  assert(cm.size() == NINS / 2);
  assert(um.size() == NINS / 2);
} 
Ejemplo n.º 14
0
/**
 * @callgraph
 */
void CGUI::LoadXmlFile(const VfsPath& Filename, boost::unordered_set<VfsPath>& Paths)
{
	Paths.insert(Filename);

	CXeromyces XeroFile;
	if (XeroFile.Load(g_VFS, Filename) != PSRETURN_OK)
		// Fail silently
		return;

	XMBElement node = XeroFile.GetRoot();

	// Check root element's (node) name so we know what kind of
	//  data we'll be expecting
	CStr root_name (XeroFile.GetElementString(node.GetNodeName()));

	try
	{

		if (root_name == "objects")
		{
			Xeromyces_ReadRootObjects(node, &XeroFile, Paths);

			// Re-cache all values so these gets cached too.
			//UpdateResolution();
		}
		else
		if (root_name == "sprites")
		{
			Xeromyces_ReadRootSprites(node, &XeroFile);
		}
		else
		if (root_name == "styles")
		{
			Xeromyces_ReadRootStyles(node, &XeroFile);
		}
		else
		if (root_name == "setup")
		{
			Xeromyces_ReadRootSetup(node, &XeroFile);
		}
		else
		{
			debug_warn(L"CGUI::LoadXmlFile error");
			// TODO Gee: Output in log
		}
	}
	catch (PSERROR_GUI& e)
	{
		LOGERROR(L"Errors loading GUI file %ls (%u)", Filename.string().c_str(), e.getCode());
		return;
	}
}
Ejemplo n.º 15
0
		static void deserialize(storage_type& s, boost::unordered_set<T>& o)
			{
			o = boost::unordered_set<T>();
			uint32_t sz;
			s.deserialize(sz);

			for (int32_t k = 0; k < sz; k++)
				{
				T key;
				s.deserialize(key);
				o.insert(key);
				}
			}
Ejemplo n.º 16
0
PNS_NODE::PNS_NODE()
{
    TRACE( 0, "PNS_NODE::create %p", this );
    m_depth = 0;
    m_root = this;
    m_parent = NULL;
    m_maxClearance = 800000;    // fixme: depends on how thick traces are.
    m_clearanceFunctor = NULL;
    m_index = new PNS_INDEX;
    m_collisionFilter = NULL;

#ifdef DEBUG
    allocNodes.insert( this );
#endif
}
Ejemplo n.º 17
0
    bool isLocalSipUri( const string& requestUri ) {

        static bool initialized = false ;
        static boost::unordered_set<string> setLocalUris ;

        if( !initialized ) {
            initialized = true ;

            nta_agent_t* agent = theOneAndOnlyController->getAgent() ;
            tport_t *t = nta_agent_tports( agent ) ;
            for (tport_t* tport = t; tport; tport = tport_next(tport) ) {
                const tp_name_t* tpn = tport_name( tport );
                if( 0 == strcmp( tpn->tpn_host, "*") ) 
                    continue ;

                string localUri = tpn->tpn_host ;
                localUri += ":" ;
                localUri += (tpn->tpn_port ? tpn->tpn_port : "5060");

                setLocalUris.insert( localUri ) ;

                if( 0 == strcmp(tpn->tpn_host,"127.0.0.1") ) {
                    localUri = "localhost:" ;
                    localUri += (tpn->tpn_port ? tpn->tpn_port : "5060");
                    setLocalUris.insert( localUri ) ;
                }
            }
       }

        url_t *url = url_make(theOneAndOnlyController->getHome(), requestUri.c_str() ) ;
        string uri = url->url_host ;
        uri += ":" ;
        uri += ( url->url_port ? url->url_port : "5060") ;

        return setLocalUris.end() != setLocalUris.find( uri ) ;
    }
Ejemplo n.º 18
0
void load(Archive & ar, boost::unordered_set<T> & t, unsigned int version)
{
    // clear the set
    t.clear();
    // read the size
    typedef typename boost::unordered_set<T>::size_type size_type;
    size_type size;
    ar & BOOST_SERIALIZATION_NVP(size);
    for (size_type i = 0; i < size; i++) {
        // read a pair
        T item;
        ar & boost::serialization::make_nvp("item"+i, item);
        // insert it into the set
        t.insert(item);
    }
}
Ejemplo n.º 19
0
void HyperTreeLoader::ExtractSourceTerminalSetFromHyperPath(
  const HyperPath &hp, boost::unordered_set<std::size_t> &sourceTerminalSet)
{
  for (std::vector<HyperPath::NodeSeq>::const_iterator p = hp.nodeSeqs.begin();
       p != hp.nodeSeqs.end(); ++p) {
    for (std::vector<std::size_t>::const_iterator q = p->begin();
         q != p->end(); ++q) {
      const std::size_t factorId = *q;
      if (factorId >= moses_MaxNumNonterminals &&
          factorId != HyperPath::kComma &&
          factorId != HyperPath::kEpsilon) {
        sourceTerminalSet.insert(factorId);
      }
    }
  }
}
Ejemplo n.º 20
0
void foo(boost::unordered_set<int>& x1,
        boost::unordered_map<int, int>& x2,
        boost::unordered_multiset<int>& x3,
        boost::unordered_multimap<int, int>& x4)
{
#if BOOST_WORKAROUND(__CODEGEARC__, BOOST_TESTED_AT(0x0613))
        struct dummy {
            boost::unordered_set<int> x1;
            boost::unordered_map<int, int> x2;
            boost::unordered_multiset<int> x3;
            boost::unordered_multimap<int, int> x4;
        };
#endif

    x1.insert(1);
    x2[2] = 2;
    x3.insert(3);
    x4.insert(std::make_pair(4, 5));
}
Ejemplo n.º 21
0
static bool collectShortcuts(const std::string & str, StringVector & vs) 
{
	static boost::unordered_set<std::string> commonFilters;
	if(commonFilters.empty()) {
#if RULE_KEY_HASH_LENGTH==7 // 7
		commonFilters.insert("http://");
		commonFilters.insert("ttp://w");
		commonFilters.insert("tp://ww");
		commonFilters.insert("p://www");
		commonFilters.insert("://www.");
#elif RULE_KEY_HASH_LENGTH==8 // 8
		commonFilters.insert("http://w");
		commonFilters.insert("ttp://ww");
		commonFilters.insert("tp://www");
		commonFilters.insert("p://www.");
#elif RULE_KEY_HASH_LENGTH==9 // 9
		commonFilters.insert("http://ww");
		commonFilters.insert("ttp://www");
		commonFilters.insert("tp://www.");
#endif
	}

	int i = 0;
	bool isFindShoutcut = false;
	while (i < abpmin(str.length() - RULE_KEY_HASH_LENGTH,80)) 
	{
		unsigned int j = i;
		for (; j < str.length(); j++) {
			if ((str[j] == '*' || str[j] == '^'))
			{
				break;
			}
		}
		for (unsigned int k = i; j - k >= RULE_KEY_HASH_LENGTH; k++) 
		{
			std::string key = str.substr(k, RULE_KEY_HASH_LENGTH);
			if(commonFilters.find(key)!=commonFilters.end())
				continue;
			isFindShoutcut = true;
			vs.push_back(key); //append(key);
		}
		i = j + 1;
	}
	return isFindShoutcut;
}
Ejemplo n.º 22
0
 inline std::pair<boost::unordered_set<Observer*>::iterator, bool>
 Observable::registerObserver(Observer* o) {
     return observers_.insert(o);
 }
Ejemplo n.º 23
0
Archivo: CGUI.cpp Proyecto: 2asoft/0ad
void CGUI::Xeromyces_ReadObject(XMBElement Element, CXeromyces* pFile, IGUIObject* pParent, std::vector<std::pair<CStr, CStr> >& NameSubst, boost::unordered_set<VfsPath>& Paths, u32 nesting_depth)
{
	ENSURE(pParent);

	XMBAttributeList attributes = Element.GetAttributes();

	CStr type(attributes.GetNamedItem(pFile->GetAttributeID("type")));
	if (type.empty())
		type = "empty";

	// Construct object from specified type
	//  henceforth, we need to do a rollback before aborting.
	//  i.e. releasing this object
	IGUIObject* object = ConstructObject(type);

	if (!object)
	{
		LOGERROR("GUI: Unrecognized object type \"%s\"", type.c_str());
		return;
	}

	// Cache some IDs for element attribute names, to avoid string comparisons
	#define ELMT(x) int elmt_##x = pFile->GetElementID(#x)
	#define ATTR(x) int attr_##x = pFile->GetAttributeID(#x)
	ELMT(object);
	ELMT(action);
	ELMT(repeat);
	ELMT(translatableAttribute);
	ELMT(translate);
	ELMT(attribute);
	ELMT(keep);
	ELMT(include);
	ATTR(style);
	ATTR(type);
	ATTR(name);
	ATTR(hotkey);
	ATTR(z);
	ATTR(on);
	ATTR(file);
	ATTR(directory);
	ATTR(id);
	ATTR(context);

	//
	//	Read Style and set defaults
	//
	//	If the setting "style" is set, try loading that setting.
	//
	//	Always load default (if it's available) first!
	//
	CStr argStyle(attributes.GetNamedItem(attr_style));

	if (m_Styles.count("default") == 1)
		object->LoadStyle(*this, "default");

	if (!argStyle.empty())
	{
		if (m_Styles.count(argStyle) == 0)
			LOGERROR("GUI: Trying to use style '%s' that doesn't exist.", argStyle.c_str());
		else
			object->LoadStyle(*this, argStyle);
	}

	bool NameSet = false;
	bool ManuallySetZ = false;

	CStrW inclusionPath;
	CStr hotkeyTag;

	for (XMBAttribute attr : attributes)
	{
		// If value is "null", then it is equivalent as never being entered
		if (CStr(attr.Value) == "null")
			continue;

		// Ignore "type" and "style", we've already checked it
		if (attr.Name == attr_type || attr.Name == attr_style)
			continue;

		if (attr.Name == attr_name)
		{
			CStr name(attr.Value);

			for (const std::pair<CStr, CStr>& sub : NameSubst)
				name.Replace(sub.first, sub.second);

			object->SetName(name);
			NameSet = true;
			continue;
		}

		if (attr.Name == attr_hotkey)
			hotkeyTag = attr.Value;

		if (attr.Name == attr_z)
			ManuallySetZ = true;

		if (object->SetSetting(pFile->GetAttributeString(attr.Name), attr.Value.FromUTF8(), true) != PSRETURN_OK)
			LOGERROR("GUI: (object: %s) Can't set \"%s\" to \"%s\"", object->GetPresentableName(), pFile->GetAttributeString(attr.Name), attr.Value);
	}

	// Check if name isn't set, generate an internal name in that case.
	if (!NameSet)
	{
		object->SetName("__internal(" + CStr::FromInt(m_InternalNameNumber) + ")");
		++m_InternalNameNumber;
	}

	if (!hotkeyTag.empty())
		m_HotkeyObjects[hotkeyTag].push_back(object);

	CStrW caption(Element.GetText().FromUTF8());
	if (!caption.empty())
		object->SetSetting("caption", caption, true);

	for (XMBElement child : Element.GetChildNodes())
	{
		// Check what name the elements got
		int element_name = child.GetNodeName();

		if (element_name == elmt_object)
		{
			// Call this function on the child
			Xeromyces_ReadObject(child, pFile, object, NameSubst, Paths, nesting_depth);
		}
		else if (element_name == elmt_action)
		{
			// Scripted <action> element

			// Check for a 'file' parameter
			CStrW filename(child.GetAttributes().GetNamedItem(attr_file).FromUTF8());

			CStr code;

			// If there is a file, open it and use it as the code
			if (!filename.empty())
			{
				Paths.insert(filename);
				CVFSFile scriptfile;
				if (scriptfile.Load(g_VFS, filename) != PSRETURN_OK)
				{
					LOGERROR("Error opening GUI script action file '%s'", utf8_from_wstring(filename));
					throw PSERROR_GUI_JSOpenFailed();
				}

				code = scriptfile.DecodeUTF8(); // assume it's UTF-8
			}

			XMBElementList grandchildren = child.GetChildNodes();
			if (!grandchildren.empty()) // The <action> element contains <keep> and <translate> tags.
				for (XMBElement grandchild : grandchildren)
				{
					if (grandchild.GetNodeName() == elmt_translate)
						code += g_L10n.Translate(grandchild.GetText());
					else if (grandchild.GetNodeName() == elmt_keep)
						code += grandchild.GetText();
				}
			else // It’s pure JavaScript code.
				// Read the inline code (concatenating to the file code, if both are specified)
				code += CStr(child.GetText());

			CStr action = CStr(child.GetAttributes().GetNamedItem(attr_on));

			// We need to set the GUI this object belongs to because RegisterScriptHandler requires an associated GUI.
			object->SetGUI(this);
			object->RegisterScriptHandler(action.LowerCase(), code, this);
		}
		else if (element_name == elmt_repeat)
		{
			Xeromyces_ReadRepeat(child, pFile, object, NameSubst, Paths, nesting_depth);
		}
		else if (element_name == elmt_translatableAttribute)
		{
			// This is an element in the form “<translatableAttribute id="attributeName">attributeValue</translatableAttribute>”.
			CStr attributeName(child.GetAttributes().GetNamedItem(attr_id)); // Read the attribute name.
			if (attributeName.empty())
			{
				LOGERROR("GUI: ‘translatableAttribute’ XML element with empty ‘id’ XML attribute found. (object: %s)", object->GetPresentableName().c_str());
				continue;
			}

			CStr value(child.GetText());
			if (value.empty())
				continue;

			CStr context(child.GetAttributes().GetNamedItem(attr_context)); // Read the context if any.
			if (!context.empty())
			{
				CStr translatedValue(g_L10n.TranslateWithContext(context, value));
				object->SetSetting(attributeName, translatedValue.FromUTF8(), true);
			}
			else
			{
				CStr translatedValue(g_L10n.Translate(value));
				object->SetSetting(attributeName, translatedValue.FromUTF8(), true);
			}
		}
		else if (element_name == elmt_attribute)
		{
			// This is an element in the form “<attribute id="attributeName"><keep>Don’t translate this part
			// </keep><translate>but translate this one.</translate></attribute>”.
			CStr attributeName(child.GetAttributes().GetNamedItem(attr_id)); // Read the attribute name.
			if (attributeName.empty())
			{
				LOGERROR("GUI: ‘attribute’ XML element with empty ‘id’ XML attribute found. (object: %s)", object->GetPresentableName().c_str());
				continue;
			}

			CStr translatedValue;

			for (XMBElement grandchild : child.GetChildNodes())
			{
				if (grandchild.GetNodeName() == elmt_translate)
					translatedValue += g_L10n.Translate(grandchild.GetText());
				else if (grandchild.GetNodeName() == elmt_keep)
					translatedValue += grandchild.GetText();
			}
			object->SetSetting(attributeName, translatedValue.FromUTF8(), true);
		}
		else if (element_name == elmt_include)
		{
			CStrW filename(child.GetAttributes().GetNamedItem(attr_file).FromUTF8());
			CStrW directory(child.GetAttributes().GetNamedItem(attr_directory).FromUTF8());
			if (!filename.empty())
			{
				if (!directory.empty())
					LOGWARNING("GUI: Include element found with file name (%s) and directory name (%s). Only the file will be processed.", utf8_from_wstring(filename), utf8_from_wstring(directory));

				Paths.insert(filename);

				CXeromyces XeroIncluded;
				if (XeroIncluded.Load(g_VFS, filename, "gui") != PSRETURN_OK)
				{
					LOGERROR("GUI: Error reading included XML: '%s'", utf8_from_wstring(filename));
					continue;
				}

				XMBElement node = XeroIncluded.GetRoot();
				if (node.GetNodeName() != XeroIncluded.GetElementID("object"))
				{
					LOGERROR("GUI: Error reading included XML: '%s', root element must have be of type 'object'.", utf8_from_wstring(filename));
					continue;
				}

				if (nesting_depth+1 >= MAX_OBJECT_DEPTH)
				{
					LOGERROR("GUI: Too many nested GUI includes. Probably caused by a recursive include attribute. Abort rendering '%s'.", utf8_from_wstring(filename));
					continue;
				}

				Xeromyces_ReadObject(node, &XeroIncluded, object, NameSubst, Paths, nesting_depth+1);
			}
			else if (!directory.empty())
			{
				if (nesting_depth+1 >= MAX_OBJECT_DEPTH)
				{
					LOGERROR("GUI: Too many nested GUI includes. Probably caused by a recursive include attribute. Abort rendering '%s'.", utf8_from_wstring(directory));
					continue;
				}

				VfsPaths pathnames;
				vfs::GetPathnames(g_VFS, directory, L"*.xml", pathnames);
				for (const VfsPath& path : pathnames)
				{
					// as opposed to loading scripts, don't care if it's loaded before
					// one might use the same parts of the GUI in different situations
					Paths.insert(path);
					CXeromyces XeroIncluded;
					if (XeroIncluded.Load(g_VFS, path, "gui") != PSRETURN_OK)
					{
						LOGERROR("GUI: Error reading included XML: '%s'", path.string8());
						continue;
					}

					XMBElement node = XeroIncluded.GetRoot();
					if (node.GetNodeName() != XeroIncluded.GetElementID("object"))
					{
						LOGERROR("GUI: Error reading included XML: '%s', root element must have be of type 'object'.", path.string8());
						continue;
					}
					Xeromyces_ReadObject(node, &XeroIncluded, object, NameSubst, Paths, nesting_depth+1);
				}

			}
			else
				LOGERROR("GUI: 'include' XML element must have valid 'file' or 'directory' attribute found. (object %s)", object->GetPresentableName().c_str());
		}
		else
		{
			// Try making the object read the tag.
			if (!object->HandleAdditionalChildren(child, pFile))
				LOGERROR("GUI: (object: %s) Reading unknown children for its type", object->GetPresentableName().c_str());
		}
	}

	if (!ManuallySetZ)
	{
		// Set it automatically to 10 plus its parents
		bool absolute;
		GUI<bool>::GetSetting(object, "absolute", absolute);

		if (absolute)
			// If the object is absolute, we'll have to get the parent's Z buffered,
			// and add to that!
			GUI<float>::SetSetting(object, "z", pParent->GetBufferedZ() + 10.f, true);
		else
			// If the object is relative, then we'll just store Z as "10"
			GUI<float>::SetSetting(object, "z", 10.f, true);
	}

	try
	{
		if (pParent == m_BaseObject)
			AddObject(object);
		else
			pParent->AddChild(object);
	}
	catch (PSERROR_GUI& e)
	{
		LOGERROR("GUI error: %s", e.what());
	}
}
Ejemplo n.º 24
0
 void operator()(const G&, const typename G::Index& index,
                 const typename G::Vector&) {
   seen_.insert(index);
 }
Ejemplo n.º 25
0
// Make sure an offer is still valid. If not, mark it unfunded.
bool OfferCreateTransactor::bValidOffer (
    SLE::ref            sleOfferDir,
    uint256 const&      uOfferIndex,
    const uint160&      uOfferOwnerID,
    const STAmount&     saOfferPays,
    const STAmount&     saOfferGets,
    const uint160&      uTakerAccountID,
    boost::unordered_set<uint256>&  usOfferUnfundedFound,
    boost::unordered_set<uint256>&  usOfferUnfundedBecame,
    boost::unordered_set<uint160>&  usAccountTouched,
    STAmount&           saOfferFunds)                       // <--
{
    bool    bValid;

    if (sleOfferDir->isFieldPresent (sfExpiration) && sleOfferDir->getFieldU32 (sfExpiration) <= mEngine->getLedger ()->getParentCloseTimeNC ())
    {
        // Offer is expired. Expired offers are considered unfunded. Delete it.
        WriteLog (lsINFO, OfferCreateTransactor) << "bValidOffer: encountered expired offer";

        usOfferUnfundedFound.insert (uOfferIndex);

        bValid  = false;
    }
    else if (uOfferOwnerID == uTakerAccountID)
    {
        // Would take own offer. Consider old offer expired. Delete it.
        WriteLog (lsINFO, OfferCreateTransactor) << "bValidOffer: encountered taker's own old offer";

        usOfferUnfundedFound.insert (uOfferIndex);

        bValid  = false;
    }
    else if (!saOfferGets.isPositive () || !saOfferPays.isPositive ())
    {
        // Offer has bad amounts. Consider offer expired. Delete it.
        WriteLog (lsWARNING, OfferCreateTransactor) << boost::str (boost::format ("bValidOffer: BAD OFFER: saOfferPays=%s saOfferGets=%s")
                % saOfferPays % saOfferGets);

        usOfferUnfundedFound.insert (uOfferIndex);
    }
    else
    {
        WriteLog (lsTRACE, OfferCreateTransactor) << "bValidOffer: saOfferPays=" << saOfferPays.getFullText ();

        saOfferFunds    = mEngine->getNodes ().accountFunds (uOfferOwnerID, saOfferPays);

        if (!saOfferFunds.isPositive ())
        {
            // Offer is unfunded, possibly due to previous balance action.
            WriteLog (lsDEBUG, OfferCreateTransactor) << "bValidOffer: offer unfunded: delete";

            boost::unordered_set<uint160>::iterator account = usAccountTouched.find (uOfferOwnerID);

            if (account != usAccountTouched.end ())
            {
                // Previously touched account.
                usOfferUnfundedBecame.insert (uOfferIndex); // Delete unfunded offer on success.
            }
            else
            {
                // Never touched source account.
                usOfferUnfundedFound.insert (uOfferIndex);  // Delete found unfunded offer when possible.
            }

            bValid  = false;
        }
        else
        {
            bValid  = true;
        }
    }

    return bValid;
}
Ejemplo n.º 26
0
void Object::add_live_object(Object* o) { live_.insert(o); }
Ejemplo n.º 27
0
/// Merge values (expects double) with the same key 
/// It merges values for identical key string that end in '/elapsed' and 
///  add a '/mean' key with the mean of the values 
/// All keys are returned via 'leaf_keys'
/// add_mean_key: adds '/mean' when sum combine '<path>/elapsed'
/// add_count_key: adds '/count' when sum combine '<path>/elapsed'
void merge_elapsed( boost::property_tree::ptree& tree, 
                    boost::unordered_set< std::string >& leaf_keys, 
                    bool add_mean_key, bool add_count_key )
{
    using boost::property_tree::ptree;
    
    std::string line;
    // counts the number of times a key is used for 'mean' value calculation e.g. for flight-prm
    boost::unordered_map< std::string, int > key_counts;    
    while( std::cin.good() && !std::cin.eof() )
    {
        std::getline( std::cin, line );
        if( line.empty() ) continue;
        std::string::size_type p = line.find_first_of( equal_sign );
        if( p == std::string::npos ) { COMMA_THROW( comma::exception, "expected '" << delimiter << "'-separated xpath" << equal_sign << "value pairs; got \"" << line << "\"" ); }
        
        //const std::string key = comma::strip( v[i].substr( 0, p );
        const std::string key_str = comma::strip( line.substr( 0, p ), '"' );
        ptree::path_type key( key_str, '/' );
        
        std::string value_str = comma::strip( line.substr( p + 1), '"' );
        
        // Only merges keys ending in '/elapsed'
        if( key_str.size() < elapsed_end.size() || key_str.substr( key_str.size() - elapsed_end.size() ) != elapsed_end ) { 
            tree.put( key, value_str );     // not 'elapsed' ending key, just put it into the ptree, may replaces earlier value for same key
        }
        else
        {   // This is /elapsed key, count occurances
            int& count = key_counts[ key_str ];
            ++count;
            
            // Get value and merge if needed
            
            double value = boost::lexical_cast< double >( value_str );
            
            // Check if there is an existing value, if so merge elapsed time
            boost::optional< double > existing_value = tree.get_optional< double >( key );
            if( existing_value ) { value += *existing_value; } // sum it up
            
            leaf_keys.insert( key_str );
            tree.put( key, value );
            
            // wether to create a 'mean' key - if there is more than one elapsed
            if( add_mean_key && count > 1 ) 
            {
                //make a 'mean' key by replacing /elapsed with /mean
                std::ostringstream ss;
                ss << key_str.substr( 0,  key_str.size() - elapsed_end.size() ) << "/mean";
                ptree::path_type mean_key( ss.str(), '/' );
                
                tree.put( mean_key, value/count );
                
                if( !add_count_key ) { continue; }
                std::ostringstream cc;
                cc << key_str.substr( 0,  key_str.size() - elapsed_end.size() ) << "/count";
                ptree::path_type count_key( cc.str(), '/' );
                tree.put( count_key, count );
            }
        }
        
    }
}
Ejemplo n.º 28
0
void CGUI::Xeromyces_ReadObject(XMBElement Element, CXeromyces* pFile, IGUIObject *pParent, const std::vector<std::pair<CStr, CStr> >& NameSubst, boost::unordered_set<VfsPath>& Paths)
{
	ENSURE(pParent);
	int i;

	// Our object we are going to create
	IGUIObject *object = NULL;

	XMBAttributeList attributes = Element.GetAttributes();

	// Well first of all we need to determine the type
	CStr type (attributes.GetNamedItem(pFile->GetAttributeID("type")));
	if (type.empty())
		type = "empty";

	// Construct object from specified type
	//  henceforth, we need to do a rollback before aborting.
	//  i.e. releasing this object
	object = ConstructObject(type);

	if (!object)
	{
		// Report error that object was unsuccessfully loaded
		LOGERROR(L"GUI: Unrecognized object type \"%hs\"", type.c_str());
		return;
	}

	// Cache some IDs for element attribute names, to avoid string comparisons
	#define ELMT(x) int elmt_##x = pFile->GetElementID(#x)
	#define ATTR(x) int attr_##x = pFile->GetAttributeID(#x)
	ELMT(object);
	ELMT(action);
	ELMT(repeat);
	ATTR(style);
	ATTR(type);
	ATTR(name);
	ATTR(hotkey);
	ATTR(z);
	ATTR(on);
	ATTR(file);

	//
	//	Read Style and set defaults
	//
	//	If the setting "style" is set, try loading that setting.
	//
	//	Always load default (if it's available) first!
	//
	CStr argStyle (attributes.GetNamedItem(attr_style));

	if (m_Styles.count("default") == 1)
		object->LoadStyle(*this, "default");

	if (! argStyle.empty())
	{
		// additional check
		if (m_Styles.count(argStyle) == 0)
		{
			LOGERROR(L"GUI: Trying to use style '%hs' that doesn't exist.", argStyle.c_str());
		}
		else object->LoadStyle(*this, argStyle);
	}
	

	//
	//	Read Attributes
	//

	bool NameSet = false;
	bool ManuallySetZ = false; // if z has been manually set, this turn true

	CStr hotkeyTag;

	// Now we can iterate all attributes and store
	for (i=0; i<attributes.Count; ++i)
	{
		XMBAttribute attr = attributes.Item(i);

		// If value is "null", then it is equivalent as never being entered
		if (CStr(attr.Value) == "null")
			continue;

		// Ignore "type" and "style", we've already checked it
		if (attr.Name == attr_type || attr.Name == attr_style)
			continue;

		// Also the name needs some special attention
		if (attr.Name == attr_name)
		{
			CStr name (attr.Value);

			// Apply the requested substitutions
			for (size_t j = 0; j < NameSubst.size(); ++j)
				name.Replace(NameSubst[j].first, NameSubst[j].second);

			object->SetName(name);
			NameSet = true;
			continue;
		}

		// Wire up the hotkey tag, if it has one
		if (attr.Name == attr_hotkey)
			hotkeyTag = attr.Value;

		if (attr.Name == attr_z)
			ManuallySetZ = true;

		// Try setting the value
		if (object->SetSetting(pFile->GetAttributeString(attr.Name), attr.Value.FromUTF8(), true) != PSRETURN_OK)
		{
			LOGERROR(L"GUI: (object: %hs) Can't set \"%hs\" to \"%ls\"", object->GetPresentableName().c_str(), pFile->GetAttributeString(attr.Name).c_str(), attr.Value.FromUTF8().c_str());

			// This is not a fatal error
		}
	}

	// Check if name isn't set, generate an internal name in that case.
	if (!NameSet)
	{
		object->SetName("__internal(" + CStr::FromInt(m_InternalNameNumber) + ")");
		++m_InternalNameNumber;
	}

	// Attempt to register the hotkey tag, if one was provided
	if (! hotkeyTag.empty())
		m_HotkeyObjects[hotkeyTag].push_back(object);

	CStrW caption (Element.GetText().FromUTF8());
	if (! caption.empty())
	{
		// Set the setting caption to this
		object->SetSetting("caption", caption, true);

		// There is no harm if the object didn't have a "caption"
	}


	//
	//	Read Children
	//

	// Iterate children
	XMBElementList children = Element.GetChildNodes();

	for (i=0; i<children.Count; ++i)
	{
		// Get node
		XMBElement child = children.Item(i);

		// Check what name the elements got
		int element_name = child.GetNodeName();

		if (element_name == elmt_object)
		{
			// Call this function on the child
			Xeromyces_ReadObject(child, pFile, object, NameSubst, Paths);
		}
		else if (element_name == elmt_action)
		{
			// Scripted <action> element

			// Check for a 'file' parameter
			CStrW filename (child.GetAttributes().GetNamedItem(attr_file).FromUTF8());

			CStr code;

			// If there is a file, open it and use it as the code
			if (! filename.empty())
			{
				Paths.insert(filename);
				CVFSFile scriptfile;
				if (scriptfile.Load(g_VFS, filename) != PSRETURN_OK)
				{
					LOGERROR(L"Error opening GUI script action file '%ls'", filename.c_str());
					throw PSERROR_GUI_JSOpenFailed();
				}

				code = scriptfile.DecodeUTF8(); // assume it's UTF-8
			}

			// Read the inline code (concatenating to the file code, if both are specified)
			code += CStr(child.GetText());

			CStr action = CStr(child.GetAttributes().GetNamedItem(attr_on));
			
			// We need to set the GUI this object belongs to because RegisterScriptHandler requires an associated GUI.
			object->SetGUI(this);
			object->RegisterScriptHandler(action.LowerCase(), code, this);
		}
		else if (element_name == elmt_repeat)
		{
			Xeromyces_ReadRepeat(child, pFile, object, Paths);
		}
		else
		{
			// Try making the object read the tag.
			if (!object->HandleAdditionalChildren(child, pFile))
			{
				LOGERROR(L"GUI: (object: %hs) Reading unknown children for its type", object->GetPresentableName().c_str());
			}
		}
	} 

	//
	//	Check if Z wasn't manually set
	//
	if (!ManuallySetZ)
	{
		// Set it automatically to 10 plus its parents
		bool absolute;
		GUI<bool>::GetSetting(object, "absolute", absolute);

		// If the object is absolute, we'll have to get the parent's Z buffered,
		//  and add to that!
		if (absolute)
		{
			GUI<float>::SetSetting(object, "z", pParent->GetBufferedZ() + 10.f, true);
		}
		else
		// If the object is relative, then we'll just store Z as "10"
		{
			GUI<float>::SetSetting(object, "z", 10.f, true);
		}
	}


	//
	//	Input Child
	//

	try
	{
		if (pParent == m_BaseObject)
			AddObject(object);
		else
			pParent->AddChild(object);
	}
	catch (PSERROR_GUI& e)
	{
		LOGERROR(L"GUI error: %hs", e.what());
	}
}