/**
 *	Inserts all the breakpoints, called after user provided 'continue' command
 *
 * 	@param pid: Process ID of the child (debuggee) 
 */
void insert_brkpt_batch( pid_t pid ) {
	for ( auto it = brkpt_batch.begin(); it != brkpt_batch.end(); ) {
		set_brkpt( pid, *it, true );
		brkpt_batch.erase( it++ /* makes a copy and destroys current it */ );
	}
}
Exemplo n.º 2
0
 vector<Interval> getIntervals() {
     return vector<Interval>(interval.begin(), interval.end());
 }
Exemplo n.º 3
0
int PolySolverNAD::FindBestSolution(SADNADGraph &graph, vector<pair<Node*, Node*> > availableSpecs, set<pair<Node*, Node*> > chosenSpecs, int verbose)
{


    if (availableSpecs.size() == 0)
    {
        //return the # of AD components
        int nb = graph.GetNbADComponents(chosenSpecs) - 1;

        if (verbose > 0)
        {

            cout<<" RETURNING "<<nb<<endl;

        }

        if (nb < bestSolSoFar)
        {
            bestSolSoFar = nb;
            bestChoiceSoFar = chosenSpecs;
        }

        return nb;
    }

    int bestWith = 0;
    int bestWithout = 0;

    //2 cases : next available spec is chosen, or not

    //EASY CASE : NOT CHOSEN
    vector<pair<Node*, Node*> > localAvailableSpecsWithout(availableSpecs);
    localAvailableSpecsWithout.erase(localAvailableSpecsWithout.begin());
    bestWithout = FindBestSolution(graph, localAvailableSpecsWithout, chosenSpecs, verbose);


    //TOUGH CASE : IT'S CHOSEN.  Then update what's available or not, and chosen or not
    set<pair<Node*, Node*> > localChosen(chosenSpecs);
    pair<Node*, Node*> nextSpec = availableSpecs[0];
    vector<pair<Node*, Node*> > localAvailableSpecs(availableSpecs);
    localChosen.insert(nextSpec);
    localAvailableSpecs.erase(localAvailableSpecs.begin());

    if (verbose > 0)
    {
        cout<<endl<<"CHOOSING AN EDGE "<<endl<<"AVAIL="<<availableSpecs.size()<<" CHOSEN="<<chosenSpecs.size();
        cout<<" Choice="<<nextSpec.first->GetLabel()<<" "<<nextSpec.second->GetLabel();

        for (vector<pair<Node*, Node*> >::iterator vit = availableSpecs.begin(); vit != availableSpecs.end(); vit++)
        {
            cout<<(*vit).first->GetLabel()<<" "<<(*vit).second->GetLabel()<<endl;
        }

        cout<<"CHOSEN="<<endl;

        for (set<pair<Node*, Node*> >::iterator vit = chosenSpecs.begin(); vit != chosenSpecs.end(); vit++)
        {
            cout<<(*vit).first->GetLabel()<<" "<<(*vit).second->GetLabel()<<endl;
        }
    }

    //automatically include every spec in the same clique as nextSpec
    //what nextSpec does is that it "combines" two cliques
    //first, get the 2 cliques the nextSpec vertices are in
    Node* v1 = nextSpec.first;
    Node* v2 = nextSpec.second;
    set<Node*> cliqueV1;
    cliqueV1.insert(v1);
    set<Node*> cliqueV2;
    cliqueV2.insert(v2);

    for (set<pair<Node*, Node*> >::iterator it = localChosen.begin(); it != localChosen.end(); it++)
    {
        pair<Node*, Node*> e = (*it);

        if (e != nextSpec)
        {
            if (e.first == v1)
                cliqueV1.insert(e.second);
            if (e.second == v1)
                cliqueV1.insert(e.first);

            if (e.first == v2)
                cliqueV2.insert(e.second);
            if (e.second == v2)
                cliqueV2.insert(e.first);
        }
    }


    //now, each cliqueV1 and cliqueV2 should be complete to eachother (otherwise this code is not working)
    //The spec edges that link these 2 cliques are chosen "by default", so no need to make them available
    vector<pair<Node*, Node*> >::iterator avit = localAvailableSpecs.begin();
    while (avit != localAvailableSpecs.end())
    {
        pair<Node*, Node*> e = (*avit);

        //NOTE : next spec shouldn't be in localAvailableSpecs
        if ((cliqueV1.find(e.first) != cliqueV1.end() && cliqueV2.find(e.second) != cliqueV2.end()) ||
            (cliqueV2.find(e.first) != cliqueV2.end() && cliqueV1.find(e.second) != cliqueV1.end()))
        {
            avit = localAvailableSpecs.erase(avit);
        }
        else
        {
            avit++;
        }
    }

    //we must add all these clique-joiners edges to the chosen ones.  They are not necessarely all
    //in the availables, so we must do it manually
    for (set<Node*>::iterator c1it = cliqueV1.begin(); c1it != cliqueV1.end(); c1it++)
    {
        Node* n1 = (*c1it);
        for (set<Node*>::iterator c2it = cliqueV2.begin(); c2it != cliqueV2.end(); c2it++)
        {
            Node* n2 = (*c2it);
            localChosen.insert( make_pair(n1, n2) );
        }
    }

    //then, make all speciations that wouldn't grow the clique properly unavailable
    //If W = cliqueV1 union cliqueV2, a node x  is bad w.r.t. W if it has a non-neighbor in W
    //or if x has a bad neighbor in chosen
    //A speciation in available cannot be chosen if
    //- it has one endpoint in W and the other in the bad set


    set<Node*> badNodes;  //first we find the set of such x that are bad
    const map<Node*, SADNADNode*> nodes = graph.GetNodes();
    for (map<Node*, SADNADNode*>::const_iterator itNodes = nodes.begin(); itNodes != nodes.end(); itNodes++)
    {
        Node* n = (*itNodes).first;
        SADNADNode* sad = (*itNodes).second;

        bool itIsBad = false;
        //try to find a non-neighbor of sad in W.  The AD+NAD edges are the complement of the S edges, by the way
        for (set<Node*>::iterator itSad = sad->AD_Neighbors.begin(); itSad != sad->AD_Neighbors.end() && !itIsBad; itSad++)
        {
            if (cliqueV1.find((*itSad)) != cliqueV1.end() || cliqueV2.find((*itSad)) != cliqueV2.end())
            {
                itIsBad = true;
            }
        }
        for (set<Node*>::iterator itSad = sad->NAD_Neighbors.begin(); itSad != sad->NAD_Neighbors.end() && !itIsBad; itSad++)
        {
            if (cliqueV1.find((*itSad)) != cliqueV1.end() || cliqueV2.find((*itSad)) != cliqueV2.end())
            {
                itIsBad = true;
            }
        }

        if (itIsBad)
        {
            badNodes.insert(n);

            //also add every clique nbr of n to the unchoosable
            for (set<pair<Node*, Node*> >::iterator vit = localChosen.begin(); vit != localChosen.end(); vit++)
            {
                if ((*vit).first == n)
                    badNodes.insert((*vit).second);
                if ((*vit).second == n)
                    badNodes.insert((*vit).first);
            }
        }
    }

    if (verbose > 0)
        cout<<" badNodes size="<<badNodes.size();

    //make unavailable all specs with one endpoint in badNodes and one in cliqueNbrs
    //TODO : this could be incorporated in the previous loop...here we keep it simple
    avit = localAvailableSpecs.begin();
    while (avit != localAvailableSpecs.end())
    {
        pair<Node*, Node*> e = (*avit);

        if ((badNodes.find(e.first) != badNodes.end() && cliqueV1.find(e.second) != cliqueV1.end()) ||
            (badNodes.find(e.second) != badNodes.end() && cliqueV1.find(e.first) != cliqueV1.end()) ||
            (badNodes.find(e.first) != badNodes.end() && cliqueV2.find(e.second) != cliqueV2.end()) ||
            (badNodes.find(e.second) != badNodes.end() && cliqueV2.find(e.first) != cliqueV2.end()))
        {
            avit = localAvailableSpecs.erase(avit);
        }
        else
        {
            avit++;
        }
    }

    if (verbose > 0)
    {
        cout<<endl<<"AfterAvail="<<localAvailableSpecs.size()<<endl;
    }

    bestWith = FindBestSolution(graph, localAvailableSpecs, localChosen, verbose);


    return min(bestWithout, bestWith);
}
Exemplo n.º 4
0
namespace v81c { namespace xml {


namespace patch {

// В сигвинѣ нѣт std::stoi

static
int stoi(const string &s)
{
    int r;
    sscanf(s.c_str(), "%d", &r);
    return r;
}

}

v8::String &__read(v8::String &dst, xmlpp::Node *element)
{
    const xmlpp::Node::NodeList children = element->get_children(); // совместимость с libxml++ < 2.36
    if (!children.empty()) {
        const xmlpp::Node *text = children.front();

        const xmlpp::TextNode *tn = dynamic_cast<const xmlpp::TextNode *>(text);
        string sc(tn->get_content().c_str());

        dst = v8::String(sc);

    } else
        dst = v8::String();

    return dst;
}

v8::StringInLanguage &__read(v8::StringInLanguage &dst, xmlpp::Node *element)
{
    v8::String lang;
    v8::String content;

    xmlpp::Node::PrefixNsMap ns;
    ns["xmlns"] = v8::xmlns;

    xmlpp::NodeSet nodes;
    nodes = element->find("xmlns:lang", ns);
    if (!nodes.empty()) {
        dst.setLang(__read(lang, nodes.at(0)));
    }

    nodes = element->find("xmlns:content", ns);
    if (!nodes.empty()) {
        dst.setContent(__read(content, nodes.at(0)));
    }

    return dst;
}

v8::StringInDifferentLanguages &
__read(v8::StringInDifferentLanguages &dst, xmlpp::Node *element)
{
    xmlpp::Node::PrefixNsMap ns;
    ns["xmlns"] = v8::xmlns;

    xmlpp::NodeSet nodes;
    nodes = element->find("xmlns:item", ns);

    dst.clear();

    for (auto node : nodes) {
        v8::StringInLanguage item;
        dst.push_back(__read(item, node));
    }

    return dst;
}

v8::Boolean &
__read(v8::Boolean &dst, xmlpp::Node *element)
{
    dst.setValue(false);

    const xmlpp::Node::NodeList children = element->get_children(); // совместимость с libxml++ < 2.36
    if (!children.empty()) {
        const xmlpp::Node *text = children.front();

        const xmlpp::TextNode *tn = dynamic_cast<const xmlpp::TextNode *>(text);
        string sc(tn->get_content().c_str());

        if (sc == "true")
            dst.setValue(true);

    }

    return dst;
}

v8::Number &
__read(v8::Number &dst, xmlpp::Node *element)
{
    const xmlpp::Node::NodeList children = element->get_children(); // совместимость с libxml++ < 2.36
    if (!children.empty()) {
        const xmlpp::Node *text = children.front();

        const xmlpp::TextNode *tn = dynamic_cast<const xmlpp::TextNode *>(text);
        string sc(tn->get_content().c_str());

        dst.setValue(patch::stoi(sc));
    }

    return dst;
}

// BooleanAuto отрабатываем отдельно, потому что в коде это Yes/No/Auto, а в файле true/false/...
lf::BooleanAuto &
__read(lf::BooleanAuto &dst, xmlpp::Node *element)
{
    dst = lf::BooleanAuto::Auto;

    const xmlpp::Node::NodeList children = element->get_children(); // совместимость с libxml++ < 2.36
    if (!children.empty()) {
        const xmlpp::Node *text = children.front();
        const xmlpp::TextNode *tn = dynamic_cast<const xmlpp::TextNode *>(text);
        string sc(tn->get_content().c_str());
        if (sc == "false") {
            dst = lf::BooleanAuto::No;
            return dst;
        }
        if (sc == "true") {
            dst = lf::BooleanAuto::Yes;
            return dst;
        }
    }
    return dst;
}


template <typename T>
void __read_one(T &dst, const string &name, xmlpp::Node *element)
{
    debug::mark(name);

    xmlpp::Node::NodeList children = element->get_children(name);
    if (children.empty())
        return;

    xmlpp::Node *child = children.front();
    if (child)
        __read(dst, child);
}

#ifdef DEBUG
static set<string> unrecognized;
#endif

template <typename T>
shared_ptr<T> new_element(const v8::Number &id, const v8::String &name)
{
    auto result = make_shared<T>();
    result->id = id;
    result->name = name;
    return result;
}

template <typename T>
shared_ptr<T> read_new(xmlpp::Node *element, const v8::Number &id, const v8::String &name)
{
    auto obj = new_element<T>(id, name);
    read(*obj, element);
    return obj;
}

lf::ColumnGroup &
__read(lf::ColumnGroup &dst, xmlpp::Node *element)
{

    debug::entry("ColumnGroup");

    __read_one(dst.Group, "Group", element);
    __read_one(dst.Items, "ChildItems", element);

    debug::out(element);

    return dst;

}

lf::FormTable &
__read(lf::FormTable &dst, xmlpp::Node *element)
{

    debug::entry("FormTable");

    __read_one(dst.AutoAddIncomplete, "AutoAddIncomplete", element);
    __read_one(dst.Autofill, "Autofill", element);
    __read_one(dst.AutoInsertNewRow, "AutoInsertNewRow", element);
    __read_one(dst.AutoMarkIncomplete, "AutoMarkIncomplete", element);
    __read_one(dst.ChangeRowOrder, "ChangeRowOrder", element);
    __read_one(dst.ChangeRowSet, "ChangeRowSet", element);
    __read_one(dst.ChildItems, "ChildItems", element);
    __read_one(dst.DataPath, "DataPath", element);
    __read_one(dst.DefaultItem, "DefaultItem", element);
    __read_one(dst.Footer, "Footer", element);
    __read_one(dst.FooterHeight, "FooterHeight", element);
    __read_one(dst.Header, "Header", element);
    __read_one(dst.HeaderHeight, "HeaderHeight", element);
    __read_one(dst.Height, "Height", element);
    __read_one(dst.HeightInTableRows, "HeightInTableRows", element);
    __read_one(dst.HorizontalLines, "HorizontalLines", element);
    __read_one(dst.HorizontalScrollBar, "HorizontalScrollBar", element);
    __read_one(dst.HorizontalStretch, "HorizontalStretch", element);
    __read_one(dst.Title, "Title", element);
    __read_one(dst.TitleLocation, "TitleLocation", element);
    __read_one(dst.VerticalLines, "VerticalLines", element);
    __read_one(dst.VerticalScrollBar, "VerticalScrollBar", element);
    __read_one(dst.VerticalStretch, "VerticalStretch", element);
    __read_one(dst.Width, "Width", element);

    debug::out(element);

	return dst;
}

shared_ptr<lf::ManagedFormElement> recognize_form_element(xmlpp::Node *node)
{
    xmlpp::Element *el = dynamic_cast<xmlpp::Element *>(node);
    if (!el)
        return nullptr;

    v8::String aName;
    v8::Number aId;

    xmlpp::Attribute *xaName = el->get_attribute("name");
    if (xaName) {
       aName = v8::String(string(xaName->get_value().c_str()));
    }
    xmlpp::Attribute *xaId = el->get_attribute("id");
    if (xaId) {
        aId = v8::Number(patch::stoi(string(xaId->get_value().c_str())));
    }

    string name(el->get_name().c_str());

    if (name == "InputField") {
        return read_new<lf::InputField>(node, aId, aName);
    } else

    if (name == "UsualGroup") {
        return read_new<lf::UsualGroup>(node, aId, aName);
    } else

    if (name == "Table") {
        return read_new<lf::FormTable>(node, aId, aName);
    } else
    if (name == "PictureField") {
        // read input field
    } else

    if (name == "ColumnGroup") {
        return read_new<lf::ColumnGroup>(node, aId, aName);
    } else

    if (name == "Pages") {
        // read input field
    } else

    if (name == "LabelField") {
        return read_new<lf::LabelField>(node, aId, aName);
    } else

    if (name == "CommandBar") {
        // read input field
    } else

    if (name == "PictureDecoration") {
        // read input field
    } else

    if (name == "LabelDecoration") {
        // read input field
    } else

    if (name == "RadioButtonField") {
        // read input field
    } else

    if (name == "Button") {
        // read input field
    } else

    if (name == "CheckBoxField") {
        // read input field
    } else

    if (name == "SpreadSheetDocumentField") {
        // read input field
    } else

    if (name == "TextDocumentField") {
        // read input field
    } else

    if (name == "HTMLDocumentField") {
        // read input field
    } else

    {
        #ifdef DEBUG
            if (unrecognized.find(name) == unrecognized.end()) {
                cout << "Unrecognized form element " << name << endl;
                unrecognized.insert(name);
            }
        #endif
        return nullptr;
    }

    return nullptr;
}

lf::UsualGroup &
__read(lf::UsualGroup &dst, xmlpp::Node *element)
{

    debug::entry("UsualGroup");

    __read_one(dst.Title, "Title", element);
    __read_one(dst.ToolTip, "ToolTip", element);
    __read_one(dst.ToolTipRepresentation, "ToolTipRepresentation", element);
    __read_one(dst.VerticalScroll, "VerticalScroll", element);
    __read_one(dst.Width, "Width", element);
    __read_one(dst.Group, "Group", element);
    __read_one(dst.VerticalStretch, "VerticalStretch", element);
    __read_one(dst.ChildItemsWidth, "ChildItemsWidth", element);


    __read_one(dst.ShowTitle, "ShowTitle", element);
    __read_one(dst.Visible, "Visible", element);
    __read_one(dst.Visible, "Enabled", element);
    __read_one(dst.Representation, "Representation", element);

    __read_one(dst.Items, "ChildItems", element);

    debug::out(element);

    return dst;
}

lf::InputField &
__read(lf::InputField &dst, xmlpp::Node *element)
{

    debug::entry("InputField");

    __read_one(dst.Width, "Width", element);
    __read_one(dst.Height, "Height", element);
    __read_one(dst.DataPath, "DataPath", element);
    __read_one(dst.HorizontalStretch, "HorizontalStretch", element);
    __read_one(dst.VerticalStretch, "VerticalStretch", element);
//    __read_one(dst.ContextMenu, "ContextMenu", element);
    __read_one(dst.ClearButton, "ClearButton", element);
//    __read_one(dst.ExtendedToolTip, "ExtendedToolTip", element);
//    __read_one(dst.Events, "Events", element);
    __read_one(dst.Title, "Title", element);
    __read_one(dst.ListChoiceMode, "ListChoiceMode", element);
//    __read_one(dst.ChooseType, "ChooseType", element);
    __read_one(dst.TextEdit, "TextEdit", element);
//    __read_one(dst.ChoiceList, "ChoiceList", element);
//    __read_one(dst.EditMode, "EditMode", element);
    __read_one(dst.ReadOnly, "ReadOnly", element);
    __read_one(dst.Wrap, "Wrap", element);
//    __read_one(dst.BorderColor, "BorderColor", element);
    __read_one(dst.ChoiceButton, "ChoiceButton", element);
    __read_one(dst.TitleLocation, "TitleLocation", element);
    __read_one(dst.MultyLine, "MultyLine", element);
    __read_one(dst.ChoiceListButton, "ChoiceListButton", element);
    __read_one(dst.ToolTip, "ToolTip", element);
    __read_one(dst.HorizontalAlign, "HorizontalAlign", element);
    __read_one(dst.EditFormat, "EditFormat", element);
    __read_one(dst.TypeDomainEnabled, "TypeDomainEnabled", element);
//    __read_one(dst.MinValue, "MinValue", element);
    __read_one(dst.FooterHorizontalAlign, "FooterHorizontalAlign", element);
    __read_one(dst.PasswordMode, "PasswordMode", element);
    __read_one(dst.OpenButton, "OpenButton", element);
//    __read_one(dst.ChoiceParameters, "ChoiceParameters", element);
    __read_one(dst.SpinButton, "SpinButton", element);

    debug::out(element);

    return dst;
}

lf::LabelField &
__read(lf::LabelField &dst, xmlpp::Node *element)
{
    debug::entry("LabelField");

    __read_one(dst.DataPath, "DataPath", element);

    debug::out(element);

    return dst;
}


lf::FormItems &
__read(lf::FormItems &dst, xmlpp::Node *element)
{
    dst.clear();

    xmlpp::Node::NodeList children = element->get_children();

    for (auto child : children) {
        auto element = recognize_form_element(child);
        if (element) {
            dst.push_back(element);
        }
    }

    return dst;
}


lf::ManagedForm &
__read(lf::ManagedForm &dst, xmlpp::Node *element)
{

    debug::entry("ManagedForm");

    __read_one(dst.Title, "Title", element);
    __read_one(dst.AutoTitle, "AutoTitle", element);
    __read_one(dst.Customizable, "Customizable", element);
    __read_one(dst.CommandBarLocation, "CommandBarLocation", element);
    __read_one(dst.VerticalScroll, "VerticalScroll", element);
    __read_one(dst.AutoSaveDataInSettings, "AutoSaveDataInSettings", element);
    __read_one(dst.SaveDataInSettings, "SaveDataInSettings", element);
    __read_one(dst.AutoTime, "AutoTime", element);
    __read_one(dst.UsePostingMode, "UsePostingMode", element);
    __read_one(dst.RepostOnWrite, "RepostOnWrite", element);
    __read_one(dst.WindowOpeningMode, "WindowOpeningMode", element);
    __read_one(dst.EnterKeyBehavior, "EnterKeyBehavior", element);
    __read_one(dst.UseForFoldersAndItems, "UseForFoldersAndItems", element);
    __read_one(dst.AutoFillCheck, "AutoFillCheck", element);
    __read_one(dst.Width, "Width", element);
    __read_one(dst.Group, "Group", element);
    __read_one(dst.ChildItemsWidth, "ChildItemsWidth", element);

    __read_one(dst.Items, "ChildItems", element);

    #ifdef DEBUG
    debug::out(element);
    #endif

    return dst;
}

}}
Exemplo n.º 5
0
static void InstrumentCalls (BPatch_image *appImage, BPatch_addressSpace *appProcess,
	ApplicationType *appType, set<string> &OMPset, set<string> &USERset,
    map<string, vector<string> > & LoopLevels,
    bool instrumentMPI, bool instrumentOMP, bool instrumentUF)
{
	unsigned i = 0;
	unsigned OMPinsertion = 0;
	unsigned OMPreplacement_intel_v11 = 0;
	unsigned MPIinsertion = 0;
	unsigned APIinsertion = 0;
	unsigned UFinsertion = 0;
	const char *PMPI_C_prefix = "PMPI_";
	const char *PMPI_F_prefix = "pmpi_";
	const char *MPI_C_prefix = "MPI_";
	const char *MPI_F_prefix= "mpi_";

	cout << PACKAGE_NAME << ": Obtaining functions from application image (this may take a while)..." << flush;
	BPatch_Vector<BPatch_function *> *vfunctions = appImage->getProcedures (false);
	cout << "Done" << endl;

	set<string> CUDAkernels;

	/* Look for CUDA kernels if the application is CUDA */
	if (appType->get_isCUDA())
	{
		cout << PACKAGE_NAME << ": Looking for CUDA kernels inside binary (this may take a while)..." << endl;

		i = 0;
		while (i < vfunctions->size())
		{
			char name[1024];

			BPatch_function *f = (*vfunctions)[i];
			f->getName (name, sizeof(name));
			BPatch_Vector<BPatch_point *> *vpoints = f->findPoint (BPatch_subroutine);

			if (vpoints != NULL)
			{
				unsigned j = 0;
				while (j < vpoints->size())
				{
					BPatch_function *called = ((*vpoints)[j])->getCalledFunction();
					if (NULL != called)
					{
						char calledname[1024];
						called->getName (calledname, 1024);
	
						if (strncmp (calledname, "__device_stub__", strlen("__device_stub__")) == 0)
						{
							CUDAkernels.insert (name);
							if (VerboseLevel)
								cout << PACKAGE_NAME << ": Found kernel " << name << endl;
						}
					}
					j++;
				}
			}
			i++;
		}
		cout << PACKAGE_NAME << ": Finished looking for CUDA kernels" << endl;
	}

	cout << PACKAGE_NAME << ": Parsing executable looking for instrumentation points (" << vfunctions->size() << ") ";
	if (VerboseLevel)
		cout << endl;
	else
		cout << flush;

	/*
	  The 1st step includes:
	  a) gather information of openmp outlined routines (original is added to USERset),
	  b) instrument openmp outlined routines
	  c) instrument mpi calls
	  d) instrument api calls
	*/

	i = 0;
	while (i < vfunctions->size())
	{
		char name[1024], sharedlibname_c[1024];

		BPatch_function *f = (*vfunctions)[i];
		(f->getModule())->getFullName (sharedlibname_c, sizeof(sharedlibname_c));
		f->getName (name, sizeof(name));

		string sharedlibname = sharedlibname_c;

		string sharedlibname_ext;
		if (sharedlibname.rfind('.') != string::npos)
			sharedlibname_ext = sharedlibname.substr (sharedlibname.rfind('.'));
		else
			sharedlibname_ext = "";

		/* For OpenMP apps, if the application has been linked with Extrae, just need to
		   instrument the function calls that have #pragma omp in them. The outlined
			 routines will be instrumented by the library attached to the binary */
		if (!BinaryLinkedWithInstrumentation &&
		    instrumentOMP && appType->get_isOpenMP() && loadedModule != sharedlibname)
		{
			/* OpenMP instrumentation (just for OpenMP apps) */
			if (appType->isMangledOpenMProutine (name))
			{
				if (VerboseLevel)
					if (!BinaryLinkedWithInstrumentation)
						cout << PACKAGE_NAME << ": Instrumenting OpenMP outlined routine " << name << endl;

				if (!BinaryLinkedWithInstrumentation)
				{
					/* Instrument routine */ 
					wrapTypeRoutine (f, name, OMPFUNC_EV, appImage);

					/* Add to list if not already there */
					OMPset.insert (name);
				}

				/* Demangle name and add into the UF list if it didn't exist there */
				string demangled = appType->demangleOpenMProutine (name);
				if (!XML_excludeAutomaticFunctions())
					USERset.insert (demangled);
				if (VerboseLevel)
				{
					if (!XML_excludeAutomaticFunctions())
						cout << PACKAGE_NAME << ": Adding demangled OpenMP routine " << demangled << " to the user function list" << endl;	
					else
						cout << PACKAGE_NAME << ": Will not add demangled OpenMP routine " << demangled << " due to user request in the XML configuration file" << endl;
				}

				OMPinsertion++;
			}
		}

		if (sharedlibname_ext == ".f" || sharedlibname_ext == ".F" ||   /* fortran */
		  sharedlibname_ext == ".for" || sharedlibname_ext == ".FOR" || /* fortran */
		  sharedlibname_ext == ".f90" || sharedlibname_ext == ".F90" || /* fortran 90 */
		  sharedlibname_ext == ".i90" ||                                /* fortran 90 through ifort */
		  sharedlibname_ext == ".f77" || sharedlibname_ext == ".F77" || /* fortran 77 */
		  sharedlibname_ext == ".c" || sharedlibname_ext == ".C" ||     /* C */
		  sharedlibname_ext == ".cxx" || sharedlibname_ext == ".cpp" || /* c++ */
		  sharedlibname_ext == ".c++" || /* c++ */
		  sharedlibname_ext == ".i" || /* some compilers generate this extension in intermediate files */ 
		  sharedlibname == "DEFAULT_MODULE" /* Dyninst specific container that represents the executable */
		)
		{
			/* API instrumentation (for any kind of apps)
	
			   Skip calls from my own module
			*/
			BPatch_Vector<BPatch_point *> *vpoints = f->findPoint (BPatch_subroutine);

			if (vpoints == NULL)
				break;

			if (VerboseLevel >= 2)
				printCallingSites (i, vfunctions->size(), name, sharedlibname, vpoints);

			unsigned j = 0;
			while (j < vpoints->size())
			{
				BPatch_function *called = ((*vpoints)[j])->getCalledFunction();
				if (NULL != called)
				{
					char calledname[1024];
					called->getName (calledname, 1024);

					/* Check API calls */
					BPatch_function *patch_api = getAPIPatch (calledname);
					if (patch_api != NULL)
					{
						if (appProcess->replaceFunctionCall (*((*vpoints)[j]), *patch_api))
						{
							APIinsertion++;
							if (VerboseLevel)
								cout << PACKAGE_NAME << ": Replaced call " << calledname << " in routine " << name << " (" << sharedlibname << ")" << endl;
						}
						else
							cerr << PACKAGE_NAME << ": Cannot replace " << calledname << " routine" << endl;
					}

					/* Check MPI calls */
					if (!BinaryLinkedWithInstrumentation &&
					    instrumentMPI && appType->get_isMPI() && (
					    strncmp (calledname, PMPI_C_prefix, 5) == 0 || strncmp (calledname, MPI_C_prefix, 4) == 0 ||
					    strncmp (calledname, PMPI_F_prefix, 5) == 0 || strncmp (calledname, MPI_F_prefix, 4) == 0))
					{
						BPatch_function *patch_mpi = getMPIPatch (calledname);
						if (patch_mpi != NULL)
						{
							if (appProcess->replaceFunctionCall (*((*vpoints)[j]), *patch_mpi))
							{
								MPIinsertion++;
								if (VerboseLevel)
									cout << PACKAGE_NAME << ": Replaced call " << calledname << " in routine " << name << " (" << sharedlibname << ")" << endl;
							}
							else
								cerr << PACKAGE_NAME << ": Cannot replace " << calledname << " routine" << endl;
						}
					}

					/* Special instrumentation for calls in Intel OpenMP runtime v11/v12
					   currently only for __kmpc_fork_call */
					if (!BinaryLinkedWithInstrumentation &&
					    appType->get_OpenMP_rte() == ApplicationType::Intel_v11 &&
					    strncmp (calledname, "__kmpc_fork_call", strlen("__kmpc_fork_call")) == 0)
					{
						BPatch_function *patch_openmp = getRoutine (
							"__kmpc_fork_call_extrae_dyninst", appImage, false);
						if (patch_openmp != NULL)
						{
							if (appProcess->replaceFunctionCall (*((*vpoints)[j]), *patch_openmp))
							{
								OMPreplacement_intel_v11++;
								if (VerboseLevel)
									cout << PACKAGE_NAME << ": Replaced call " << calledname << " in routine " << name << " (" << sharedlibname << ")" << endl;
							}
							else
								cerr << PACKAGE_NAME << ": Cannot replace " << calledname << " routine" << endl;
						}

						/* Instrument the routine that invokes the runtime */
						if (!XML_excludeAutomaticFunctions())
							USERset.insert (name);
						if (VerboseLevel)
						{
							if (!XML_excludeAutomaticFunctions())
								cout << PACKAGE_NAME << ": Adding call to OpenMP routine " << name << " to the user function list" << endl;
							else
								cout << PACKAGE_NAME << ": Will not add call to OpenMP routine " << name << " due to user request in the XML configuration file" << endl;
						}
					}

					/* Special instrumentation for fork() / wait() / exec* calls */
					if (!BinaryLinkedWithInstrumentation &&
					   (
					    strncmp (calledname, "fork", strlen("fork")) == 0 ||
					    strncmp (calledname, "wait", strlen("wait")) == 0 ||
					    strncmp (calledname, "waitpid", strlen("waitpid")) == 0 ||
					    strncmp (calledname, "system", strlen("system")) == 0 ||
					    strncmp (calledname, "execl", strlen("execl")) == 0 ||
					    strncmp (calledname, "execle", strlen("execle")) == 0 ||
					    strncmp (calledname, "execlp", strlen("execlp")) == 0 ||
					    strncmp (calledname, "execv", strlen("execv")) == 0 ||
					    strncmp (calledname, "execve", strlen("execve")) == 0 ||
					    strncmp (calledname, "execvp", strlen("execvp")) == 0
						)
					   )
					{
						/* Instrument the routine that invokes the runtime */
						if (!XML_excludeAutomaticFunctions())
							USERset.insert (name);
						if (VerboseLevel)
						{
							if (!XML_excludeAutomaticFunctions())
								cout << PACKAGE_NAME << ": Adding routine " << name << " to the user function list because it calls to " << calledname << endl;
							else
								cout << PACKAGE_NAME << ": Will not add routine to the user function list " << name << " due to user request in the XML configuration file" << endl;
						}
					}

					/* Instrument routines that call CUDA */
					if (appType->get_isCUDA())
					{
						string scalledname (calledname);

						if (find (CUDAkernels.begin(), CUDAkernels.end(), scalledname) != CUDAkernels.end())
						{
							if (!XML_excludeAutomaticFunctions())
								USERset.insert (name);

							if (VerboseLevel)
							{
								if (!XML_excludeAutomaticFunctions())
									cout << PACKAGE_NAME << ": Adding routine " << name << " to the user function list because it calls the CUDA kernel '" << calledname<< "'" << endl;	
								else
									cout << PACKAGE_NAME << ": Will not instrument CUDA routine " << name << " due to user request in the XML configuration file" << endl;
							}
						}
					}

				}
				j++;
			}
		}

		i++;

		if (!VerboseLevel)
		{
			if (i == 1)
				cout << "1" << flush;
			else if (i%1000 == 0)
				cout << i << flush;
			else if (i%100 == 0)
				cout << "." << flush;
		}
	}

	if (!VerboseLevel)
		cout << ".Done" << endl;

	if (USERset.size() > 0 && instrumentUF)
	{
		/* Instrument user functions! */

		cout << PACKAGE_NAME << ": Instrumenting user functions...";
		if (VerboseLevel)
			cout << endl;
		else
			cout << flush;

		set<string>::iterator iter = USERset.begin();
		while (iter != USERset.end())
		{
			if (*iter != "main")
			{
				BPatch_function *f = getRoutine ((*iter).c_str(), appImage);

				if (f != NULL)
				{
					wrapTypeRoutine (f, *iter, USRFUNC_EV, appImage);

                    vector<string> points = LoopLevels[*iter]; // LoopLevels['foo'] = [bb_1,loop_1.2.3,bb_5]
                    instrumentLoops(f, *iter, appImage, points);
                    instrumentBasicBlocks(f, appImage, points);

					UFinsertion++;

					if (VerboseLevel)
						cout << PACKAGE_NAME << ": Instrumenting user function : " << *iter << endl;
				}
				else
				{
					if (VerboseLevel)
						cout << PACKAGE_NAME << ": Unable to instrument user function : " << *iter << endl;
				}
			}
			else
			{
				if (VerboseLevel)
					cout << PACKAGE_NAME << ": Although 'main' symbol was in the instrumented functions list, it will not be instrumented" << endl;
			}
			iter++;
		}
		if (VerboseLevel)
			cout << PACKAGE_NAME << ": End of instrumenting functions" << endl;
		else
			cout << "Done" << endl;
	}

	cout << PACKAGE_NAME << ": " << APIinsertion << " API patches applied" << endl;
	if (appType->get_isMPI())
		cout << PACKAGE_NAME << ": " << MPIinsertion << " MPI patches applied" << endl;
	if (appType->get_isOpenMP())
	{
		cout << PACKAGE_NAME << ": " << OMPinsertion << " OpenMP patches applied to outlined routines" << endl;
		if (appType->get_OpenMP_rte() == ApplicationType::Intel_v11)
			cout << PACKAGE_NAME << ": " << OMPreplacement_intel_v11 << " OpenMP patches applied to specific locations for Intel runtime" << endl;
	}
	if (USERset.size() > 0)
		cout << PACKAGE_NAME << ": " << UFinsertion << " user function" << ((UFinsertion!=1)?"s":"") << " instrumented" << endl;
}
Exemplo n.º 6
0
void init_lookup_table() { vis.clear(); }
Exemplo n.º 7
0
void initialize_exclusion_set( set<string> &exs){
    static string _exclude[6] = {"a","an","the","but","or","and"};
    exs.insert(_exclude,_exclude+6);
}
Exemplo n.º 8
0
void WorklessInstrument::InstrumentWorkless0Or1Star(Module * pModule, Loop * pLoop, set<string> & setWorkingBlocks)
{
	LoadInst * pLoad0 = NULL;
	LoadInst * pLoad1 = NULL;
	//BinaryOperator* pAdd = NULL;
	StoreInst * pStore = NULL;
	CallInst * pCall = NULL;

	Function * pMain = NULL;

	if(strMainName != "" )
	{
		pMain = pModule->getFunction(strMainName.c_str());
	}
	else
	{
		pMain = pModule->getFunction("main");
	}

	for (Function::iterator BB = pMain->begin(); BB != pMain->end(); ++BB) 
	{
		if(BB->getName().equals("entry"))
		{
			CallInst * pCall;
			StoreInst * pStore;

			Instruction * II = BB->begin();
			pCall = CallInst::Create(this->InitHooks, "", II);
			pCall->setCallingConv(CallingConv::C);
			pCall->setTailCall(false);
			AttributeSet emptySet;
			pCall->setAttributes(emptySet);

			pCall = CallInst::Create(this->getenv, this->SAMPLE_RATE_ptr, "", II);
			pCall->setCallingConv(CallingConv::C);
			pCall->setTailCall(false);
			AttributeSet AS;
			{
				SmallVector<AttributeSet, 4> Attrs;
				AttributeSet PAS;
				{
					AttrBuilder B;
					B.addAttribute(Attribute::NoUnwind);
					PAS = AttributeSet::get(pModule->getContext(), ~0U, B);
				}
				Attrs.push_back(PAS);
				AS = AttributeSet::get(pModule->getContext(), Attrs);
			}
			pCall->setAttributes(AS);

			pCall = CallInst::Create(this->function_atoi, pCall, "", II);
			pCall->setCallingConv(CallingConv::C);
			pCall->setTailCall(false);
			{
  				SmallVector<AttributeSet, 4> Attrs;
   				AttributeSet PAS;
    			{
    	 			AttrBuilder B;
     				B.addAttribute(Attribute::NoUnwind);
     				B.addAttribute(Attribute::ReadOnly);
     				PAS = AttributeSet::get(pModule->getContext(), ~0U, B);
    			}
   
   				Attrs.push_back(PAS);
   				AS = AttributeSet::get(pModule->getContext(), Attrs);
   
  			}
  			pCall->setAttributes(AS);

  			pStore = new StoreInst(pCall, this->SAMPLE_RATE, false, II);
  			pStore->setAlignment(4);

  			pCall = CallInst::Create(this->geo, pCall, "", II);
  			pCall->setCallingConv(CallingConv::C);
  			pCall->setTailCall(false);
  			pCall->setAttributes(emptySet);

  			CastInst * pCast = CastInst::CreateIntegerCast(pCall, this->LongType, true, "", II);
  			pStore = new StoreInst(pCast, this->CURRENT_SAMPLE, false, II);
  			pStore->setAlignment(8);

  			vector<Value *> vecParam;
  			vecParam.push_back(this->Output_Format_String);
  			vecParam.push_back(pCall);
  			pCall = CallInst::Create(this->printf, vecParam, "", II);
  			pCall->setCallingConv(CallingConv::C);
  			pCall->setTailCall(false);
  			pCall->setAttributes(emptySet);
  			break;
		}
	}

	for (Function::iterator BB = pMain->begin(); BB != pMain->end(); ++BB) 
	{
		for (BasicBlock::iterator Ins = BB->begin(); Ins != BB->end(); ++Ins) 
		{
			if (isa<ReturnInst>(Ins) || isa<ResumeInst>(Ins)) 
			{
				vector<Value*> vecParams;
				pLoad0 = new LoadInst(numIterations, "", false, Ins); 
				pLoad0->setAlignment(8); 
				vecParams.push_back(pLoad0);
				pLoad1 = new LoadInst(numInstances, "", false, Ins); 
				pLoad1->setAlignment(8);
				vecParams.push_back(pLoad1);
				
				pCall = CallInst::Create(this->PrintLoopInfo, vecParams, "", Ins);
				pCall->setCallingConv(CallingConv::C);
				pCall->setTailCall(false);
				AttributeSet aSet;
				pCall->setAttributes(aSet);

				vecParams.clear();
				pLoad0 = new LoadInst(numIterations, "", false, Ins); 
				pLoad0->setAlignment(8); 
				vecParams.push_back(pLoad0);
				pLoad1 = new LoadInst(numWorkingIterations, "", false, Ins); 
				pLoad1->setAlignment(8);
				vecParams.push_back(pLoad1);


				pCall = CallInst::Create(PrintWorkingRatio, vecParams, "", Ins);
				pCall->setCallingConv(CallingConv::C);
				pCall->setTailCall(false);
				pCall->setAttributes(aSet);

			}
			else if(isa<CallInst>(Ins) || isa<InvokeInst>(Ins))
			{
				CallSite cs(Ins);
				Function * pCalled = cs.getCalledFunction();

				if(pCalled == NULL)
				{
					continue;
				}

				if(pCalled->getName() == "exit" || pCalled->getName() == "_ZL9mysql_endi")
				{
					vector<Value*> vecParams;
					pLoad0 = new LoadInst(numIterations, "", false, Ins);
					pLoad0->setAlignment(8); 
					vecParams.push_back(pLoad0);
					pLoad1 = new LoadInst(numInstances, "", false, Ins); 
					pLoad1->setAlignment(8);
					vecParams.push_back(pLoad1);

					pCall = CallInst::Create(this->PrintLoopInfo, vecParams, "", Ins);
					pCall->setCallingConv(CallingConv::C);
					pCall->setTailCall(false);
					AttributeSet aSet;
					pCall->setAttributes(aSet);

					vecParams.clear();
					pLoad0 = new LoadInst(numIterations, "", false, Ins); 
					pLoad0->setAlignment(8); 
					vecParams.push_back(pLoad0);
					pLoad1 = new LoadInst(numWorkingIterations, "", false, Ins); 
					pLoad1->setAlignment(8);
					vecParams.push_back(pLoad1);

					pCall = CallInst::Create(PrintWorkingRatio, vecParams, "", Ins);
					pCall->setCallingConv(CallingConv::C);
					pCall->setTailCall(false);
					pCall->setAttributes(aSet);
				}
			}
		}
	}

	Function * pFunction = pLoop->getHeader()->getParent();
	BasicBlock * pEntry = &(pFunction->getEntryBlock());

	AllocaInst * pAlloc = new AllocaInst(this->LongType, "bWorkingIteration.local", pEntry->getFirstInsertionPt());

	vector<BasicBlock *> vecWorkingBlock;
	
	for(Function::iterator BB = pFunction->begin(); BB != pFunction->end(); ++ BB)
	{
		if(setWorkingBlocks.find(BB->getName()) != setWorkingBlocks.end() )
		{
			vecWorkingBlock.push_back(BB);
		}
	}

	errs() << "working block number: " << vecWorkingBlock.size() << "\n";

	BasicBlock * pHeader = pLoop->getHeader();
	set<BasicBlock *> setExitBlock;
	CollectExitBlock(pLoop, setExitBlock);

	vector<BasicBlock *> vecAdded;
	CreateIfElseBlock(pLoop, vecAdded);

	ValueToValueMapTy  VMap;
	set<BasicBlock *> setCloned;
	CloneInnerLoop(pLoop, vecAdded, VMap, setCloned);

	//BasicBlock * pPreHeader = vecAdded[0];
	BasicBlock * pElseBody = vecAdded[1];
	
	vector<BasicBlock *>::iterator itVecBegin = vecWorkingBlock.begin();
	vector<BasicBlock *>::iterator itVecEnd   = vecWorkingBlock.end();

	for(; itVecBegin != itVecEnd; itVecBegin++ )
	{
		BasicBlock * pClonedBlock = cast<BasicBlock>(VMap[*itVecBegin]);
		pStore = new StoreInst(this->ConstantLong1, pAlloc, false, pClonedBlock->getFirstInsertionPt());
		pStore->setAlignment(8);
		pClonedBlock->dump();
	}


	pStore = new StoreInst(this->ConstantLong0, pAlloc, false, pElseBody->getTerminator());
	pStore->setAlignment(8);

	pLoad0 = new LoadInst(this->numIterations, "", false, pElseBody->getTerminator());
	pLoad0->setAlignment(8);

	pLoad1 = new LoadInst(this->numWorkingIterations, "", false, pElseBody->getTerminator());
	pLoad1->setAlignment(8);  

	BasicBlock * pClonedHeader = cast<BasicBlock>(VMap[pHeader]);

	set<BasicBlock *> setPredBlocks;

	for(pred_iterator PI = pred_begin(pClonedHeader), E = pred_end(pClonedHeader); PI != E; ++PI)
	{
		setPredBlocks.insert(*PI);
	}

	BasicBlock::iterator itInsert = pClonedHeader->getFirstInsertionPt();

	PHINode * pNewIterations = PHINode::Create(pLoad0->getType(), setPredBlocks.size(), "numIterations.2", itInsert);
	PHINode * pNewWorkingIterations = PHINode::Create(pLoad1->getType(), setPredBlocks.size(), "WorkingIterations.2", itInsert);

	BinaryOperator * pIterationAdd = BinaryOperator::Create(Instruction::Add, pNewIterations, this->ConstantLong1, "Iterations.add.2", itInsert);

	set<BasicBlock *>::iterator itSetBegin = setPredBlocks.begin();
	set<BasicBlock *>::iterator itSetEnd   = setPredBlocks.end();

	for(; itSetBegin != itSetEnd; itSetBegin ++ )
	{
		if((*itSetBegin) == pElseBody)
		{
			pNewIterations->addIncoming(pLoad0, pElseBody);
		}
		else
		{
			pNewIterations->addIncoming(pIterationAdd, *itSetBegin);
		}
	}

	pLoad0 = new LoadInst(pAlloc, "", false, itInsert);
	BinaryOperator * pWorkingAdd = 	BinaryOperator::Create(Instruction::Add, pNewWorkingIterations, pLoad0, "Working.add.2", itInsert);

	itSetBegin = setPredBlocks.begin();
	itSetEnd   = setPredBlocks.end();

	for(; itSetBegin != itSetEnd; itSetBegin ++ )
	{
		if((*itSetBegin) == pElseBody)
		{
			pNewWorkingIterations->addIncoming(pLoad1, pElseBody);
		}
		else
		{
			pNewWorkingIterations->addIncoming(pWorkingAdd, *itSetBegin);
		}
	}

	pStore = new StoreInst(this->ConstantLong0, pAlloc, false, itInsert);
	pStore->setAlignment(8);


	itSetBegin = setExitBlock.begin();
	itSetEnd   = setExitBlock.end();

	for(; itSetBegin != itSetEnd; itSetBegin ++ )
	{
		SmallVector<BasicBlock*, 8> LoopBlocks;

		for(pred_iterator PI = pred_begin(*itSetBegin), E = pred_end(*itSetBegin); PI != E; ++PI)
		{
			if(setCloned.find(*PI) != setCloned.end())
			{
				LoopBlocks.push_back(*PI);
			}
		}

		BasicBlock * NewExitBB = SplitBlockPredecessors(*itSetBegin, LoopBlocks, ".WL.loopexit", this);

		pStore = new StoreInst(pIterationAdd, this->numIterations, false, NewExitBB->getFirstInsertionPt());
		pStore->setAlignment(8);

		pStore = new StoreInst(pWorkingAdd, this->numWorkingIterations, false, NewExitBB->getFirstInsertionPt());
		pStore->setAlignment(8);
	}

	//pFunction->dump();

	DominatorTree * DT = &(getAnalysis<DominatorTree>(*pFunction));
	vector<AllocaInst *> vecAlloc;
	vecAlloc.push_back(pAlloc);
	PromoteMemToReg(vecAlloc, *DT);

	pFunction->dump();
}
Exemplo n.º 9
0
void CDetCandit::Creating_DismCase_Cases(const char* inputchar, size_t i, size_t SENID, size_t& CASID,  set<size_t>&  START_s, set<size_t>& END_s, map<size_t, double>& START_Rtn_map, 
map<size_t, double>& END_Rtn_map, map<size_t, set<size_t>>& pmSavedPair, map<size_t, map<size_t, ACE_entity_mention*>>& EntityMention_mm, vector<CanditCase*>& pmCandit_v)
{
	size_t length = NLPOP::Get_Chinese_Sentence_Length_Counter(inputchar);


	if((START_s.find(i) != START_s.end()) && START_Feedback_Ref_Flag){
		multimap<double, size_t> FeedbackCase_mm;
		if(!Greedy_Matching_Method_FLag){
			size_t FeedBorder = Get_END_Boundary_Range_For_START(START_s, END_s, i, length);
			for(size_t j = i; j <= FeedBorder; j++){//:* <? <=?
				if(END_Rtn_map.find(j) == END_Rtn_map.end()){//decreasing performance...
					continue;
				}
				if(END_s.find(j) != END_s.end()){
					FeedbackCase_mm.insert(make_pair(2, j));
				}
				else if(END_Rtn_map[j] > FEEDBACE_PRO_LIMIT){
					FeedbackCase_mm.insert(make_pair(END_Rtn_map[j], j));
				}
			}
		}
		else{
			//AppCall::Secretary_Message_Box("Can not be use yet! in CDetCandit::Creating_DismCase_Cases()", MB_OK);
		}
		Erasing_Prescribed_Candidates(FeedbackCase_mm);
		for(multimap<double, size_t>::iterator mmite = FeedbackCase_mm.begin(); mmite != FeedbackCase_mm.end(); mmite++){
			if(Exist_Detection_and_Updata(pmSavedPair, i, mmite->second)){
				continue;
			}
			pCanditCase ploc_Candit = new CanditCase;
			ploc_Candit->SENID = SENID;
			ploc_Candit->CASID = CASID++;
			ploc_Candit->CEDT_Head_Flag = CEDT_Head_Flag;
//			ploc_Candit->Detection_Flag = CEDT_Detection_Flag;
			ploc_Candit->START = i;
			ploc_Candit->END = mmite->second;

			int Left_Out_Range = Get_Left_Outer_Feature_Range_For_START(START_s, END_s, ploc_Candit->START, -1);
			int Right_Out_Range = Get_Right_Outer_Feature_Range_For_END(START_s, END_s, ploc_Candit->END, length-1);
			ploc_Candit->l_outmstr = Sentop::Get_Substr_by_Chinese_Character_Cnt(inputchar, Left_Out_Range+1, ploc_Candit->START-Left_Out_Range-1);
			ploc_Candit->r_outmstr = Sentop::Get_Substr_by_Chinese_Character_Cnt(inputchar, ploc_Candit->END+1, Right_Out_Range-ploc_Candit->END-1);
			
			ploc_Candit->prix = Sentop::Get_Substr_by_Chinese_Character_Cnt(inputchar, 0, ploc_Candit->START);
			ploc_Candit->prox = Sentop::Get_Substr_by_Chinese_Character_Cnt(inputchar, ploc_Candit->END+1, -1);
			ploc_Candit->mention = Sentop::Get_Substr_by_Chinese_Character_Cnt(inputchar, ploc_Candit->START, ploc_Candit->END-ploc_Candit->START+1);

			ploc_Candit->Cand_Flag = false;
			ploc_Candit->pNE_mention = NULL;
			ploc_Candit->predit_TYPE = (Detect_Single_NE_TYPE.length()==0)?POSITIVE:Detect_Single_NE_TYPE;
			ploc_Candit->org_TYPE = NEGETIVE;
			if(EntityMention_mm.find(ploc_Candit->START) != EntityMention_mm.end()){
				if(EntityMention_mm[ploc_Candit->START].find(ploc_Candit->END) != EntityMention_mm[ploc_Candit->START].end()){
					ploc_Candit->Cand_Flag = true;
					ploc_Candit->pNE_mention = EntityMention_mm[ploc_Candit->START][ploc_Candit->END];
					ploc_Candit->org_TYPE = CEDT_Detection_Flag?POSITIVE:EntityMention_mm[ploc_Candit->START][ploc_Candit->END]->Entity_TYPE;
				}
			}
			pmCandit_v.push_back(ploc_Candit);
		}
	}
	if((END_s.find(i) != END_s.end()) && END_Feedback_Ref_Flag){
		multimap<double, size_t> FeedbackCase_mm;
		if(!Greedy_Matching_Method_FLag){
			int FeedBorder = Get_START_Boundary_Range_For_END(START_s, END_s, i, 0);
			for(int j = i; j >= FeedBorder; j--){
				if(START_Rtn_map.find(j) == START_Rtn_map.end()){
					continue;
				}
				if(START_s.find(j) != START_s.end()){
					FeedbackCase_mm.insert(make_pair(2, j));
				}
				else if(START_Rtn_map[j] > FEEDBACE_PRO_LIMIT){
					FeedbackCase_mm.insert(make_pair(START_Rtn_map[j], j));
				}
			}
		}
		else{
			set<size_t> matched_s;
			Greedy_Right_to_Left_matching(START_s, END_s, i, 0, 2, matched_s);
			//Greedy_Left_to_Right_matching(START_s, END_s, i, length-1, 2, matched_s);

			for(set<size_t>::iterator site = matched_s.begin(); site != matched_s.end(); site++){
				if(START_Rtn_map.find(*site) == START_Rtn_map.end()){
					continue;
				}
				else{
					FeedbackCase_mm.insert(make_pair(START_Rtn_map[*site], *site));
				}
			}
		}
		Erasing_Prescribed_Candidates(FeedbackCase_mm);
		for(multimap<double, size_t>::iterator mmite = FeedbackCase_mm.begin(); mmite != FeedbackCase_mm.end(); mmite++){
			if(Exist_Detection_and_Updata(pmSavedPair, mmite->second, i)){
				continue;
			}
			pCanditCase ploc_Candit = new CanditCase;
			ploc_Candit->SENID = SENID;
			ploc_Candit->CASID = CASID++;
			ploc_Candit->CEDT_Head_Flag = CEDT_Head_Flag;
			ploc_Candit->Detection_Flag = CEDT_Detection_Flag;
			ploc_Candit->START = mmite->second;
			ploc_Candit->END = i;

			int Left_Out_Range = Get_Left_Outer_Feature_Range_For_START(START_s, END_s, ploc_Candit->START, -1);
			int Right_Out_Range = Get_Right_Outer_Feature_Range_For_END(START_s, END_s, ploc_Candit->END, length-1);
			ploc_Candit->l_outmstr = Sentop::Get_Substr_by_Chinese_Character_Cnt(inputchar, Left_Out_Range+1, ploc_Candit->START-Left_Out_Range-1);
			ploc_Candit->r_outmstr = Sentop::Get_Substr_by_Chinese_Character_Cnt(inputchar, ploc_Candit->END+1, Right_Out_Range-ploc_Candit->END-1);
			
			ploc_Candit->prix = Sentop::Get_Substr_by_Chinese_Character_Cnt(inputchar, 0, ploc_Candit->START);
			ploc_Candit->prox = Sentop::Get_Substr_by_Chinese_Character_Cnt(inputchar, ploc_Candit->END+1, -1);
			ploc_Candit->mention = Sentop::Get_Substr_by_Chinese_Character_Cnt(inputchar, ploc_Candit->START, ploc_Candit->END-ploc_Candit->START+1);
			
			ploc_Candit->Cand_Flag = false;
			ploc_Candit->pNE_mention = NULL;
			ploc_Candit->predit_TYPE = (Detect_Single_NE_TYPE.length()==0)?POSITIVE:Detect_Single_NE_TYPE;
			ploc_Candit->org_TYPE = NEGETIVE;
			if(EntityMention_mm.find(ploc_Candit->START) != EntityMention_mm.end()){
				if(EntityMention_mm[ploc_Candit->START].find(ploc_Candit->END) != EntityMention_mm[ploc_Candit->START].end()){
					ploc_Candit->Cand_Flag = true;
					ploc_Candit->pNE_mention = EntityMention_mm[ploc_Candit->START][ploc_Candit->END];
					ploc_Candit->org_TYPE = CEDT_Detection_Flag?POSITIVE:EntityMention_mm[ploc_Candit->START][ploc_Candit->END]->Entity_TYPE;
				}
			}
			pmCandit_v.push_back(ploc_Candit);
		}
	}
}
Exemplo n.º 10
0
 void MemoryMappedFile::created(){
     mmfiles.insert(this);
 }
Exemplo n.º 11
0
void WorklessInstrument::CloneInnerLoop(Loop * pLoop, vector<BasicBlock *> & vecAdd, ValueToValueMapTy & VMap, set<BasicBlock *> & setCloned)
{
	Function * pFunction = pLoop->getHeader()->getParent();
	BasicBlock * pPreHeader = vecAdd[0];

	SmallVector<BasicBlock *, 4> ExitBlocks;
	pLoop->getExitBlocks(ExitBlocks);

	set<BasicBlock *> setExitBlocks;

	for(unsigned long i = 0; i < ExitBlocks.size(); i++)
	{
		setExitBlocks.insert(ExitBlocks[i]);
	}

	for(unsigned long i = 0; i < ExitBlocks.size(); i++ )
	{
		VMap[ExitBlocks[i]] = ExitBlocks[i];
	}

	vector<BasicBlock *> ToClone;
	vector<BasicBlock *> BeenCloned;

	
	//clone loop
	ToClone.push_back(pLoop->getHeader());

	while(ToClone.size()>0)
	{
		BasicBlock * pCurrent = ToClone.back();
		ToClone.pop_back();

		WeakVH & BBEntry = VMap[pCurrent];
		if (BBEntry)
		{
			continue;
		}

		BasicBlock * NewBB;
		BBEntry = NewBB = BasicBlock::Create(pCurrent->getContext(), "", pFunction);

		if(pCurrent->hasName())
		{
			NewBB->setName(pCurrent->getName() + ".CPI");
		}

		if(pCurrent->hasAddressTaken())
		{
			errs() << "hasAddressTaken branch\n" ;
			exit(0);
		}

		for(BasicBlock::const_iterator II = pCurrent->begin(); II != pCurrent->end(); ++II )
		{
			Instruction * NewInst = II->clone();
			if(II->hasName())
			{
				NewInst->setName(II->getName() + ".CPI");
			}
			VMap[II] = NewInst;
			NewBB->getInstList().push_back(NewInst);
		}

		const TerminatorInst *TI = pCurrent->getTerminator();
		for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
		{
			ToClone.push_back(TI->getSuccessor(i));
		}

		setCloned.insert(NewBB);
		BeenCloned.push_back(NewBB);
	}

	//remap value used inside loop
	vector<BasicBlock *>::iterator itVecBegin = BeenCloned.begin();
	vector<BasicBlock *>::iterator itVecEnd = BeenCloned.end();

	for(; itVecBegin != itVecEnd; itVecBegin ++)
	{
		for(BasicBlock::iterator II = (*itVecBegin)->begin(); II != (*itVecBegin)->end(); II ++ )
		{
			//II->dump();
			RemapInstruction(II, VMap);
		}
	}

	//add to the else if body
	BasicBlock * pElseBody = vecAdd[1];

	BasicBlock * pClonedHeader = cast<BasicBlock>(VMap[pLoop->getHeader()]);

	BranchInst::Create(pClonedHeader, pElseBody);

	//errs() << pPreHeader->getName() << "\n";
	for(BasicBlock::iterator II = pClonedHeader->begin(); II != pClonedHeader->end(); II ++ )
	{
		if(PHINode * pPHI = dyn_cast<PHINode>(II))
		{
			vector<int> vecToRemoved;
			for (unsigned i = 0, e = pPHI->getNumIncomingValues(); i != e; ++i) 
			{
				if(pPHI->getIncomingBlock(i) == pPreHeader)
				{
					pPHI->setIncomingBlock(i, pElseBody);
				}
			}
		}
	}

	set<BasicBlock *> setProcessedBlock;

	for(unsigned long i = 0; i < ExitBlocks.size(); i++ )
	{
		if(setProcessedBlock.find(ExitBlocks[i]) != setProcessedBlock.end() )
		{
			continue;
		}
		else
		{
			setProcessedBlock.insert(ExitBlocks[i]);
		}

		for(BasicBlock::iterator II = ExitBlocks[i]->begin(); II != ExitBlocks[i]->end(); II ++ )
		{
			if(PHINode * pPHI = dyn_cast<PHINode>(II))
			{
				unsigned numIncomming = pPHI->getNumIncomingValues();
				for(unsigned i = 0; i<numIncomming; i++)
				{
					BasicBlock * incommingBlock = pPHI->getIncomingBlock(i);
					if(VMap.find(incommingBlock) != VMap.end() )
					{
						Value * incommingValue = pPHI->getIncomingValue(i);

						if(VMap.find(incommingValue) != VMap.end() )
						{
							incommingValue = VMap[incommingValue];
						}

						pPHI->addIncoming(incommingValue, cast<BasicBlock>(VMap[incommingBlock]));

					}
				} 

			}
		}
	}
}
Exemplo n.º 12
0
 MemoryMappedFile::~MemoryMappedFile() {
     close();
     mmfiles.erase(this);
 }
Exemplo n.º 13
0
void findUniqueWidgetTypes(fstream& stream, WidgetNode *root, set<string> &widgetTypes) {
	if(root->widgetType!="Gui" && root->widgetType!="root")
		widgetTypes.insert(root->widgetType);
	for(size_t i = 0; i < root->children.size(); i++)
		findUniqueWidgetTypes(stream, root->children[i], widgetTypes); 
}
bool
TileMapLayerInfoVector::updateLayers( TileMapLayerInfoVector& clientVector,
                                      const set<int>& existinLayers )
{
   // The clientVector will be the target of this operation.
   // Afterwards the vector is copied.
   int changed = 0;

   // Add changes from the client vector to our settings.
   for( TileMapLayerInfoVector::iterator it = clientVector.begin();
        it != clientVector.end();
        ++it ) {
      TileMapLayerInfo* myInfo = NULL;
      // Find the info from the server.
      for ( TileMapLayerInfoVector::iterator jt = this->begin();
            jt != this->end();
            ++jt ) {
         if ( jt->getID() == it->getID() ) {
            myInfo = &(*jt);
            break;
         }
      }
      changed += it->setPresent( myInfo &&
                ( existinLayers.find( it->getID() ) != existinLayers.end() ) );
      if ( ! myInfo ) {
         continue;
      }
      // These are always correct from the server by definition
      changed += it->setOptional( myInfo->isOptional() );
      changed += it->setAffectedByACPMode( myInfo->isAffectedByACPMode() );
      changed += it->setFetchLayerWhenACPEnabled( myInfo->getFetchLayerWhenACPEnabled() );
      changed += it->setFetchLayerWhenACPDisabled( myInfo->getFetchLayerWhenACPDisabled() );
      
      // Non-optional layers can not be turned off.
      if ( ! it->isOptional() ) {
         changed += it->setVisible( true );
      }
      if ( it->getServerOverrideNumber() !=
           myInfo->getServerOverrideNumber() ) {
         // Force the update into the vector.
         changed +=
            it->setUpdatePeriodMinutes( myInfo->getUpdatePeriodMinutes() );
         changed += it->setVisible( myInfo->isVisible() );
         // But only do it once.
         it->setServerOverrideNumber( myInfo->getServerOverrideNumber() );
      } else {
         // Keep the info that the client entered
      }
   }
   // Add layers to the vector that are not present yet.
   for ( iterator jt = begin();
         jt != end();
         ++jt ) {
      bool found = false;
      for ( iterator it = clientVector.begin();
            it != clientVector.end();
            ++it ) {
         if ( jt->getID() == it->getID() ) {
            found = true;
            break;
         }
      }
      if ( ! found ) {
         // Insert that into the client vector.
         ++changed;
         clientVector.push_back( *jt );
      }
   }

   // This vector will now be the same as the other one.
   *this = clientVector;
   
   return changed;
}
void f(int b) {
    q.clear();
    BORDER = b;
    dfs(0, 0);
}
Exemplo n.º 16
0
	void deleteMyself(set<Shape<int>* >& aSet) 
	{
		aSet.erase(this);
    cout << "Me: " << this->getName() << " is still in here" << endl;
    
	}
Exemplo n.º 17
0
 virtual void visit(SgNode* n) {nodes.insert(n);}
Exemplo n.º 18
0
bool isinL(int x){
	if (L.find(x) != L.end()) return true;
	return false;
}
Exemplo n.º 19
0
int try_to_insert(int s) {
  if(vis.count(s)) return 0;
  vis.insert(s);
  return 1;
}
Exemplo n.º 20
0
void MyObservable::AddObserver(MyObserver& o)
{
	observers.insert(&o);	
}
Exemplo n.º 21
0
shared_ptr<lf::ManagedFormElement> recognize_form_element(xmlpp::Node *node)
{
    xmlpp::Element *el = dynamic_cast<xmlpp::Element *>(node);
    if (!el)
        return nullptr;

    v8::String aName;
    v8::Number aId;

    xmlpp::Attribute *xaName = el->get_attribute("name");
    if (xaName) {
       aName = v8::String(string(xaName->get_value().c_str()));
    }
    xmlpp::Attribute *xaId = el->get_attribute("id");
    if (xaId) {
        aId = v8::Number(patch::stoi(string(xaId->get_value().c_str())));
    }

    string name(el->get_name().c_str());

    if (name == "InputField") {
        return read_new<lf::InputField>(node, aId, aName);
    } else

    if (name == "UsualGroup") {
        return read_new<lf::UsualGroup>(node, aId, aName);
    } else

    if (name == "Table") {
        return read_new<lf::FormTable>(node, aId, aName);
    } else
    if (name == "PictureField") {
        // read input field
    } else

    if (name == "ColumnGroup") {
        return read_new<lf::ColumnGroup>(node, aId, aName);
    } else

    if (name == "Pages") {
        // read input field
    } else

    if (name == "LabelField") {
        return read_new<lf::LabelField>(node, aId, aName);
    } else

    if (name == "CommandBar") {
        // read input field
    } else

    if (name == "PictureDecoration") {
        // read input field
    } else

    if (name == "LabelDecoration") {
        // read input field
    } else

    if (name == "RadioButtonField") {
        // read input field
    } else

    if (name == "Button") {
        // read input field
    } else

    if (name == "CheckBoxField") {
        // read input field
    } else

    if (name == "SpreadSheetDocumentField") {
        // read input field
    } else

    if (name == "TextDocumentField") {
        // read input field
    } else

    if (name == "HTMLDocumentField") {
        // read input field
    } else

    {
        #ifdef DEBUG
            if (unrecognized.find(name) == unrecognized.end()) {
                cout << "Unrecognized form element " << name << endl;
                unrecognized.insert(name);
            }
        #endif
        return nullptr;
    }

    return nullptr;
}
Exemplo n.º 22
0
void MyObservable::RemoveObserver(MyObserver& o)
{	
	observers.erase(&o);
}
Exemplo n.º 23
0
static void GenerateSymFile (set<string> &ParFunc, set<string> &UserFunc, BPatch_image *appImage, BPatch_addressSpace *appProces)
{
	ofstream symfile;
	string symname = string(::XML_GetFinalDirectory())+string("/")+string(::XML_GetTracePrefix())+".sym";

	symfile.open (symname.c_str());
	if (!symfile.good())
	{
		cerr << "Cannot create the symbolic file" << symname << endl;
		return;
	}

	for (set<string>::iterator iter = ParFunc.begin();
		iter != ParFunc.end(); iter++)
	{
		BPatch_function *f = getRoutine ((*iter).c_str(), appImage);

		if (f != NULL)
		{
			BPatch_Vector< BPatch_statement > lines;

			appProces->getSourceLines ((unsigned long) f->getBaseAddr(), lines);
			if (lines.size() > 0)
			{
				symfile << "P " << hex << f->getBaseAddr() << dec << " \"" << *iter
					<< "\" \"" <<  lines[0].fileName() <<  "\" " << lines[0].lineNumber()
					<< endl;
			}
			else
			{
				/* this happens if the application was not compiled with -g */
				char modname[1024];
				f->getModuleName (modname, 1024);
				symfile << "P " << hex << f->getBaseAddr() << dec << " \"" << *iter
					<< "\" \"" << modname << "\" 0" << endl;
			}
		}
	}

	for (set<string>::iterator iter = UserFunc.begin();
		iter != UserFunc.end(); iter++)
	{
		BPatch_function *f = getRoutine ((*iter).c_str(), appImage);

		if (f != NULL)
		{
			BPatch_Vector< BPatch_statement > lines;

			appProces->getSourceLines ((unsigned long) f->getBaseAddr(), lines);
			if (lines.size() > 0)
			{
				symfile << "U " << hex << f->getBaseAddr() << dec << " \"" << *iter
					<< "\" \"" << lines[0].fileName() <<  "\" " << lines[0].lineNumber()
					<< endl;
			}
			else
			{
				/* this happens if the application was not compiled with -g */
				char modname[1024];
				f->getModuleName (modname, 1024);
				symfile << "U " << hex << f->getBaseAddr() << dec << " \"" << *iter
					<< "\" \"" << modname << "\" 0" << endl;
			}
		}
	}

    map<string, unsigned>::iterator BB_symbols_iter = BB_symbols->begin();
    map<string, unsigned>::iterator BB_symbols_end = BB_symbols->end();
    while(BB_symbols_iter != BB_symbols_end){
        symfile << "b " << BB_symbols_iter->second << " \"" << BB_symbols_iter->first << "\"\n";
        BB_symbols_iter++;
    }



	symfile.close();
}
Exemplo n.º 24
0
void Grammar::build_CFSM() {
	set<ConfigurationSet> 	S;
	queue<ConfigurationSet>	Q;
	ConfigurationSet 		s0, sb;
	int 					label = 0;
	ConfigurationSet::State state;
	
	state.dot = 0;
	state.lookahead = vector<string>();
	state.lookahead.push_back(Grammar::lambda);
	for(size_t i = 0; i < rules.size(); i++) {
		if(rules[i].LHS == this->start_symbol) {
			s0.configs.insert(make_pair(rules[i], state));
		}
	}
	s0 = ConfigurationSet::closure0(s0, *this);
	s0.label = label++;
	
	S.insert(s0);
	Q.push(s0);
	
	buildSymbols();
	/* hw need */
	map<int, vector< pair<int, string> > > hwPrint;
	/* hw need */
	while(!Q.empty()) {
		s0 = Q.front(), Q.pop();
		LRstates.push_back(s0);
		for(set<string>::iterator it = symbols.begin();
			it != symbols.end(); it++) {
			sb = ConfigurationSet::go_to0(s0, *it, *this);
			if(sb.configs.size() > 0) {
				if(S.find(sb) == S.end()) {
					sb.label = label++;
					S.insert(sb);
					Q.push(sb);
				}
				
				go_to_table[s0.label][*it] = (* S.find(sb)).label;
				/* hw need */
				hwPrint[(* S.find(sb)).label].push_back(make_pair(s0.label, *it));
			}
		}
	}
	// build_action();
#ifdef DEBUG	
	printf("Total State: %d\n", label);
	for(int i = 0; i < label; i++) {
		if(hwPrint[i].size() > 0) {
			printf("State %d from", i);
			for(vector< pair<int, string> >::iterator it = hwPrint[i].begin();
				it != hwPrint[i].end(); it++) {
				printf("%cState %d(%s)", it == hwPrint[i].begin() ? ' ' : ',', it->first, it->second.c_str());
			}
			puts("");
		} else {
			printf("State %d\n", i);
		}
		LRstates[i].print(*this);
		puts("");
	}
#endif
}
Exemplo n.º 25
0
void AddTimeData(const CNetAddr& ip, int64_t nTime)
{
    int64_t nOffsetSample = nTime - GetTime();

    LOCK(cs_nTimeOffset);
    // Ignore duplicates
    static set<CNetAddr> setKnown;
    if (!setKnown.insert(ip).second)
        return;

    // Add data
    static CMedianFilter<int64_t> vTimeOffsets(200,0);
    vTimeOffsets.input(nOffsetSample);
    LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);

    // There is a known issue here (see issue #4521):
    //
    // - The structure vTimeOffsets contains up to 200 elements, after which
    // any new element added to it will not increase its size, replacing the
    // oldest element.
    //
    // - The condition to update nTimeOffset includes checking whether the
    // number of elements in vTimeOffsets is odd, which will never happen after
    // there are 200 elements.
    //
    // But in this case the 'bug' is protective against some attacks, and may
    // actually explain why we've never seen attacks which manipulate the
    // clock offset.
    //
    // So we should hold off on fixing this and clean it up as part of
    // a timing cleanup that strengthens it in a number of other ways.
    //
    if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
    {
        int64_t nMedian = vTimeOffsets.median();
        std::vector<int64_t> vSorted = vTimeOffsets.sorted();
        // Only let other nodes change our time by so much
        if (abs64(nMedian) < 70 * 60)
        {
            nTimeOffset = nMedian;
        }
        else
        {
            nTimeOffset = 0;

            static bool fDone;
            if (!fDone)
            {
                // If nobody has a time different than ours but within 5 minutes of ours, give a warning
                bool fMatch = false;
                BOOST_FOREACH(int64_t nOffset, vSorted)
                    if (nOffset != 0 && abs64(nOffset) < 5 * 60)
                        fMatch = true;

                if (!fMatch)
                {
                    fDone = true;
                    string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Litedoge will not work properly.");
                    strMiscWarning = strMessage;
                    LogPrintf("*** %s\n", strMessage);
                    uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
                }
            }
        }
Exemplo n.º 26
0
int main() {
	const bool debug = false;
	int i, j, k;
	P bg, nd, t;
	while(~scanf("%d%d%d%d", &x1, &y1, &x2, &y2)) {
		if(x1 == 0 && x2 == 0 && y1 == 0 && y2 == 0)break;
		scanf("%d", &n);

		x.clear();x.insert(x1);x.insert(x2);
		y.clear();y.insert(y1);y.insert(y2);

		for(i = 0; i < n; i++) {
			b[i].init();
			x.insert(b[i].x1);
			x.insert(b[i].x2);
			y.insert(b[i].y1);
			y.insert(b[i].y2);
		}
		hx.clear();
		hy.clear();

		//对x离散化
		for(si = x.begin(), mx = 2; si != x.end(); hx[*si++] = mx, mx+=2) ;

		//对y离散化
		for(si = y.begin(), my = 2; si != y.end(); hy[*si++] = my, my+=2);
		//初始化
		for(j = 0; j < 4; ++j){
			for(i = 0; i < mx; ++i){
				if(!j)fill(m[i], m[i] + my, 0);
				fill(v[j][i], v[j][i] + my, false);
				fill(s[j][i], s[j][i] + my, inf);
			}
		}

		//填充矩阵,填充为1
		for(i = 0; i < n; i++) {
			int xuper = hx[b[i].x2];
			int yuper = hy[b[i].y2];
			//填充上下边界
			for(j = hx[b[i].x1]; j <= xuper; j++){
				m[j][hy[b[i].y1]]=m[j][hy[b[i].y2]]=1;
			}
			//填充左右边界
			for(k = hy[b[i].y1]; k <= yuper; k++){
				m[hx[b[i].x1]][k]=m[hx[b[i].x2]][k]=1;
			}
			//填充矩阵内部
			for(j = hx[b[i].x1] + 1; j < xuper; j++) {
				for(k = hy[b[i].y1] + 1; k < yuper; k++) {
					m[j][k]=2;
				}
			}
		}


		//此路不同,标记为2
		for(i=1;i<mx-1;i++){
			for(j=1;j<my-1;j++){
				if(m[i-1][j]&&m[i][j-1]&&m[i+1][j]&&m[i][j+1])
					m[i][j]=2;
			}
		}

		if(debug) {
			puts("---- stp ----");
			for(i = 0; i < mx; i++) {
				for(j = 0; j < my; j++) {
					printf(" %2d",m[i][j]);
				}
				puts("");
			}
			puts("---- stp ----\n\n");
		}


		while(!que.empty())que.pop();

		nd.x = hx[x2];
		nd.y = hy[y2];

		bg.x = hx[x1];
		bg.y = hy[y1];

		bg.stp = 0;
		//分别标记出发点的四个方向,并入‡队
		for(i = 0; i < 4; i++) {
			bg.d = i;
			v[i][bg.x][bg.y] = true;
			s[i][bg.x][bg.y] = 0;
			que.push(bg);
		}

		int ndnum=0;

		while(!que.empty()) {

			bg = que.top();que.pop();

			//由于是优先搜索,所以只要到达就一定是最优的
			if(bg.x == nd.x && bg.y == nd.y){
				break;
			}

			for(i = 0; i < 4; i++) {

				//回头,不会有更优的答案
				if((i+2)%4 == bg.d)continue;

				t.x = bg.x + pos[i][0];
				t.y = bg.y + pos[i][1];

				//越界
				if(t.x < 0 || t.y < 0 || t.x >= mx || t.y >= my)continue;

				//此路不通
				if(m[t.x][t.y] >1)continue;

				//更新步数
				t.stp = s[bg.d][bg.x][bg.y] + (i == bg.d?0:1);

				//此地点已经达到过,且更优
				if(v[i][t.x][t.y] && t.stp >= s[i][t.x][t.y])continue;




				//此路可以更新
				s[i][t.x][t.y] = t.stp;
				v[i][t.x][t.y] = true;
				t.d = i;

				que.push(t);
			}

		}

		int ans = inf;
		for(i = 0; i < 4; i++) {
			if(ans > s[i][nd.x][nd.y])
				ans = s[i][nd.x][nd.y];
		}
		printf("%d\n", ans==inf?-1:ans);

		if(debug) {
			puts("---- stp ----");
			for(i = 0; i < mx; i++) {
				for(j = 0; j < my; j++) {
					if(m[i][j]){
						printf(" %2d",-m[i][j]);
					}else{
						int tmp=inf;
						for(int kk=0;kk<4;kk++){
							if(tmp>s[kk][i][j]){
								tmp=s[kk][i][j];
							}
						}
						if(tmp==inf)tmp=-3;
						printf(" %2d",tmp);
					}

				}
				puts("");
			}
			puts("---- stp ----\n\n");
		}

	}
	return 0;
}
Exemplo n.º 27
0
 int size() const { 
   return d_data.size();
 };
Exemplo n.º 28
0
	bool queryRange(int left, int right) {
		auto it = rc.lower_bound(make_pair(left, right));
		return it!=rc.end() && it->first <= left && it->second >= right;
	}
Exemplo n.º 29
0
vector<vector<Node*> > PolySolverNAD::GetSortedLocalADComponents(SADNADGraph &graph, set<Node*> guys, set<Node*> otherGuys)
{
    //TODO : I was sick when I wrote the fake node addition thing.  It could probably be a lot better...
    map<Node*, vector<Node*> > localADComps;


    for (set<Node*>::iterator leftIt = guys.begin(); leftIt != guys.end(); leftIt++)
    {
        Node* g = (*leftIt);

        vector<Node*> comp;
        Node* gCompRep = graph.GetADComponentRepresentantOf(g);
        if (localADComps.find(gCompRep) != localADComps.end())
            comp = localADComps[gCompRep];
        comp.push_back(g);

        localADComps[gCompRep] = comp;
    }


    //for those AD-comps with a bridge, we need to add one fake node
    //that might break out ties in the sort and it is important
    for (map<Node*, vector<Node*> >::iterator it = localADComps.begin(); it != localADComps.end(); it++)
    {
        vector<Node*> curComp = (*it).second;
        bool hasBridge = false;

        for (int i = 0; i < curComp.size() && !hasBridge; i++)
        {
            Node* n1 = curComp[i];
            for (set<Node*>::iterator otherIt = otherGuys.begin(); otherIt != otherGuys.end() && !hasBridge; otherIt++)
            {
                Node* n2 = (*otherIt);

                if (graph.HaveSameADComponent(n1, n2))
                    hasBridge = true;
            }
        }

        if (hasBridge)
        {
            Node* nfake = new Node(false);
            //cout<<"BRIDGE ADDED TO CC OF "<<curComp[0]->GetLabel()<<endl;
            nfake->SetLabel("fake");
            curComp.push_back(nfake);
            localADComps[(*it).first] = curComp;
        }
    }


    //sort the local comps by size
    vector<vector<Node*> > v_localADComps;
    for (map<Node*, vector<Node*> >::iterator lit = localADComps.begin(); lit != localADComps.end(); lit++)
    {
        v_localADComps.push_back((*lit).second);
        //cout<<"COMP OF "<<(*lit).second[0]->GetLabel()<<"="<<(*lit).second.size()<<endl;
    }

    std::sort(v_localADComps.begin(), v_localADComps.end(), vector_size_sorter());




    vector<vector<Node*> > v_final_ad_comps;
    //then, delete any fakeass node we added
    for (int i = 0; i < v_localADComps.size(); i++)
    {
        vector<Node*> curComp = v_localADComps[i];

        //cout<<i<<" : "<<curComp[0]->GetLabel()<<" SIZE="<<curComp.size()<<endl;

        Node* last = curComp[curComp.size() - 1];
        if (last->GetLabel() == "fake")
        {
            curComp.pop_back();
            delete last;

            //localADComps[(*it).first] = curComp;
        }
        v_final_ad_comps.push_back(curComp);

    }


    return v_final_ad_comps;
}
Exemplo n.º 30
0
int main() {
    //11:35 - 11:57
	scanf("%d%d%d",&n,&a,&b);
	int t;
    for (int i = 0; i < n; i++){
        scanf("%d", &t);
        h[i] = make_pair(t,2);
        k.insert(t);
    }
        
    for (int i = 0; i < n; i++){
        if(k.find(a-h[i].first)!=k.end()){
            if(k.find(b-(a-h[i].first))!=k.end() && k.find(b-h[i].first)!=k.end()){
                h[i].second=1;
                k.erase(b-h[i].first);
            }else{
                h[i].second=0;  
                k.erase(a-h[i].first);
            } 
        }else if(k.find(b-h[i].first)!=k.end())
            if(k.find(a-(b-h[i].first))!=k.end() && k.find(a-h[i].first)!=k.end()){
                h[i].second=0;
                k.erase(a-h[i].first);
            }else{
                h[i].second=1;
                k.erase(b-h[i].first);
            }
        else{
            cout<<"NO";
            return 0;
        }
    }
    
    printf("YES\n");
    for (int i = 0; i < n; i++)
        printf("%d ", h[i].second);
    
    
    

    return 0;
}