示例#1
0
    bool PolygonElementParser::handlesElement(const NodeType::XMLNode& node) const
    {
        if (!typeIDSetInitialized) {
            std::lock_guard<std::mutex> lock(polygonElementParser_initializedTypeIDMutex);

            if(!typeIDSetInitialized) {
                typeIDSet.insert(NodeType::GML_TriangleNode.typeID());
                typeIDSet.insert(NodeType::GML_RectangleNode.typeID());
                typeIDSet.insert(NodeType::GML_PolygonNode.typeID());
                typeIDSet.insert(NodeType::GML_PolygonPatchNode.typeID());
                typeIDSetInitialized = true;
            }
        }

        return typeIDSet.count(node.typeID()) > 0;
    }
示例#2
0
bool should_rename(DexClass *clazz,
    std::vector<std::string>& pre_patterns,
    std::vector<std::string>& post_patterns,
    std::unordered_set<const DexType*>& untouchables,
    bool rename_annotations) {
  if (!rename_annotations && is_annotation(clazz)) return false;
  if (untouchables.count(clazz->get_type())) return false;
  auto chstring = clazz->get_type()->get_name()->c_str();
  /* We're assuming anonymous classes are safe always safe to rename. */
  auto substr = strrchr(chstring, '$');
  if (substr != nullptr) {
    auto val = *++substr;
    if (val >= '0' && val <= '9') {
      match_inner++;
      return true;
    }
  }
  /* Check for more aggressive, but finer grained filters first */
  for (auto p : pre_patterns) {
    auto substr = strstr(chstring, p.c_str());
    if (substr != nullptr) {
      if (p.length() > 1) {
        match_long++;
      } else {
        match_short++;
      }
      return true;
    }
  }
  if (!can_rename(clazz) && !can_delete(clazz)) {
    return false;
  }
  /* Check for wider, less precise filters */
  for (auto p : post_patterns) {
    auto substr = strstr(chstring, p.c_str());
    if (substr != nullptr) {
      if (p.length() > 1) {
        match_long++;
      } else {
        match_short++;
      }
      return true;
    }
  }
  return false;
}
示例#3
0
void Regex::expandSpontaneous(std::unordered_set<std::size_t>& states) const {
    std::queue<std::size_t> queue;
    for (auto& state : states) {
        queue.push(state);
    }

    while (!queue.empty()) {
        std::size_t state = queue.front();
        queue.pop();
        for (std::size_t index : stateList[state].spontaneous) {
            if (states.count(index) == 0) {
                states.insert(index);
                queue.push(index);
            }
        }
    }
}
示例#4
0
SparseArray3<Body>::Iterator GetBodyAt(Vec3i position) {
	auto it = bodies.begin();
	for(; it != bodies.end(); it++) {
		if(!it->destroyable->alive) {
			if(eatables.count(it.getHandle()))
				eatables.erase(it.getHandle());

			if(pushables.count(it.getHandle()))
				pushables.erase(it.getHandle());

			UnreferenceDestroyable(it->destroyable);
			bodies.remove(it);
			continue;
		}
		if(it->position == position)
			return it;
	}
	return it;
}
示例#5
0
double xrelevance(const MLNetworkSharedPtr& mnet, const ActorSharedPtr& actor, const std::unordered_set<LayerSharedPtr>& layers, edge_mode mode) {
	set<actor_id> neighbors_on_selected_layers;
	set<actor_id> neighbors_on_other_layers;
	set<actor_id> all_neighbors;
	for (NodeSharedPtr node: *mnet->get_nodes(actor)) {
		for (NodeSharedPtr neighbor: *mnet->neighbors(node, mode)) {
			all_neighbors.insert(neighbor->actor->id);
			if (layers.count(neighbor->layer)>0)
				neighbors_on_selected_layers.insert(neighbor->actor->id);
			else neighbors_on_other_layers.insert(neighbor->actor->id);
		}
	}
	if (all_neighbors.size()==0) return 0; // by definition
	else {
		for (actor_id actor: neighbors_on_other_layers)
			neighbors_on_selected_layers.erase(actor);
		return (double)neighbors_on_selected_layers.size()/all_neighbors.size();
	}
}
示例#6
0
bool PhpParam::defValNeedsVariable() const {
  if (defVal.empty() || !isTypeCppIndirectPass(cppType)) {
    return false;
  }

  if (cppType == "HPHP::String const&" && (defVal == "empty_string" ||
                                           defVal == "null_string")) {
    return false;
  } else if (cppType == "HPHP::String const&" &&
             g_knownStringConstants.count(defVal) > 0) {
    return false;
  } else if (cppType == "HPHP::Array const&" && defVal == "null_array") {
    return false;
  } else if (cppType == "HPHP::Object const&" && defVal == "null_object") {
    return false;
  } else if (cppType == "HPHP::Variant const&" && defVal == "null_variant") {
    return false;
  }
  return true;
}
示例#7
0
void Pedigree::addNode(std::unordered_set<OrganismSpecifier>& set, const OrganismSpecifier& newNode) {
	// First check for exact match via hash-collision and equality
	if (set.count(newNode) > 0) return;

	// Now check for equality with something existing
	for (auto& node : set) {
		if (node == newNode) {
			// See if the new node adds some more information and take this into account
			if (node.name().empty() && !newNode.name().empty()) {
				set.erase(node);
				set.insert(newNode);
			}

			return;
		}
	}

	// If nothing found then just insert the new node as given
	set.insert(newNode);
}
        size_t ExpiryTimerImpl::cancelAll(
                const std::unordered_set< std::shared_ptr<TimerTask > >& tasks)
        {
            std::lock_guard< std::mutex > lock{ m_mutex };
            size_t erased { 0 };

            for(auto it = m_tasks.begin(); it != m_tasks.end();)
            {
                if(tasks.count(it->second))
                {
                    it = m_tasks.erase(it);
                    ++erased;
                }
                else
                {
                    ++it;
                }
            }
            return erased;
        }
示例#9
0
void mesh::keep_faces(std::unordered_set<int> & to_keep, aiScene * s) {
    aiMesh * mesh = s->mMeshes[0];

    int num_new = 0;
    aiFace * new_faces = new aiFace[mesh->mNumFaces];

    // For each face in the mesh
    for (int i = 0; i < mesh->mNumFaces; ++i) {
        // If this face is in to_keep keep it
        if (to_keep.count(i) > 0) {
            new_faces[num_new] = mesh->mFaces[i];
            ++num_new;
        }
    }

    delete[] mesh->mFaces;

    mesh->mNumFaces = num_new;
    mesh->mFaces = std::move(new_faces);
}
示例#10
0
// Use DFS to detect a possible loop, most likely an loop in an irreducible
// CFG. One of the headers of the loop is the FirstBB.
// Loop is set to true upon successfully detecting such a loop.
void ExprBuilder::checkIrreducibleCFG(BasicBlock *BB,
                    BasicBlock *FirstBB,
                    std::unordered_set<const BasicBlock *> &VisitedBBs,
                    bool &Loop) {
  VisitedBBs.insert(BB);
  for (succ_iterator PI = succ_begin(BB), E = succ_end(BB);
       PI != E; ++PI) {
    BasicBlock *Succ = *PI;
    if (Succ == FirstBB) {
      Loop = true;
    }
    else if (VisitedBBs.count(Succ)) {
      continue;
    }
    else {
      checkIrreducibleCFG(Succ, FirstBB, VisitedBBs, Loop);
    }
    if (Loop)
      return;
  }
}
示例#11
0
void mod_manager::load_mods_list(WORLDPTR world) const
{
    if (world == NULL) {
        return;
    }
    std::vector<std::string> &amo = world->active_mod_order;
    amo.clear();
    std::ifstream mods_list_file( get_mods_list_file(world).c_str(),
                                  std::ios::in | std::ios::binary );
    if (!mods_list_file) {
        return;
    }
    bool obsolete_mod_found = false;
    try {
        JsonIn jsin(mods_list_file);
        JsonArray ja = jsin.get_array();
        while (ja.has_more()) {
            const std::string mod = ja.next_string();
            if( mod.empty() || std::find(amo.begin(), amo.end(), mod) != amo.end() ) {
                continue;
            }
            if( obsolete_mod_list.count( mod ) ) {
                obsolete_mod_found = true;
                continue;
            }

            amo.push_back(mod);
        }
    } catch (std::string e) {
        DebugLog( D_ERROR, DC_ALL ) << "worldfactory: loading mods list failed: " << e;
    }
    if( obsolete_mod_found ) {
        // If we found an obsolete mod, overwrite the mod list without the obsolete one.
        save_mods_list(world);
    }
}
示例#12
0
/**
 * Add to the list the single called.
 */
void SimpleInlinePass::select_single_called(
    Scope& scope, std::unordered_set<DexMethod*>& methods) {
  std::unordered_map<DexMethod*, int> calls;
  for (const auto& method : methods) {
    calls[method] = 0;
  }
  // count call sites for each method
  walk_opcodes(scope, [](DexMethod* meth) { return true; },
      [&](DexMethod* meth, DexInstruction* insn) {
        if (is_invoke(insn->opcode())) {
          auto mop = static_cast<DexOpcodeMethod*>(insn);
          auto callee = resolve_method(
              mop->get_method(), opcode_to_search(insn), resolved_refs);
          if (callee != nullptr && callee->is_concrete()
              && methods.count(callee) > 0) {
            calls[callee]++;
          }
        }
      });

  // pick methods with a single call site and add to candidates.
  // This vector usage is only because of logging we should remove it
  // once the optimization is "closed"
  std::vector<std::vector<DexMethod*>> calls_group(MAX_COUNT);
  for (auto call_it : calls) {
    if (call_it.second >= MAX_COUNT) {
      calls_group[MAX_COUNT - 1].push_back(call_it.first);
      continue;
    }
    calls_group[call_it.second].push_back(call_it.first);
  }
  assert(method_breakup(calls_group));
  for (auto callee : calls_group[1]) {
    inlinable.insert(callee);
  }
}
int parse_db_arguments(const std::string& db_arg_str, std::string& db_type, int& db_flags)
{
  std::vector<std::string> db_args;
  boost::split(db_args, db_arg_str, boost::is_any_of("#"));
  db_type = db_args.front();
  boost::algorithm::trim(db_type);

  if (db_args.size() == 1)
  {
    return 0;
  }
  else if (db_args.size() > 2)
  {
    std::cerr << "unrecognized database argument format: " << db_arg_str << ENDL;
    return 1;
  }

  std::string db_arg_str2 = db_args[1];
  boost::split(db_args, db_arg_str2, boost::is_any_of(","));

  // optionally use a composite mode instead of individual flags
  const std::unordered_set<std::string> db_modes {"safe", "fast", "fastest"};
  std::string db_mode;
  if (db_args.size() == 1)
  {
    if (db_modes.count(db_args[0]) > 0)
    {
      db_mode = db_args[0];
    }
  }
  if (! db_mode.empty())
  {
    db_flags = get_db_flags_from_mode(db_mode);
  }
  return 0;
}
示例#14
0
文件: gsoc-c.cpp 项目: nebw/gsoc2012
void stepFunction(
    const std::unordered_set<unsigned int>& excitatory_neurons,
    double                               ***state,
    const unsigned int                      ind_old,
    const unsigned int                      ind_new,
    double                                 *state_K1,
    double                                 *state_K2,
    double                                 *state_K3,
    double                                 *state_K4,
    double                                 *state_temp_1,
    double                                 *state_temp_2,
    double                                 *state_temp_3,
    const double   *sumFootprintAMPA,
    const double   *sumFootprintNMDA,
    const double   *sumFootprintGABAA,
    const unsigned int                      numNeurons,
    const unsigned int                      stateSize,
    const double                            dt,
    std::vector<double>                    *spikeTimes_e,
    std::vector<double>                    *spikeNeuronIndices_e,
    std::vector<double>                    *spikeTimes_i,
    std::vector<double>                    *spikeNeuronIndices_i,
    const unsigned int                      firstNeuron,
    const unsigned int                      lastNeuron
    )
{
    for (unsigned int indexOfNeuron = firstNeuron; indexOfNeuron < lastNeuron;
         indexOfNeuron += 1)
    {
        if (excitatory_neurons.count(indexOfNeuron))
        {
            state[ind_new][indexOfNeuron][0] =
                state[ind_old][indexOfNeuron][0] + 1;
        runge_kutta_generic(
          (const double **)state[ind_old],
          state_K1,
          state_K2,
          state_K3,
          state_K4,
          state_temp_1,
          state_temp_2,
          state_temp_3,
          numNeurons,
          stateSize,
          indexOfNeuron,
          1,
          sumFootprintAMPA,
          sumFootprintNMDA,
          sumFootprintGABAA,
          dt,
          (*golomb::f_dV_dt),
          state[ind_new][indexOfNeuron]);
            runge_kutta((*golomb::f_I_Na_dh_dt), 2);
            runge_kutta((*golomb::f_dn_dt), 3);
            runge_kutta((*golomb::f_dz_dt), 4);
            runge_kutta((*golomb::f_dsAMPA_dt), 5);
            runge_kutta((*golomb::f_dxNMDA_dt), 6);
            runge_kutta((*golomb::f_dsNMDA_dt), 7);
            state[ind_new][indexOfNeuron][8] =
                state[ind_old][indexOfNeuron][8];
            state[ind_new][indexOfNeuron][9] =
                state[ind_old][indexOfNeuron][9];

            if (((int)state[ind_new][indexOfNeuron][1]) >= 20)
            {
#ifdef USE_STD_THREADS
                std::lock_guard<std::mutex> lk(m);
#endif // ifdef USE_STD_THREADS
                spikeTimes_e->push_back(
                    (state[ind_new][indexOfNeuron][0]) * dt);
                spikeNeuronIndices_e->push_back(indexOfNeuron);
            }
        } else {
            state[ind_new][indexOfNeuron][0] =
                state[ind_old][indexOfNeuron][0] + 1;
        runge_kutta_generic(
          (const double **)state[ind_old],
          state_K1,
          state_K2,
          state_K3,
          state_K4,
          state_temp_1,
          state_temp_2,
          state_temp_3,
          numNeurons,
          stateSize,
          indexOfNeuron,
          1,
          sumFootprintAMPA,
          sumFootprintNMDA,
          sumFootprintGABAA,
          dt,
          (*wang_buzsaki::f_dV_dt),
          state[ind_new][indexOfNeuron]);
            runge_kutta((*wang_buzsaki::f_I_Na_dh_dt), 2);
            runge_kutta((*wang_buzsaki::f_I_Kdr_dn_dt), 3);
            state[ind_new][indexOfNeuron][4] =
                state[ind_old][indexOfNeuron][4];
            state[ind_new][indexOfNeuron][5] =
                state[ind_old][indexOfNeuron][5];
            state[ind_new][indexOfNeuron][6] =
                state[ind_old][indexOfNeuron][6];
            state[ind_new][indexOfNeuron][7] =
                state[ind_old][indexOfNeuron][7];
            runge_kutta((*wang_buzsaki::f_dsGABAA_dt), 8);
            state[ind_new][indexOfNeuron][9] =
                state[ind_old][indexOfNeuron][9];

            if (((int)state[ind_new][indexOfNeuron][1]) >= 20)
            {
#ifdef USE_STD_THREADS
                std::lock_guard<std::mutex> lk(m);
#endif // ifdef USE_STD_THREADS
                spikeTimes_i->push_back(
                    (state[ind_new][indexOfNeuron][0]) * dt);
                spikeNeuronIndices_i->push_back(indexOfNeuron);
            }
        }
    }
}
示例#15
0
static bool allow_ext_entity_protocol(const String& protocol) {
  return s_ext_entity_whitelist.count(protocol.get());
}
示例#16
0
 char getOps(std::string const& s, int& pos) {
     pos = s.find_first_not_of(" ", pos); // skip all spaces
     if (pos == std::string::npos) { return NON_OP; }
     auto res = s.at(pos++);
     return validOps.count(res) ? res : NON_OP;
 }
示例#17
0
inline bool EndgameModule::drawnEndgame(HashKey materialHashKey) const
{
    return mFideDrawnEndgames.count(materialHashKey) > 0 || mOtherDrawnEndgames.count(materialHashKey) > 0;
}
示例#18
0
bool KeyboardDevice::writeText(const QString &text, int delay, bool noUnicodeCharacters) const
{
#ifdef Q_OS_UNIX
	bool result = true;
	KeySym keySym[2];
	std::wstring wideString = text.toStdWString();
	wchar_t wcSinglecharStr[2] = {L'\0'};

	for(unsigned int i = 0; wideString[i] != L'\0' && i < wideString.size(); ++i)
	{
		wcSinglecharStr[0] = wideString[i];

		//KeySym lookup
		keySym[0] = ActionTools::KeySymHelper::wcharToKeySym(wcSinglecharStr[0]);
		keySym[1] = 0;

		if(keySym[0] == 0 || ActionTools::KeySymHelper::keySymToKeyCode(keySym[0]) == 0)
		{
			//No keycode found -> try to find a Multi_key combination for this character
			keySym[0] = 0;

			for(int j = 0; j < ActionTools::KeySymHelper::MULTIKEY_MAP_SIZE; ++j)
			{
				if(wcSinglecharStr[0] == ActionTools::KeySymHelper::multikeyMapChar[j])//Found
				{
					keySym[0] = ActionTools::KeySymHelper::wcharToKeySym(ActionTools::KeySymHelper::multikeyMapFirst[j]);
					keySym[1] = ActionTools::KeySymHelper::wcharToKeySym(ActionTools::KeySymHelper::multikeyMapSecond[j]);
					if((ActionTools::KeySymHelper::keySymToKeyCode(keySym[0]) == 0)
						|| (ActionTools::KeySymHelper::keySymToKeyCode(keySym[1]) == 0))
						keySym[0] = 0;//Character not supported

					break;
				}
			}
		}

		if(keySym[0])
		{
			if(keySym[1])//Multi key sequence
			{
				result &= sendKey("Multi_key");
				result &= sendCharacter(keySym[0]);
				result &= sendCharacter(keySym[1]);
			}
			else//Single key
				result &= sendCharacter(keySym[0]);
		}

		if(delay > 0)
			ActionTools::CrossPlatform::sleep(delay);
	}

	return result;
#endif
	
#ifdef Q_OS_WIN
    std::array<INPUT, 2> input;
    SecureZeroMemory(input.data(), input.size() * sizeof(INPUT));
	bool result = true;

	for(int i = 0; i < 2; ++i)
	{
		input[i].type = INPUT_KEYBOARD;
		input[i].ki.wVk = 0;
        if(noUnicodeCharacters)
            input[i].ki.dwFlags = KEYEVENTF_SCANCODE | (i == 0 ? 0 : KEYEVENTF_KEYUP);
        else
            input[i].ki.dwFlags = KEYEVENTF_UNICODE | (i == 0 ? 0 : KEYEVENTF_KEYUP);
		input[i].ki.time = 0;
        input[i].ki.dwExtraInfo = 0;
    }

    HKL keyboardLayout = GetKeyboardLayout(0);

    auto sendModifiersFunction = [&keyboardLayout](int key, int additionalFlags)
    {
        INPUT modifierInput;
        SecureZeroMemory(&modifierInput, sizeof(INPUT));

        modifierInput.type = INPUT_KEYBOARD;
        modifierInput.ki.dwFlags = KEYEVENTF_SCANCODE | additionalFlags;
        modifierInput.ki.wScan = MapVirtualKeyEx(key, MAPVK_VK_TO_VSC, keyboardLayout);

        if(extendedKeys.count(key) > 0)
            modifierInput.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;

        SendInput(1, &modifierInput, sizeof(INPUT));
    };

	for(int i = 0; i < text.length(); ++i)
	{
        SHORT virtualKey = 0;

        if(noUnicodeCharacters)
        {
            virtualKey = VkKeyScanEx(text[i].unicode(), keyboardLayout);
            auto scanCode = MapVirtualKeyEx(LOBYTE(virtualKey), MAPVK_VK_TO_VSC, keyboardLayout);

            if(extendedKeys.count(virtualKey) > 0)
            {
                input[0].ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
                input[1].ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
            }

            if(HIBYTE(virtualKey) & 1) //Shift
                sendModifiersFunction(VK_LSHIFT, 0);

            if(HIBYTE(virtualKey) & 2) //Control
                sendModifiersFunction(VK_LCONTROL, 0);

            if(HIBYTE(virtualKey) & 4) //Alt
                sendModifiersFunction(VK_LMENU, 0);

            input[0].ki.wVk = input[1].ki.wVk = virtualKey;
            input[0].ki.wScan = input[1].ki.wScan = scanCode;
        }
        else
        {
            input[0].ki.wScan = input[1].ki.wScan = text[i].unicode();
        }

        result &= (SendInput(2, input.data(), sizeof(INPUT)) != 0);

        if(noUnicodeCharacters)
        {
            if(HIBYTE(virtualKey) & 4) //Alt
                sendModifiersFunction(VK_LMENU, KEYEVENTF_KEYUP);

            if(HIBYTE(virtualKey) & 2) //Control
                sendModifiersFunction(VK_LCONTROL, KEYEVENTF_KEYUP);

            if(HIBYTE(virtualKey) & 1) //Shift
                sendModifiersFunction(VK_LSHIFT, KEYEVENTF_KEYUP);
        }

		if(delay > 0)
			ActionTools::CrossPlatform::sleep(delay);
	}

	return result;
#endif
}
示例#19
0
bool is_kept_member(DexField* sfield,
                    const std::unordered_set<DexField*>& keep_members) {
  return keep_members.count(sfield);
}
示例#20
0
bool isBroadcasting(Node *node) {
  return broadcasting.count(node->kind());
}
示例#21
0
 void insert(const K& newk) {
   if (keys_to_insert.count(newk) == 0) {
     keys_to_insert.insert(newk);
   }
 }
示例#22
0
 bool isProtected(T* product)
 {
     std::lock_guard<std::mutex> lock(m_mutex);
     return m_protected.count(product) == 1;
 }
示例#23
0
文件: data.cpp 项目: zeil/Synca
StrPair loadContent(const StrPair& url)
{
    const int MAX_BUF_SIZE = 1024*1000;
    const int READ_BUF_SIZE = 1024*16;

    auto&& host = url.first;
    auto&& path = url.second;
    JLOG("loading url: " << host << ", " << path);
    Resolver r;
    Resolver::EndPoints ends = r.resolve(host, 80);
    VERIFY(ends != Resolver::EndPoints(), "Cannot resolve hostname: " + host);
    Socket s;
    s.connect(*ends);
    Str req =
        "GET " + path + " HTTP/1.1" EOL
        "Host: " + host + EOL EOL;
    s.write(req);
    Str resp;
    Str buf;
    size_t header = std::string::npos;
    while (header == std::string::npos)
    {
        VERIFY(resp.size() < MAX_BUF_SIZE, "Header is too large");
        buf.resize(READ_BUF_SIZE);
        s.partialRead(buf);
        VERIFY(!buf.empty(), "Empty buffer on partial read");
        resp += buf;
        header = resp.find(EOL EOL);
    }
    Str head = resp.substr(0, header);
    header += 4; // add 2 EOLs
    static const regex eStatus("^http/1\\.[01] ([\\d]{3})", regex::icase);
    smatch whatStatus;
    bool result = regex_search(head, whatStatus, eStatus);
    VERIFY(result, "Invalid http status header");
    Str status = whatStatus[1];
    static const std::unordered_set<Str> allowedStatuses = {"200", "301", "302", "303"};
    VERIFY(allowedStatuses.count(status), "Unexpected status: " + status);
    static const regex e("content-length: *(\\d+)", regex::icase);
    smatch what;
    result = regex_search(head, what, e);
    if (result)
    {
        int len = std::atoi(Str(what[1]).c_str());
        VERIFY(len > 0 && len < MAX_BUF_SIZE, "Content length: invalid value");
        buf.resize(len - (resp.size() - header));
        s.read(buf);
        resp += buf;
    }
    else
    {
        static const regex et("transfer-encoding: *chunked", regex::icase);
        // read chunks
        result = regex_search(head, et);
        VERIFY(result, "Either content-length or transfer-encoding must be present in header");
        while (resp.find(EOL EOL, resp.size() - 4) == std::string::npos)
        {
            VERIFY(resp.size() < MAX_BUF_SIZE, "Response is too large");
            buf.resize(READ_BUF_SIZE);
            s.partialRead(buf);
            VERIFY(!buf.empty(), "Empty buffer on partial read");
            resp += buf;
        }
    }
    Str body = resp.substr(header);
    return {host, body};
}
示例#24
0
bool isNonheapRoot(void* p) {
    if (p > max_nonheap_root || p < min_nonheap_root)
        return false;
    return nonheap_roots.count(p) != 0;
}
示例#25
0
 bool isPendingDelete(T* product)
 {
     std::lock_guard<std::mutex> lock(m_mutex);
     return m_pendingDelete.count(product) == 1;
 }
示例#26
0
 bool isUgly2(int n){
     return n == 1 ||
             (n%2 == 0 && _uglyNumber.count(n/2)) ||
             (n%3 == 0 && _uglyNumber.count(n/3)) ||
             (n%5 == 0 && _uglyNumber.count(n/5));
 }
示例#27
0
文件: goals.cpp 项目: uicus/sbg2gdl
std::pair<uint, std::pair<goals, goals>> parse_goals(
    parser& p,
    std::vector<warning>& warnings_list,
    const std::unordered_set<char>& declared_pieces,
    const board& declared_board)throw(goals_parse_error,parse_error){
    uint turns_limit;
    goals uppercase_player_goals;
    goals lowercase_player_goals;
    if(!p.expect_string("<GOALS>"))
        throw parse_error(p.get_line_number(), p.get_char_in_line_number(), "Goals segment must begin with \'<GOALS>\' string");
    p.expect_whitespace();
    parser_result<int> turns_limit_result = p.expect_int();
    if(!turns_limit_result)
        throw goals_parse_error(turns_limit_result.info.line_number, turns_limit_result.info.char_number, turns_limit_result.info.human_readable_info.c_str());
    if(turns_limit_result.result < 1)
        throw goals_parse_error(p.get_line_number(), p.get_char_in_line_number(), "Turns limit must be positive");
    turns_limit = turns_limit_result.result;
    p.expect_whitespace();
    if(p.expect_plain_char()!='&')
        throw goals_parse_error(p.get_line_number(), p.get_char_in_line_number(), "Turns limit must be terminated with \'&\'");
    p.expect_whitespace();
    char next_char = p.expect_plain_char();
    bool ignore;
    while(next_char == '@' || next_char == '#'){
        ignore = false;
        if(next_char == '@'){
            next_char = p.expect_plain_char();
            bool uppercase_player;
            if(isupper(next_char))
                uppercase_player = true;
            else if(islower(next_char)){
                uppercase_player = false;
                next_char = toupper(next_char);
            }
            else
                throw goals_parse_error(p.get_line_number(), p.get_char_in_line_number(), "Expected letter after \'@\'");
            if(!declared_pieces.count(next_char)){
                ignore = true;
                warnings_list.push_back(warning(p.get_line_number(), p.get_char_in_line_number(), "Undeclared piece (piece doesn't appear in the previous board declaration)"));
            }
            char piece_symbol = next_char;
            do{
                p.expect_whitespace();
                parser_result<int> x_result = p.expect_int();
                if(!x_result)
                    throw goals_parse_error(x_result.info.line_number, x_result.info.char_number, x_result.info.human_readable_info.c_str());
                if(x_result.result < 0)
                    throw goals_parse_error(p.get_line_number(), p.get_char_in_line_number(), "x coordinate must be non-negative");
                if(!p.expect_whitespace())
                    throw goals_parse_error(p.get_line_number(), p.get_char_in_line_number(), "Expected whitespace after x coordinate");
                parser_result<int> y_result = p.expect_int();
                if(!y_result)
                    throw goals_parse_error(y_result.info.line_number, y_result.info.char_number, y_result.info.human_readable_info.c_str());
                if(y_result.result < 0)
                    throw goals_parse_error(p.get_line_number(), p.get_char_in_line_number(), "y coordinate must be non-negative");
                if(!declared_board.inside(x_result.result, y_result.result)){
                    ignore = true;
                    warnings_list.push_back(warning(p.get_line_number(), p.get_char_in_line_number(), "Given point is outside the board"));
                }
                if(!ignore){
                    if(uppercase_player)
                        uppercase_player_goals.add_piece_placement_goal(piece_symbol, x_result.result, y_result.result);
                    else
                        lowercase_player_goals.add_piece_placement_goal(piece_symbol, x_result.result, y_result.result);
                }
                p.expect_whitespace();
                next_char = p.expect_plain_char();
                if(next_char != ',' && next_char != '&')
                    throw goals_parse_error(p.get_line_number(), p.get_char_in_line_number(), "Expected \',\' or \'&\'");
            }while(next_char != '&');
        }
        else{
            next_char = p.expect_plain_char();
            bool uppercase_player;
            if(isupper(next_char))
                uppercase_player = false;
            else if(islower(next_char)){
                uppercase_player = true;
                next_char = toupper(next_char);
            }
            else
                throw goals_parse_error(p.get_line_number(), p.get_char_in_line_number(), "Expected letter after \'#\'");
            if(!declared_pieces.count(next_char)){
                ignore = true;
                warnings_list.push_back(warning(p.get_line_number(), p.get_char_in_line_number(), "Undeclared piece (piece doesn't appear in the previous board declaration)"));
            }
            p.expect_whitespace();
            parser_result<int> number_of_pieces_result = p.expect_int();
            if(!number_of_pieces_result)
                throw goals_parse_error(number_of_pieces_result.info.line_number, number_of_pieces_result.info.char_number, number_of_pieces_result.info.human_readable_info.c_str());
            if(number_of_pieces_result.result < 0)
                throw goals_parse_error(p.get_line_number(), p.get_char_in_line_number(), "Number of piece captures must be non negative");
            if(!ignore){
                if(uppercase_player)
                    uppercase_player_goals.add_piece_capture_goal(next_char, number_of_pieces_result.result);
                else
                    lowercase_player_goals.add_piece_capture_goal(next_char, number_of_pieces_result.result);
            }
            p.expect_whitespace();
            if(p.expect_plain_char()!='&')
                throw goals_parse_error(p.get_line_number(), p.get_char_in_line_number(), "Capture goal must be terminated with \'&\'");
        }
        p.expect_whitespace();
        next_char = p.expect_plain_char();
    }
    return std::make_pair(turns_limit, std::make_pair(std::move(uppercase_player_goals), std::move(lowercase_player_goals)));
}
示例#28
0
 bool
 enabled (uint256 const& feature) const
 {
     return set_.count(feature) > 0;
 }
示例#29
0
// Given a Python tuple of raw output tensors (raw_output), set each of
// the corresponding entries in a different Python tuple (outputs) with
// these tensors wrapped with variables.  We save the gradient function (self)
// to the variable if the output is not volatile (is_volatile).
//
// There is a considerable amount of complexity to handle if the operation
// that produced these output tensors is inplace.  A mapping of *input*
// tensors to variables (t2var) is used to test if this occurred, and
// the set of dirty tensors (dirty_inputs) is used to figure out what to
// do in this case.  After this method is run, t2var is extended with
// mappings for output tensors as well.
static void _wrap_outputs(THPFunction *self, t2var_type &t2var,
    std::unordered_set<PyObject *> &dirty_inputs,
    const t2var_type &shared_pairs,
    PyObject *raw_output, PyObject *outputs, bool is_volatile)
{
  bool is_executable = self->cdata.is_executable;
  TORCH_ASSERT(!is_volatile || !is_executable);
  auto cdata = is_executable ? THPFunction_asFunction(self) : nullptr;
  auto flags = VarFlags(is_executable, is_volatile);
  Py_ssize_t num_outputs = PyTuple_GET_SIZE(raw_output);
  if (self->cdata.is_executable) {
    self->output_info.clear();
    self->output_info.reserve(num_outputs);
  }

  // Given an output tensor, find the input Variable with which it shares storage
  auto get_shared_base = [&](PyObject* tensor) -> Variable {
    auto input_it = t2var.find(tensor);
    if (input_it != t2var.end()) {
      // If the output is an input treat that as the base
      return input_it->second->cdata;
    }
    auto it = shared_pairs.find(tensor);
    if (it != shared_pairs.end()) {
      // It's explicitly marked as shared via mark_shared_storage
      return it->second->cdata;
    }
    return Variable();
  };

  // Wraps an output Tensor in a Variable or returns the previous wrapper in
  // the case of in-place modification.
  auto wrap_output = [&](at::Tensor data, Variable prev, int output_nr, bool is_modified) -> Variable {
    if (!prev.defined()) {
      return make_variable(std::move(data), flags, output_nr, cdata);
    }
    if (is_modified) {
      if (prev.is_leaf() && prev.requires_grad()) {
        throw std::runtime_error("a leaf Variable that requires grad has been used in an in-place operation.");
      }
      // If the input was modified, transplant the grad_fn in the graph:
      // grad_fn <- variable <- self  ==>  grad_fn <- self <- variable
      prev.get()->grad.reset();
      prev.get()->hooks.clear();
      if (auto grad_acc_fn = prev.get()->grad_accumulator.lock()) {
        auto grad_acc = dynamic_cast<AccumulateGrad*>(grad_acc_fn.get());
        grad_acc->variable.reset();
      }
      prev.rebase_history(flags, output_nr, cdata);
      return prev;
    }
    // An input has been returned, but it wasn't modified. Return it as a view
    // so that we can attach a new grad_fn to the Variable.
    return make_variable_view(std::move(prev), std::move(data), flags, output_nr, cdata);
  };

  t2var_type output2var;
  for (int i = 0; i < num_outputs; i++) {
    PyObject *output = PyTuple_GET_ITEM(raw_output, i);

    THPVariable* output_var;
    auto it = output2var.find(output);
    if (it != output2var.end()) {
      output_var = it->second;
      Py_INCREF(output_var);
    } else {
      // Wrap the output in a Variable
      bool is_modified = dirty_inputs.count(output) > 0;
      Variable var = wrap_output(
          torch::createTensor(output),
          get_shared_base(output),
          i,
          is_modified);

      output_var = (THPVariable*)THPVariable_Wrap(var);
      if (!output_var) throw python_error();

      // We already have the data tensor wrapped as a PyObject*
      Py_INCREF(output);
      Py_CLEAR(output_var->data);
      output_var->data = output;

      output2var[output] = output_var;
    }

    if (self->cdata.is_executable) {
      self->output_info.emplace_back(output_var->cdata);
    }
    PyTuple_SET_ITEM(outputs, i, (PyObject*)output_var);
  }

  // Add every entry in output2var to t2var
  for (auto& entry : output2var) {
    t2var[entry.first] = entry.second;
  }
}
示例#30
0
bool S4Prover::isSatisfiable(SddNode* alpha, SddManager* m, std::unordered_set<SddLiteral> permVars, SddNode* permSdd,
                                std::unordered_set<SddNode*,SddHasher>& assumedSatSdds , std::unordered_set<SddLiteral>& responsibleVars) {
    
    //Match against cache
    if (satCache.count(alpha) == 1) {
        return true;
    }
    
    //Base cases
    if (sdd_node_is_true(alpha)) {
        return true;
    }
    
    if (sdd_node_is_false(alpha)) {
        return false;
    }
    
    //Scrape off a single satisfying set, corresponding to a single open tableaux branch.
    std::vector<SddLiteral> branch = getOpenBranch(alpha, std::vector<SddLiteral>());
    SddNode* branchSdd = branchToSDD(branch,m);
    sdd_ref(branchSdd,m);

    /*std::cout << "BRANCH\n\n";
    for (SddLiteral i : branch) {
        if (i < 0) std::cout << "~" << *literalsToAtoms[-i] << "\n\n";
        else std::cout << *literalsToAtoms[i] << "\n\n";
    }
    std::cout << "BRANCH END\n\n";*/
    
    //Extract all modal atoms from the branch.
    std::vector<SddLiteral> boxes;
    std::vector<SddLiteral> negBoxes;
    if (extractModals(branch,boxes,negBoxes) == 0) {
        return true;
    };

    //Checks for new boxed variables
    SddNode* tmp;
    std::unordered_set<SddLiteral> newPermVars = permVars;
    std::vector<SddLiteral> unboxed;
    SddNode* postUnboxingBranch = sdd_conjoin(sdd_manager_true(m),branchSdd,m);
    sdd_ref(postUnboxingBranch,m);
    SddNode* newPermSdd = sdd_conjoin(sdd_manager_true(m),permSdd,m);
    sdd_ref(newPermSdd,m);
    for (SddLiteral i : boxes) {
        if (newPermVars.count(i) == 0) {
            unboxed.push_back(i);
            newPermVars.insert(i);
            postUnboxingBranch = sdd_conjoin(tmp = postUnboxingBranch, compiler::KtoSDD(&literalsToAtoms[i]->getleft(),m),m);
            sdd_deref(tmp,m); sdd_ref(postUnboxingBranch,m);
            newPermSdd = sdd_conjoin(tmp = newPermSdd, compiler::KtoSDD(&literalsToAtoms[i]->getleft(),m),m);
            sdd_deref(tmp,m); sdd_ref(newPermSdd,m);
            newPermSdd = sdd_conjoin(tmp = newPermSdd, compiler::KtoSDD(literalsToAtoms[i],m),m);
            sdd_deref(tmp,m); sdd_ref(newPermSdd,m);
            //If becomes false while unboxing, recurse.
            if (sdd_node_is_false(postUnboxingBranch)) {

                //Determine minimal set of unboxed variables
                std::vector<SddLiteral> minLits;
                minLits.push_back(i);
                responsibleVars.insert(i);
                std::vector<SddLiteral>::iterator endIt = --(unboxed.end());
                SddNode* minimalSdd = sdd_conjoin(compiler::KtoSDD(&literalsToAtoms[i]->getleft(),m),branchSdd,m);
                sdd_ref(minimalSdd,m);
                SddNode* minBoxVarsSdd = sdd_conjoin(compiler::KtoSDD(&literalsToAtoms[i]->getleft(),m),sdd_manager_true(m),m);
                sdd_ref(minBoxVarsSdd,m);                       
                while (true) {
                    sdd_deref(postUnboxingBranch,m);
                    postUnboxingBranch = sdd_conjoin(minimalSdd, sdd_manager_true(m), m);
                    sdd_ref(postUnboxingBranch,m);
                    if (sdd_node_is_false(postUnboxingBranch)) break; //Last one added made it false
                    for (std::vector<SddLiteral>::iterator v = unboxed.begin();
							v != endIt; ++v) {
                        postUnboxingBranch = sdd_conjoin(tmp = postUnboxingBranch, compiler::KtoSDD(&literalsToAtoms[*v]->getleft(),m),m);
                        sdd_deref(tmp,m); sdd_ref(postUnboxingBranch,m);
						if (sdd_node_is_false(postUnboxingBranch)) {
							//Last one added made it false
							minimalSdd = sdd_conjoin(tmp = minimalSdd, compiler::KtoSDD(&literalsToAtoms[*v]->getleft(),m),m);
                            sdd_deref(tmp,m); sdd_ref(minimalSdd,m);
                            minBoxVarsSdd = sdd_conjoin(tmp = minBoxVarsSdd,compiler::KtoSDD(&literalsToAtoms[*v]->getleft(),m),m);
                            sdd_deref(tmp,m); sdd_ref(minBoxVarsSdd,m);
                            minLits.push_back(*v);
                            responsibleVars.insert(*v);
							endIt = v;
							break;
						}
					}
                }
                // Determine minimal set of branch variables together with unboxed variables
                std::vector<SddLiteral>::iterator BendIt = branch.end();
                sdd_deref(minimalSdd,m);
                minimalSdd = sdd_conjoin(sdd_manager_true(m),minBoxVarsSdd,m);
                sdd_ref(minimalSdd,m);
				while (true) {
                    sdd_deref(minBoxVarsSdd,m);
					minBoxVarsSdd = sdd_conjoin(minimalSdd, sdd_manager_true(m), m);
                    sdd_ref(minBoxVarsSdd,m);
                    if (sdd_node_is_false(minBoxVarsSdd)) break; //Last one added made it false
					for (std::vector<SddLiteral>::iterator v = branch.begin();
						v != BendIt; ++v) {
                        minBoxVarsSdd = sdd_conjoin(tmp = minBoxVarsSdd, sdd_manager_literal(*v,m), m);
                        sdd_deref(tmp,m); sdd_ref(minBoxVarsSdd,m);
                        if (sdd_node_is_false(minBoxVarsSdd)) {
    						//Last one added made it false
                            minimalSdd = sdd_conjoin(tmp = minimalSdd, sdd_manager_literal(*v,m),m);
                            sdd_deref(tmp,m); sdd_ref(minimalSdd,m);
							minLits.push_back(*v);
                            responsibleVars.insert(*v);
                            BendIt = v;
							break;
						}
					}
				}
                sdd_deref(minimalSdd,m); sdd_deref(postUnboxingBranch,m); sdd_deref(minBoxVarsSdd,m);
                
                //std::cout << *literalsToAtoms[minLits[0]] << " and " << *literalsToAtoms[minLits[1]] << "\n";
                SddNode* beta = refineSdd(minLits, alpha, m);
                sdd_ref(beta,m);
                dependentSdds.insert(alpha);
                bool isSat = isSatisfiableRefined(beta, m, permVars, permSdd, assumedSatSdds, responsibleVars);
                dependentSdds.erase(alpha);
                sdd_deref(beta,m); sdd_deref(branchSdd,m); sdd_deref(newPermSdd,m);
                return isSat;
            }
        }
    }
    // There were new boxes, so recurse.
    if (!unboxed.empty()) {
        dependentSdds.insert(alpha);
        std::unordered_set<SddLiteral> postResponsibleVars;
        if (!isSatisfiable(postUnboxingBranch,m,newPermVars,newPermSdd,assumedSatSdds, postResponsibleVars)) {
            std::vector<SddLiteral> minLits;
            for (SddLiteral v : branch) {
                if (postResponsibleVars.count(v) == 1) {
                    minLits.push_back(v);
                    responsibleVars.insert(v);
                }
            }
			for (SddLiteral v : unboxed) {
				std::unordered_set<SddLiteral> children;
				KFormula::computeChildrenBoxS4(&literalsToAtoms[v]->getleft(), children);
				if (shareAnElement(postResponsibleVars, children)) {
                    minLits.push_back(v);
                    responsibleVars.insert(v);
				}
			}
               SddNode* beta = refineSdd(minLits, alpha, m);
               sdd_ref(beta,m);
               bool isSat = isSatisfiableRefined(beta, m, permVars, permSdd, assumedSatSdds, responsibleVars);
               sdd_deref(beta,m); sdd_deref(branchSdd,m); sdd_deref(newPermSdd,m); sdd_deref(postUnboxingBranch,m);
               dependentSdds.erase(alpha);
               return isSat;
        }
        sdd_deref(branchSdd,m); sdd_deref(newPermSdd,m);
        dependentSdds.erase(alpha);
        return true;
    }
    
    // There are no new boxes, so start undiamonding.
    sdd_deref(branchSdd,m);
    if (negBoxes.empty()) {
		return true;
	}
	dependentSdds.insert(alpha);
	SddNode* nextWorld;
    for (SddLiteral i : negBoxes) {
        nextWorld = sdd_conjoin(permSdd, sdd_negate(compiler::KtoSDD(&literalsToAtoms[-i]->getleft(),m),m),m);
        sdd_ref(nextWorld,m);        
        
        if (sdd_node_is_false(nextWorld)) {
            
            sdd_deref(nextWorld,m);
            nextWorld = sdd_conjoin(sdd_manager_true(m), sdd_negate(compiler::KtoSDD(&literalsToAtoms[-i]->getleft(),m),m),m);
            sdd_ref(nextWorld,m);
			responsibleVars.insert(i);
			std::vector<SddLiteral> minLits;
            minLits.push_back(i);
			
			// Determine a minimal unsatisfiable subset.
			std::unordered_set<SddLiteral>::iterator endIt = permVars.end();
            SddNode* minimalSdd = sdd_conjoin(nextWorld, sdd_manager_true(m),m);
            sdd_ref(minimalSdd,m);
			while (true) {
                sdd_deref(nextWorld,m);
                nextWorld = sdd_conjoin(minimalSdd, sdd_manager_true(m), m);
                sdd_ref(nextWorld,m);
				if (sdd_node_is_false(nextWorld)) break;
				for (std::unordered_set<SddLiteral>::iterator v = permVars.begin();
							v != endIt; ++v) {
                    nextWorld = sdd_conjoin(tmp = nextWorld,compiler::KtoSDD(&literalsToAtoms[*v]->getleft(),m) ,m);
                    sdd_deref(tmp, m); sdd_ref(nextWorld,m);
                    nextWorld = sdd_conjoin(tmp = nextWorld,sdd_manager_literal(*v,m) ,m);
                    sdd_deref(tmp, m); sdd_ref(nextWorld,m);
					if (sdd_node_is_false(nextWorld)) {
                        minimalSdd = sdd_conjoin(tmp = minimalSdd,compiler::KtoSDD(&literalsToAtoms[*v]->getleft(),m) ,m);
                        sdd_deref(tmp, m); sdd_ref(minimalSdd,m);
                        minimalSdd = sdd_conjoin(tmp = minimalSdd,sdd_manager_literal(*v,m) ,m);
                        sdd_deref(tmp, m); sdd_ref(minimalSdd,m);
						minLits.push_back(*v);
						responsibleVars.insert(*v);
                        endIt = v;
						break;
					}
				}
			} 
			SddNode* beta = refineSdd(minLits, alpha, m);
            sdd_ref(beta,m);
            bool isSat = isSatisfiableRefined(beta, m, permVars, permSdd, assumedSatSdds, responsibleVars);
            sdd_deref(beta,m); sdd_deref(nextWorld,m); sdd_deref(minimalSdd,m);
            dependentSdds.erase(alpha);
            return isSat;	  
        }
        if (dependentSdds.count(nextWorld) == 1) {
            //Loop detected
            assumedSatSdds.insert(nextWorld);
            continue;
        }
        std::unordered_set<SddNode*,SddHasher> postModalAssumedSatSdds = assumedSatSdds;
        std::unordered_set<SddLiteral> postResponsibleVars;
        if (!isSatisfiable(nextWorld,m,permVars,permSdd,postModalAssumedSatSdds, postResponsibleVars)) {
            
            std::vector<SddLiteral> minLits;

			bool newPostModalJumpResVarsAdded = true;
			while (newPostModalJumpResVarsAdded) {
				newPostModalJumpResVarsAdded = false;
				for (std::unordered_set<SddLiteral>::iterator v = permVars.begin();
						v != permVars.end(); ++v) {
					if (responsibleVars.count(*v) != 0) {
						continue;
					}
					std::unordered_set<SddLiteral> children = getChildren(*v);
					children.insert(*v);
					if (shareAnElement(postResponsibleVars, children)) {
                        minLits.push_back(*v);
						responsibleVars.insert(*v);
						// Add in other children to postModalJumpResVars
						postResponsibleVars.insert(children.begin(),
													children.end());
						newPostModalJumpResVarsAdded = true;
					}
				}
				if (responsibleVars.count(i) != 0) {
					// Don't bother, we've already accounted for this dia var.
				} else if (shareAnElement(postResponsibleVars, getChildren(i))) {
					// Note, <>phi stored as []~phi, thus the nith.
					minLits.push_back(i);
					responsibleVars.insert(i);
					// Add in other children to postModalJumpResVars
					postResponsibleVars.insert(getChildren(i).begin(),
												getChildren(i).end());
					newPostModalJumpResVarsAdded = true;
				}
			}
	
            SddNode* beta = refineSdd(minLits, alpha, m);
            sdd_ref(beta,m);
            bool isSat = isSatisfiableRefined(beta, m, permVars, permSdd, assumedSatSdds, responsibleVars);
            sdd_deref(beta,m); sdd_deref(nextWorld,m);
            dependentSdds.erase(alpha);
            return isSat;
        }
        assumedSatSdds.insert(postModalAssumedSatSdds.begin(),postModalAssumedSatSdds.end());
    }
    
    satCache.insert(alpha);
    dependentSdds.erase(alpha);
    return true;
}