예제 #1
0
파일: Reasoner.cpp 프로젝트: LEW21/Xtreeme
		std::vector<InferredStatement> think(Data& data, Statement N)
		{
			auto R = std::vector<InferredStatement>{}; // reasoned statements

			auto sameAs             = data[::sameAs];
			auto inverseOf          = data[::inverseOf];
			auto equivalentProperty = data[::equivalentProperty];
			auto subPropertyOf      = data[::subPropertyOf];
			auto instanceOf         = data[::instanceOf];
			auto TransitiveProperty = data[::TransitiveProperty];
			auto SymmetricProperty  = data[::SymmetricProperty];

			// Check for special things related to our subject.
			for (auto id : data.find(N.subject.id, sameAs.id, 0, 0))
			{
				auto S_sameAs = data.resource(id).as<Statement>();

				R.emplace_back(Statement{S_sameAs.object, N.predicate, N.object}, std::vector<Statement>{N, S_sameAs});
			}

			// Check for special things related to our predicate.
			for (auto pID : data.find(N.predicate.id, 0, 0, 0))
			{
				auto p = data.resource(pID).as<Statement>();

				if (p.predicate == sameAs || p.predicate == equivalentProperty || p.predicate == subPropertyOf)
				{
					R.emplace_back(Statement(N.subject, p.object, N.object), std::vector<Statement>{N, p});
				}
				else if (p.predicate == inverseOf)
				{
					R.emplace_back(Statement(N.object, p.object, N.subject), std::vector<Statement>{N, p});
				}
				else if (p.predicate == instanceOf)
				{
					if (p.object == TransitiveProperty)
					{
						// We need A-Y-C for every A-Y-B B-Y-C pair.
						// If we are A-Y-B:
						for (auto s : data.find(N.object, N.predicate, {}, {}))
							R.emplace_back(Statement(N.subject, N.predicate, s.object), std::vector<Statement>{N, p, s});
						// If we are B-Y-C:
						for (auto s : data.find({}, N.predicate, N.subject, {}))
							R.emplace_back(Statement(s.subject, N.predicate, N.object), std::vector<Statement>{N, p, s});
					}
					else if (p.object == SymmetricProperty)
					{
						R.emplace_back(Statement(N.object, N.predicate, N.subject), std::vector<Statement>{N, p});
					}
				}
			}

			// Check for special things related to our object.
			for (auto id : data.find(N.object.id, sameAs.id, 0, 0))
			{
				auto O_sameAs = data.resource(id).as<Statement>();

				R.emplace_back(Statement{N.subject, N.predicate, O_sameAs.object}, std::vector<Statement>{N, O_sameAs});
			}

			// OKAY, and now the other way.

			if (N.predicate == instanceOf)
			{
				if (N.object == TransitiveProperty)
				{
					// OK, so this is a transitive property!
					// We need to create A-Y-C for every s(A-Y-B) z(B-Y-C) pair.
					for (auto s : data.find({}, N.subject, {}, {}))
						for (auto z : data.find(s.object, N.subject, {}, {}))
							R.emplace_back(Statement{s.subject, N.subject, z.object}, vector<Statement>{N, s, z});
				}
				else if (N.object == SymmetricProperty)
				{
					// OK, so this is a symmetric property!
					// We need to copy all the statements using it in a reversed way.
					for (auto s : data.find({}, N.subject, {}, {}))
						R.emplace_back(Statement{s.object, N.subject, s.subject}, vector<Statement>{N, s});
				}
			}
			else if (N.predicate == sameAs)
			{
				// Is currently added property sameAs? If so, then copy everything!
				// There is no difference in which way will we copy it - everything will be copied in the second way by reversed sameAs created before by the effect of SymmetricProperty.
				for (auto s : data.find(N.subject, {}, {}, {}))
					R.emplace_back(Statement{N.object, s.predicate, s.object}, vector<Statement>{N, s});

				for (auto s : data.find({}, N.subject, {}, {}))
					R.emplace_back(Statement{s.subject, N.object, s.object}, vector<Statement>{N, s});

				for (auto s : data.find({}, {}, N.subject, {}))
					R.emplace_back(Statement{s.subject, s.predicate, N.object}, vector<Statement>{N, s});
			}
			else if (N.predicate == equivalentProperty || N.predicate == subPropertyOf)
			{
				for (auto s : data.find({}, N.subject, {}, {}))
					R.emplace_back(Statement{s.subject, N.object, s.object}, vector<Statement>{N, s});
			}
			else if (N.predicate == inverseOf)
			{
				for (auto s : data.find({}, N.subject, {}, {}))
					R.emplace_back(Statement{s.object, N.object, s.subject}, vector<Statement>{N, s});
			}
			// TODO equivalentClass, subClassOf

			// Remove useless ideas, like A => A.
			auto Rbak = move(R);
			R = {};
			for (auto r : Rbak)
			{
				bool recursive = false;
				for (auto reason : r.inferredFrom)
					if (r.s.subject == reason.subject && r.s.predicate == reason.predicate && r.s.object == reason.object)
						recursive = true;
				if (!recursive)
					R.emplace_back(r);
			}

			return R;
		}
std::vector<Lepton> MuXboostedBTagging::Muons(std::vector<Lepton> const &delphes_muons, Jet const &jet) const
{
    INFO0;
    auto muons = std::vector<Lepton> {};
    for (auto const &muon : delphes_muons) if (Close<Lepton>(jet, Settings::JetConeSize())(muon)) muons.emplace_back(muon);
    boost::sort(muons, [](Jet const & one, Jet const & two) {
        return one.Pt() < two.Pt();
    });
    return muons;
}
예제 #3
0
void readRelocsIntoVector(TransRelocInfo&& tri, void* data) {
  if (mcg->code().prof().contains(tri.start)) return;
  auto v = static_cast<std::vector<TransRelocInfo>*>(data);
  v->emplace_back(std::move(tri));
}
예제 #4
0
파일: main.cpp 프로젝트: vogel/kadu
int main(int argc, char *argv[]) try
{
    WSAHandler wsaHandler;

    QApplication application{argc, argv};
    application.setApplicationName("Kadu");
    application.setQuitOnLastWindowClosed(false);

    auto executionArgumentsParser = ExecutionArgumentsParser{};
    // do not parse program name
    auto executionArguments = executionArgumentsParser.parse(QCoreApplication::arguments().mid(1));

    if (executionArguments.queryVersion())
    {
        printVersion();
        return 0;
    }

    if (executionArguments.queryUsage())
    {
        printUsage();
        return 0;
    }

    if (!executionArguments.debugMask().isEmpty())
    {
        bool ok;
        executionArguments.debugMask().toInt(&ok);
        if (ok)
            qputenv("DEBUG_MASK", executionArguments.debugMask().toUtf8());
        else
            fprintf(stderr, "Ignoring invalid debug mask '%s'\n", executionArguments.debugMask().toUtf8().constData());
    }

    qRegisterMetaType<Message>();

    auto profileDirectory = executionArguments.profileDirectory().isEmpty()
                            ? QString::fromUtf8(qgetenv("CONFIG_DIR"))
                            : executionArguments.profileDirectory();

    auto modules = std::vector<std::unique_ptr<injeqt::module>> {};
    modules.emplace_back(std::make_unique<AccountModule>());
    modules.emplace_back(std::make_unique<ActionsModule>());
    modules.emplace_back(std::make_unique<AvatarModule>());
    modules.emplace_back(std::make_unique<BuddyModule>());
    modules.emplace_back(std::make_unique<ChatModule>());
    modules.emplace_back(std::make_unique<ChatStyleModule>());
    modules.emplace_back(std::make_unique<ChatWidgetModule>());
    modules.emplace_back(std::make_unique<ChatWindowModule>());
    modules.emplace_back(std::make_unique<CoreModule>(std::move(profileDirectory)));
    modules.emplace_back(std::make_unique<ConfigurationModule>());
    modules.emplace_back(std::make_unique<ContactModule>());
    modules.emplace_back(std::make_unique<DomModule>());
    modules.emplace_back(std::make_unique<FileTransferModule>());
    modules.emplace_back(std::make_unique<FormattedStringModule>());
    modules.emplace_back(std::make_unique<GuiModule>());
    modules.emplace_back(std::make_unique<IconsModule>());
    modules.emplace_back(std::make_unique<IdentityModule>());
    modules.emplace_back(std::make_unique<MessageModule>());
    modules.emplace_back(std::make_unique<MultilogonModule>());
    modules.emplace_back(std::make_unique<NetworkModule>());
    modules.emplace_back(std::make_unique<NotificationModule>());
    modules.emplace_back(std::make_unique<OsModule>());
    modules.emplace_back(std::make_unique<ParserModule>());
    modules.emplace_back(std::make_unique<PluginModule>());
    modules.emplace_back(std::make_unique<RosterModule>());
    modules.emplace_back(std::make_unique<SslModule>());
    modules.emplace_back(std::make_unique<StatusModule>());
    modules.emplace_back(std::make_unique<TalkableModule>());
    modules.emplace_back(std::make_unique<ThemesModule>());

    auto injector = injeqt::injector{std::move(modules)};

    try
    {
        injector.instantiate<Application>(); // force creation of Application object

#ifndef Q_OS_WIN
        // Qt version is better on win32
        qInstallMsgHandler(kaduQtMessageHandler);
#endif

#ifdef DEBUG_OUTPUT_ENABLED
        showTimesInDebug = (0 != qgetenv("SHOW_TIMES").toInt());
#endif

        Core core{std::move(injector)};
        return core.executeSingle(executionArguments);
    }
    catch (ConfigurationUnusableException &)
    {
        auto profilePath = injector.get<ConfigurationPathProvider>()->configurationDirectoryPath();
        auto errorMessage = QCoreApplication::translate("@default", "We're sorry, but Kadu cannot be loaded. "
                            "Profile is inaccessible. Please check permissions in the '%1' directory.")
                            .arg(profilePath.left(profilePath.length() - 1));
        QMessageBox::critical(0, QCoreApplication::translate("@default", "Profile Inaccessible"), errorMessage, QMessageBox::Abort);

        throw;
    }
}
#if defined(Q_OS_WIN)
catch (WSAException &)
{
    return 2;
}
#endif
catch (ConfigurationUnusableException &)
{
    // already handled
}
catch (...)
{
    throw;
}
예제 #5
0
requirement_data requirement_data::disassembly_requirements() const
{
    // TODO:
    // Allow jsonizing those tool replacements

    // Make a copy
    // Maybe TODO: Cache it somewhere and return a reference instead
    requirement_data ret = *this;
    auto new_qualities = std::vector<quality_requirement>();
    for( auto &it : ret.tools ) {
        bool replaced = false;
        for( const auto &tool : it ) {
            const itype_id &type = tool.type;

            // If crafting required a welder or forge then disassembly requires metal sawing
            if( type == "welder" || type == "welder_crude" || type == "oxy_torch" ||
                type == "forge" || type == "char_forge" ) {
                new_qualities.emplace_back( quality_id( "SAW_M_FINE" ), 1, 1 );
                replaced = true;
                break;
            }
            //This only catches instances where the two tools are explicitly stated, and not just the required sewing quality
            if( type == "sewing_kit" ||
                type == "mold_plastic" ) {
                new_qualities.emplace_back( quality_id( "CUT" ), 1, 1 );
                replaced = true;
                break;
            }

            if( type == "crucible" ) {
                replaced = true;
                break;
            }
        }

        if( replaced ) {
            // Replace the entire block of variants
            // This avoids the pesky integrated toolset
            it.clear();
        }
    }

    // Warning: This depends on the fact that tool qualities
    // are all mandatory (don't use variants)
    // If that ever changes, this will be wrong!
    if( ret.qualities.empty() ) {
        ret.qualities.resize( 1 );
    } else {
        //If the required quality level is not empty, iterate through and replace or remove
        //qualities with deconstruction equivalents
        for( auto &it : ret.qualities ) {
            bool replaced = false;
            for( const auto &quality : it ) {
                if( quality.type == quality_id( "SEW" ) ) {
                    replaced = true;
                    new_qualities.emplace_back( quality_id( "CUT" ), 1, quality.level );
                    break;
                }
                if( quality.type == quality_id( "GLARE" ) ) {
                    replaced = true;
                    //Just remove the glare protection requirement from deconstruction
                    //This only happens in case of a reversible recipe, an explicit
                    //deconstruction recipe can still specify glare protection
                    break;
                }
                if( quality.type == quality_id( "KNIT" ) ) {
                    replaced = true;
                    //Ditto for knitting needles
                    break;
                }
            }
            if( replaced ) {
                it.clear();
            }
        }
    }

    auto &qualities = ret.qualities[0];
    qualities.insert( qualities.end(), new_qualities.begin(), new_qualities.end() );
    // Remove duplicate qualities
    {
        auto itr = std::unique( qualities.begin(), qualities.end(),
        []( const quality_requirement & a, const quality_requirement & b ) {
            return a.type == b.type;
        } );
        qualities.resize( std::distance( qualities.begin(), itr ) );
    }

    // Remove empty variant sections
    ret.tools.erase( std::remove_if( ret.tools.begin(), ret.tools.end(),
    []( const std::vector<tool_comp> &tcv ) {
        return tcv.empty();
    } ), ret.tools.end() );
    // Remove unrecoverable components
    ret.components.erase( std::remove_if( ret.components.begin(), ret.components.end(),
    []( std::vector<item_comp> &cov ) {
        cov.erase( std::remove_if( cov.begin(), cov.end(),
        []( const item_comp & comp ) {
            return !comp.recoverable || item( comp.type ).has_flag( "UNRECOVERABLE" );
        } ), cov.end() );
        return cov.empty();
    } ), ret.components.end() );

    return ret;
}
예제 #6
0
 explicit taglist_t(osmium::TagList const &list)
 {
     for (auto const &t : list) {
         emplace_back(t.key(), t.value());
     }
 }
예제 #7
0
void region_prune_arcs(RegionDesc& region, std::vector<Type>* input) {
  FTRACE(4, "region_prune_arcs\n");

  region.sortBlocks();
  auto const sortedBlocks = region.blocks();

  // Maps region block ids to their RPO ids.
  auto blockToRPO = std::unordered_map<RegionDesc::BlockId,uint32_t>{};

  auto blockInfos = std::vector<BlockInfo>(sortedBlocks.size());
  auto workQ = dataflow_worklist<uint32_t>(sortedBlocks.size());
  for (auto rpoID = uint32_t{0}; rpoID < sortedBlocks.size(); ++rpoID) {
    auto const& b = sortedBlocks[rpoID];
    auto& binfo = blockInfos[rpoID];
    binfo.blockID = b->id();
    blockToRPO[binfo.blockID] = rpoID;
  }
  workQ.push(0);
  blockInfos[0].in = entry_state(region, input);

  FTRACE(4, "Iterating:\n");
  do {
    auto const rpoID = workQ.pop();
    auto& binfo = blockInfos[rpoID];
    FTRACE(4, "B{}\n", binfo.blockID);

    binfo.out = binfo.in;
    apply_transfer_function(
      binfo.out,
      region.block(binfo.blockID)->postConds()
    );

    for (auto& succ : region.succs(binfo.blockID)) {
      auto const succRPO = blockToRPO.find(succ);
      assertx(succRPO != end(blockToRPO));
      auto& succInfo = blockInfos[succRPO->second];
      if (preconds_may_pass(*region.block(succInfo.blockID), binfo.out)) {
        if (merge_into(succInfo.in, binfo.out)) {
          FTRACE(5, "  -> {}\n", succInfo.blockID);
          workQ.push(succRPO->second);
        }
      }
    }
  } while (!workQ.empty());

  FTRACE(2, "\nPostConds fixed point:\n{}\n",
    [&] () -> std::string {
      auto ret = std::string{};
      for (auto& s : blockInfos) {
        folly::format(&ret, "B{}:\n{}", s.blockID, show(s.in));
      }
      return ret;
    }()
  );

  // Now remove any edge that looks like it will unconditionally fail type
  // predictions, and completely remove any block that can't be reached.
  using ArcIDs = std::pair<RegionDesc::BlockId,RegionDesc::BlockId>;
  auto toRemove = std::vector<ArcIDs>{};
  for (auto rpoID = uint32_t{0}; rpoID < sortedBlocks.size(); ++rpoID) {
    auto const& binfo = blockInfos[rpoID];

    for (auto& succ : region.succs(binfo.blockID)) {
      auto const succRPO = blockToRPO.find(succ);
      assertx(succRPO != end(blockToRPO));
      auto const& succInfo = blockInfos[succRPO->second];
      if (!binfo.in.initialized ||
          !succInfo.in.initialized ||
          !preconds_may_pass(*region.block(succInfo.blockID), binfo.out)) {
        FTRACE(2, "Pruning arc: B{} -> B{}\n",
               binfo.blockID,
               succInfo.blockID);
        toRemove.emplace_back(binfo.blockID, succInfo.blockID);
      }
    }

    for (auto& r : toRemove) region.removeArc(r.first, r.second);
    toRemove.clear();
  }

  // Get rid of the completely unreachable blocks, now that any arcs to/from
  // them are gone.
  for (auto rpoID = uint32_t{0}; rpoID < sortedBlocks.size(); ++rpoID) {
    auto const& binfo = blockInfos[rpoID];
    if (!binfo.in.initialized) {
      FTRACE(2, "Pruning block: B{}\n", binfo.blockID);
      region.deleteBlock(binfo.blockID);
    }
  }
  FTRACE(2, "\n");
}
예제 #8
0
void MongoDSessionCatalog::onStepUp(OperationContext* opCtx) {
    // Invalidate sessions that could have a retryable write on it, so that we can refresh from disk
    // in case the in-memory state was out of sync.
    const auto catalog = SessionCatalog::get(opCtx);
    // The use of shared_ptr here is in order to work around the limitation of stdx::function that
    // the functor must be copyable.
    auto sessionKillTokens = std::make_shared<std::vector<SessionCatalog::KillToken>>();

    // Scan all sessions and reacquire locks for prepared transactions.
    // There may be sessions that are checked out during this scan, but none of them
    // can be prepared transactions, since only oplog application can make transactions
    // prepared on secondaries and oplog application has been stopped at this moment.
    std::vector<LogicalSessionId> sessionIdToReacquireLocks;

    SessionKiller::Matcher matcher(
        KillAllSessionsByPatternSet{makeKillAllSessionsByPattern(opCtx)});
    catalog->scanSessions(matcher, [&](const ObservableSession& session) {
        const auto txnParticipant = TransactionParticipant::get(session.get());
        if (!txnParticipant->inMultiDocumentTransaction()) {
            sessionKillTokens->emplace_back(session.kill());
        }

        if (txnParticipant->transactionIsPrepared()) {
            sessionIdToReacquireLocks.emplace_back(session.getSessionId());
        }
    });
    killSessionTokensFunction(opCtx, sessionKillTokens);

    {
        // Create a new opCtx because we need an empty locker to refresh the locks.
        auto newClient = opCtx->getServiceContext()->makeClient("restore-prepared-txn");
        AlternativeClientRegion acr(newClient);
        for (const auto& sessionId : sessionIdToReacquireLocks) {
            auto newOpCtx = cc().makeOperationContext();
            newOpCtx->setLogicalSessionId(sessionId);
            MongoDOperationContextSession ocs(newOpCtx.get());
            auto txnParticipant =
                TransactionParticipant::get(OperationContextSession::get(newOpCtx.get()));
            LOG(3) << "Restoring locks of prepared transaction. SessionId: " << sessionId.getId()
                   << " TxnNumber: " << txnParticipant->getActiveTxnNumber();
            txnParticipant->refreshLocksForPreparedTransaction(newOpCtx.get(), false);
        }
    }

    const size_t initialExtentSize = 0;
    const bool capped = false;
    const bool maxSize = 0;

    BSONObj result;

    DBDirectClient client(opCtx);

    if (client.createCollection(NamespaceString::kSessionTransactionsTableNamespace.ns(),
                                initialExtentSize,
                                capped,
                                maxSize,
                                &result)) {
        return;
    }

    const auto status = getStatusFromCommandResult(result);

    if (status == ErrorCodes::NamespaceExists) {
        return;
    }

    uassertStatusOKWithContext(status,
                               str::stream()
                                   << "Failed to create the "
                                   << NamespaceString::kSessionTransactionsTableNamespace.ns()
                                   << " collection");
}
예제 #9
0
static bool
blockify(Shader &shader, const LabelList &labels)
{
   shadir::CodeBlock *activeCodeBlock = nullptr;
   auto activeBlockList = &shader.blocks;
   auto labelItr = labels.begin();
   Label *label = nullptr;

   if (labelItr != labels.end()) {
      label = labelItr->get();
   }

   // Iterate over code and find matching labels to generate code blocks
   for (auto &ins : shader.code) {
      bool insertToCode = true;

      while (label && label->first == ins.get()) {
         // Most labels will skip current instruction
         insertToCode = false;

         if (label->type == Label::LoopStart) {
            assert(label->linkedLabel);
            assert(label->linkedLabel->type == Label::LoopEnd);

            // Save the active block list to the LoopEnd label
            label->linkedLabel->restoreBlockList = activeBlockList;

            // Create a new loop block
            auto loopBlock = new shadir::LoopBlock {};
            label->linkedBlock = loopBlock;
            activeBlockList->emplace_back(loopBlock);

            // Set the current block list to the loop inner
            activeBlockList = &loopBlock->inner;
            activeCodeBlock = nullptr;
         } else if (label->type == Label::LoopEnd) {
            assert(label->linkedLabel);
            assert(label->linkedLabel->type == Label::LoopStart);
            assert(label->restoreBlockList);

            // Get the matching LoopBlock from the LoopStart label
            auto loopBlock = reinterpret_cast<shadir::LoopBlock *>(label->linkedLabel->linkedBlock);

            // Restore the previous block list
            activeBlockList = label->restoreBlockList;
            activeCodeBlock = nullptr;
         } else if (label->type == Label::ConditionalStart) {
            assert(label->linkedLabel);
            assert(label->linkedLabel->type == Label::ConditionalEnd);

            // Save the active block list to the ConditionalEnd label
            label->linkedLabel->restoreBlockList = activeBlockList;

            // Create a new conditional block
            auto condBlock = new shadir::ConditionalBlock { ins.get() };
            label->linkedBlock = condBlock;
            activeBlockList->emplace_back(condBlock);

            // Set current block list to the condition inner
            activeBlockList = &condBlock->inner;
            activeCodeBlock = nullptr;
         } else if (label->type == Label::ConditionalElse) {
            assert(label->linkedLabel);
            assert(label->linkedLabel->type == Label::ConditionalStart);

            // Get the matching ConditionalBlock from the ConditionalStart label
            auto condBlock = reinterpret_cast<shadir::ConditionalBlock *>(label->linkedLabel->linkedBlock);

            // Set current block list to the condition else
            activeBlockList = &condBlock->innerElse;
            activeCodeBlock = nullptr;
         } else if (label->type == Label::ConditionalEnd) {
            assert(label->linkedLabel);
            assert(label->linkedLabel->type == Label::ConditionalStart);
            assert(label->restoreBlockList);

            // Get the matching ConditionalBlock from the ConditionalStart label
            auto condBlock = reinterpret_cast<shadir::ConditionalBlock *>(label->linkedLabel->linkedBlock);

            // Restore the previous block list
            activeBlockList = label->restoreBlockList;
            activeCodeBlock = nullptr;

            // Do not skip the current instruction, add it to a code block
            insertToCode = true;
         }

         // Start comparing to next label!
         ++labelItr;

         if (labelItr != labels.end()) {
            label = labelItr->get();
         } else {
            label = nullptr;
         }
      }

      if (insertToCode) {
         assert(activeBlockList);

         if (!activeCodeBlock) {
            // Create a new block for active list
            activeCodeBlock = new shadir::CodeBlock {};
            activeBlockList->emplace_back(activeCodeBlock);
         }

         activeCodeBlock->code.push_back(ins.get());
      }
   }

   return true;
}
예제 #10
0
template <class Container> Container *one_to_n(int n) {
    auto v = new Container();
    for (int i = 1; i <= n; i++)
        v->emplace_back(i);
    return v;
}
bool PreprocessorCompletionModel::shouldAbortCompletion(
    KTextEditor::View* const view
  , const KTextEditor::Range& inserted_range
  , const QString& inserted_text
  )
{
    auto* const doc = view->document();                     // get current document
    kDebug(DEBUG_AREA) << "completion text=" << inserted_text;

    if (!m_should_complete)
        return true;

    /// Make sure the current line starts w/ a hash.
    auto text_before = doc->text(
        {KTextEditor::Cursor(inserted_range.end().line(), 0), inserted_range.end()}
      );
    kDebug(DEBUG_AREA) << "text_before=" << text_before;

    /// Check if current line starts w/ \c '#' which is a sign of a preprocessor directive.
    if (text_before[0] != '#')
        return false;
    /// If we are start completion, and user entered text still empty,
    /// when no reason to abort completion.
    if (inserted_text.isEmpty())
        return false;

    /// Otherwise, try to collect indices of matched completion items.
    auto matches = std::vector<int>{};
    matches.reserve(COMPLETIONS.size());
    for (auto i = 0u; i < COMPLETIONS.size(); ++i)
    {
        auto text = COMPLETIONS[i].text;
        const auto end_of_first_word = text.indexOf(' ');
        if (end_of_first_word != -1)
            text = text.left(end_of_first_word);
        const auto is_match = inserted_text.size() < text.size()
          && text.startsWith(inserted_text)
          ;
        if (is_match)
            matches.emplace_back(i);
    }

    /// Then, if matched items count equal to one, that means
    /// we can auto-insert that item (cuz there is no other alternatives).
    if (matches.size() == 1)
    {
        auto item_text = COMPLETIONS[matches[0]].text;
        const auto column = item_text.indexOf('|');
        if (column != -1)
            item_text.remove(column, 1);

        doc->replaceText(inserted_range, item_text);

        // Try to reposition a cursor inside a current view
        if (column != -1)
        {
            auto pos = inserted_range.start();
            pos.setColumn(pos.column() + column);
            doc->activeView()->setCursorPosition(pos);
        }
        kDebug(DEBUG_AREA) << "yEAH! wANt ABrT;";
        return true;
    }
    m_should_complete = !matches.empty();
    kDebug(DEBUG_AREA) << "m_should_complete=" << m_should_complete;
    return !m_should_complete;
}
예제 #12
0
int GMSHInterface::writeGMSHInputFile(std::ostream& out)
{
    DBUG("GMSHInterface::writeGMSHInputFile(): get data from GEOObjects.");

    if (_selected_geometries.empty())
        return 1;

    // *** get and merge data from _geo_objs
    if (_selected_geometries.size() > 1) {
        _gmsh_geo_name = "GMSHGeometry";
        if (_geo_objs.mergeGeometries(_selected_geometries, _gmsh_geo_name))
            return 2;
    } else {
        _gmsh_geo_name = _selected_geometries[0];
        _keep_preprocessed_geometry = true;
    }

    auto* merged_pnts(const_cast<std::vector<GeoLib::Point*>*>(
        _geo_objs.getPointVec(_gmsh_geo_name)));
    if (! merged_pnts) {
        ERR("GMSHInterface::writeGMSHInputFile(): Did not found any points.");
        return 2;
    }

    if (_rotate) {
        // Rotate points to the x-y-plane.
        _inverse_rot_mat = GeoLib::rotatePointsToXY(*merged_pnts);
        // Compute inverse rotation matrix to reverse the rotation later on.
        _inverse_rot_mat.transposeInPlace();
    } else {
        // project data on the x-y-plane
        _inverse_rot_mat(0,0) = 1.0;
        _inverse_rot_mat(1,1) = 1.0;
        _inverse_rot_mat(2,2) = 1.0;
        for (auto pnt : *merged_pnts)
            (*pnt)[2] = 0.0;
    }

    std::vector<GeoLib::Polyline*> const* merged_plys(
        _geo_objs.getPolylineVec(_gmsh_geo_name));
    DBUG("GMSHInterface::writeGMSHInputFile(): Obtained data.");

    if (!merged_plys) {
        ERR("GMSHInterface::writeGMSHInputFile(): Did not find any polylines.");
        return 2;
    }

    // *** compute and insert all intersection points between polylines
    GeoLib::PointVec& pnt_vec(*const_cast<GeoLib::PointVec*>(
        _geo_objs.getPointVecObj(_gmsh_geo_name)));
    GeoLib::computeAndInsertAllIntersectionPoints(pnt_vec,
        *(const_cast<std::vector<GeoLib::Polyline*>*>(merged_plys)));

    // *** compute topological hierarchy of polygons
    for (auto polyline : *merged_plys) {
        if (!polyline->isClosed()) {
            continue;
        }
        _polygon_tree_list.push_back(new GMSH::GMSHPolygonTree(
            new GeoLib::PolygonWithSegmentMarker(*polyline), nullptr, _geo_objs,
            _gmsh_geo_name, *_mesh_density_strategy));
    }
    DBUG(
        "GMSHInterface::writeGMSHInputFile(): Computed topological hierarchy - "
        "detected %d polygons.",
        _polygon_tree_list.size());
    GeoLib::createPolygonTrees<GMSH::GMSHPolygonTree>(_polygon_tree_list);
    DBUG(
        "GMSHInterface::writeGMSHInputFile(): Computed topological hierarchy - "
        "calculated %d polygon trees.",
        _polygon_tree_list.size());

    // *** Mark in each polygon tree the segments shared by two polygons.
    for (auto* polygon_tree : _polygon_tree_list)
    {
        polygon_tree->markSharedSegments();
    }

    // *** insert stations and polylines (except polygons) in the appropriate object of
    //     class GMSHPolygonTree
    // *** insert stations
    auto gmsh_stations = std::make_unique<std::vector<GeoLib::Point*>>();
    for (auto const& geometry_name : _selected_geometries) {
        auto const* stations(_geo_objs.getStationVec(geometry_name));
        if (stations) {
            for (auto * station : *stations) {
                bool found(false);
                for (auto it(_polygon_tree_list.begin());
                    it != _polygon_tree_list.end() && !found; ++it) {
                    gmsh_stations->emplace_back(new GeoLib::Station(
                        *static_cast<GeoLib::Station*>(station)));
                    if ((*it)->insertStation(gmsh_stations->back())) {
                        found = true;
                    }
                }
            }
        }
    }
    std::string gmsh_stations_name(_gmsh_geo_name+"-Stations");
    if (! gmsh_stations->empty()) {
        _geo_objs.addStationVec(std::move(gmsh_stations), gmsh_stations_name);
    }

    // *** insert polylines
    for (auto polyline : *merged_plys) {
        if (!polyline->isClosed()) {
            for (auto * polygon_tree : _polygon_tree_list) {
                auto polyline_with_segment_marker =
                    new GeoLib::PolylineWithSegmentMarker(*polyline);
                polygon_tree->insertPolyline(polyline_with_segment_marker);
            }
        }
    }

    // *** init mesh density strategies
    for (auto& polygon_tree : _polygon_tree_list)
    {
        polygon_tree->initMeshDensityStrategy();
    }

    // *** create GMSH data structures
    const std::size_t n_merged_pnts(merged_pnts->size());
    _gmsh_pnts.resize(n_merged_pnts);
    for (std::size_t k(0); k<n_merged_pnts; k++) {
        _gmsh_pnts[k] = nullptr;
    }
    for (auto& polygon_tree : _polygon_tree_list)
    {
        polygon_tree->createGMSHPoints(_gmsh_pnts);
    }

    // *** finally write data :-)
    writePoints(out);
    std::size_t pnt_id_offset(_gmsh_pnts.size());
    for (auto* polygon_tree : _polygon_tree_list)
    {
        polygon_tree->writeLineLoop(_n_lines, _n_plane_sfc, out);
        polygon_tree->writeSubPolygonsAsLineConstraints(_n_lines, _n_plane_sfc-1, out);
        polygon_tree->writeLineConstraints(_n_lines, _n_plane_sfc-1, out);
        polygon_tree->writeStations(pnt_id_offset, _n_plane_sfc-1, out);
        polygon_tree->writeAdditionalPointData(pnt_id_offset, _n_plane_sfc-1, out);
    }

    if (! _keep_preprocessed_geometry) {
        _geo_objs.removeSurfaceVec(_gmsh_geo_name);
        _geo_objs.removePolylineVec(_gmsh_geo_name);
        _geo_objs.removePointVec(_gmsh_geo_name);
        _geo_objs.removeStationVec(gmsh_stations_name);
    }

    return 0;
}
예제 #13
0
requirement_data requirement_data::disassembly_requirements() const
{
    // TODO:
    // Allow jsonizing those tool replacements

    // Make a copy
    // Maybe TODO: Cache it somewhere and return a reference instead
    requirement_data ret = *this;
    auto new_qualities = std::vector<quality_requirement>();
    for( auto &it : ret.tools ) {
        bool replaced = false;
        for( const auto &tool : it ) {
            const itype_id &type = tool.type;

            // If crafting required a welder or forge then disassembly requires metal sawing
            if( type == "welder" || type == "welder_crude" || type == "oxy_torch" ||
                type == "forge" || type == "char_forge" ) {
                new_qualities.emplace_back( quality_id( "SAW_M_FINE" ), 1, 1 );
                replaced = true;
                break;
            }

            if( type == "sewing_kit" ||
                type == "mold_plastic" ) {
                new_qualities.emplace_back( quality_id( "CUT" ), 1, 1 );
                replaced = true;
                break;
            }

            if( type == "crucible" ) {
                replaced = true;
                break;
            }
        }

        if( replaced ) {
            // Replace the entire block of variants
            // This avoids the pesky integrated toolset
            it.clear();
        }
    }

    // Warning: This depends on the fact that tool qualities
    // are all mandatory (don't use variants)
    // If that ever changes, this will be wrong!
    if( ret.qualities.empty() ) {
        ret.qualities.resize( 1 );
    }

    auto &qualities = ret.qualities[0];
    qualities.insert( qualities.end(), new_qualities.begin(), new_qualities.end() );
    // Remove duplicate qualities
    {
        auto itr = std::unique( qualities.begin(), qualities.end(),
                                []( const quality_requirement & a, const quality_requirement & b ) {
                                    return a.type == b.type;
                                } );
        qualities.resize( std::distance( qualities.begin(), itr ) );
    }

    // Remove empty variant sections
    ret.tools.erase( std::remove_if( ret.tools.begin(), ret.tools.end(),
                                     []( const std::vector<tool_comp> &tcv ) {
                                         return tcv.empty();
                                     } ), ret.tools.end() );
    // Remove unrecoverable components
    ret.components.erase( std::remove_if( ret.components.begin(), ret.components.end(),
        []( std::vector<item_comp> &cov ) {
            cov.erase( std::remove_if( cov.begin(), cov.end(),
                []( const item_comp &comp ) {
                    return !comp.recoverable || item( comp.type ).has_flag( "UNRECOVERABLE" );
                } ), cov.end() );
            return cov.empty();
        } ), ret.components.end() );

    return ret;
}
예제 #14
0
std::unique_ptr<Builder> ConfigParser::getBuilder(
        Json::Value json,
        std::shared_ptr<arbiter::Arbiter> arbiter)
{
    if (!arbiter) arbiter = std::make_shared<arbiter::Arbiter>();

    const bool verbose(json["verbose"].asBool());

    const Json::Value d(defaults());
    for (const auto& k : d.getMemberNames())
    {
        if (!json.isMember(k)) json[k] = d[k];
    }

    const std::string outPath(json["output"].asString());
    const std::string tmpPath(json["tmp"].asString());
    const std::size_t threads(json["threads"].asUInt64());

    normalizeInput(json, *arbiter);
    auto fileInfo(extract<FileInfo>(json["input"]));

    if (!json["force"].asBool())
    {
        auto builder = tryGetExisting(
                json,
                *arbiter,
                outPath,
                tmpPath,
                threads);

        if (builder)
        {
            if (verbose) builder->verbose(true);

            // If we have more paths to add, add them to the manifest.
            // Otherwise we might be continuing a partial build, in which case
            // the paths to be built are already outstanding in the manifest.
            //
            // It's plausible that the input field could be empty to continue
            // a previous build.
            if (json["input"].isArray()) builder->append(fileInfo);
            return builder;
        }
    }

    const bool compress(json["compress"].asUInt64());
    const bool trustHeaders(json["trustHeaders"].asBool());
    auto cesiumSettings(getCesiumSettings(json["formats"]));
    bool absolute(json["absolute"].asBool());

    if (cesiumSettings)
    {
        absolute = true;
        json["reprojection"]["out"] = "EPSG:4978";
    }

    auto reprojection(maybeCreate<Reprojection>(json["reprojection"]));

    std::unique_ptr<std::vector<double>> transformation;
    std::unique_ptr<Delta> delta;
    if (!absolute && Delta::existsIn(json)) delta = makeUnique<Delta>(json);

    // If we're building from an inference, then we already have these.  A user
    // could have also pre-supplied them in the config.
    //
    // Either way, these three values are prerequisites for building, so if
    // we're missing any we'll need to infer them from the files.
    std::size_t numPointsHint(json["numPointsHint"].asUInt64());
    auto boundsConforming(maybeCreate<Bounds>(json["bounds"]));
    auto schema(maybeCreate<Schema>(json["schema"]));

    const bool needsInference(!boundsConforming || !schema || !numPointsHint);

    if (needsInference)
    {
        if (verbose)
        {
            std::cout << "Performing dataset inference..." << std::endl;
        }

        Inference inference(
                fileInfo,
                reprojection.get(),
                trustHeaders,
                !absolute,
                tmpPath,
                threads,
                verbose,
                !!cesiumSettings,
                arbiter.get());

        inference.go();

        // Overwrite our initial fileInfo with the inferred version, which
        // contains details for each file instead of just paths.
        fileInfo = inference.fileInfo();

        if (!absolute && inference.delta())
        {
            if (!delta) delta = makeUnique<Delta>();

            if (!json.isMember("scale"))
            {
                delta->scale() = inference.delta()->scale();
            }

            if (!json.isMember("offset"))
            {
                delta->offset() = inference.delta()->offset();
            }
        }

        if (!boundsConforming)
        {
            boundsConforming = makeUnique<Bounds>(inference.bounds());

            if (verbose)
            {
                std::cout << "Inferred: " << inference.bounds() << std::endl;
            }
        }

        if (!schema)
        {
            auto dims(inference.schema().dims());
            if (delta)
            {
                const Bounds cube(
                        Metadata::makeScaledCube(
                            *boundsConforming,
                            delta.get()));
                dims = Schema::deltify(cube, *delta, inference.schema()).dims();
            }

            const std::size_t pointIdSize([&fileInfo]()
            {
                std::size_t max(0);
                for (const auto& f : fileInfo)
                {
                    max = std::max(max, f.numPoints());
                }

                if (max <= std::numeric_limits<uint32_t>::max()) return 4;
                else return 8;
            }());

            const std::size_t originSize([&fileInfo]()
            {
                if (fileInfo.size() <= std::numeric_limits<uint32_t>::max())
                    return 4;
                else
                    return 8;
            }());

            dims.emplace_back("OriginId", "unsigned", originSize);
            dims.emplace_back("PointId", "unsigned", pointIdSize);

            schema = makeUnique<Schema>(dims);
        }

        if (!numPointsHint) numPointsHint = inference.numPoints();

        if (const std::vector<double>* t = inference.transformation())
        {
            transformation = makeUnique<std::vector<double>>(*t);
        }
    }

    auto subset(maybeAccommodateSubset(json, *boundsConforming, delta.get()));

    json["numPointsHint"] = static_cast<Json::UInt64>(numPointsHint);
    Structure structure(json);
    Structure hierarchyStructure(Hierarchy::structure(structure, subset.get()));
    const HierarchyCompression hierarchyCompression(
            compress ? HierarchyCompression::Lzma : HierarchyCompression::None);

    const auto ep(arbiter->getEndpoint(json["output"].asString()));
    const Manifest manifest(fileInfo, ep);

    const Metadata metadata(
            *boundsConforming,
            *schema,
            structure,
            hierarchyStructure,
            manifest,
            trustHeaders,
            compress,
            hierarchyCompression,
            reprojection.get(),
            subset.get(),
            delta.get(),
            transformation.get(),
            cesiumSettings.get());

    OuterScope outerScope;
    outerScope.setArbiter(arbiter);

    auto builder =
        makeUnique<Builder>(metadata, outPath, tmpPath, threads, outerScope);

    if (verbose) builder->verbose(true);
    return builder;
}
예제 #15
0
void Value::set(const wxArrayString& values) {
	clear();
	wxArrayString::const_iterator it;
	for (it = values.begin(); it != values.end(); it++)
		emplace_back(it->ToStdString(), size() + 1);
}
예제 #16
0
int OperationFailed(const string& Object, LNGID Title, const string& Description, bool AllowSkip)
{
	std::vector<string> Msg;
	IFileIsInUse *pfiu = nullptr;
	LNGID Reason = MObjectLockedReasonOpened;
	bool SwitchBtn = false, CloseBtn = false;
	DWORD Error = Global->CaughtError();
	if(Error == ERROR_ACCESS_DENIED ||
		Error == ERROR_SHARING_VIOLATION ||
		Error == ERROR_LOCK_VIOLATION ||
		Error == ERROR_DRIVE_LOCKED)
	{
		string FullName;
		ConvertNameToFull(Object, FullName);
		pfiu = CreateIFileIsInUse(FullName);
		if (pfiu)
		{
			FILE_USAGE_TYPE UsageType = FUT_GENERIC;
			pfiu->GetUsage(&UsageType);
			switch(UsageType)
			{
			case FUT_PLAYING:
				Reason = MObjectLockedReasonPlayed;
				break;
			case FUT_EDITING:
				Reason = MObjectLockedReasonEdited;
				break;
			case FUT_GENERIC:
				Reason = MObjectLockedReasonOpened;
				break;
			}
			DWORD Capabilities = 0;
			pfiu->GetCapabilities(&Capabilities);
			if(Capabilities&OF_CAP_CANSWITCHTO)
			{
				SwitchBtn = true;
			}
			if(Capabilities&OF_CAP_CANCLOSE)
			{
				CloseBtn = true;
			}
			LPWSTR AppName = nullptr;
			if(SUCCEEDED(pfiu->GetAppName(&AppName)))
			{
				Msg.emplace_back(AppName);
			}
		}
		else
		{
			DWORD dwSession;
			WCHAR szSessionKey[CCH_RM_SESSION_KEY+1] = {};
			if (Imports().RmStartSession(&dwSession, 0, szSessionKey) == ERROR_SUCCESS)
			{
				PCWSTR pszFile = FullName.data();
				if (Imports().RmRegisterResources(dwSession, 1, &pszFile, 0, nullptr, 0, nullptr) == ERROR_SUCCESS)
				{
					DWORD dwReason;
					DWORD RmGetListResult;
					UINT nProcInfoNeeded;
					UINT nProcInfo = 1;
					std::vector<RM_PROCESS_INFO> rgpi(nProcInfo);
					while((RmGetListResult=Imports().RmGetList(dwSession, &nProcInfoNeeded, &nProcInfo, rgpi.data(), &dwReason)) == ERROR_MORE_DATA)
					{
						nProcInfo = nProcInfoNeeded;
						rgpi.resize(nProcInfo);
					}
					if(RmGetListResult ==ERROR_SUCCESS)
					{
						for (size_t i = 0; i < nProcInfo; i++)
						{
							string tmp = rgpi[i].strAppName;
							if (*rgpi[i].strServiceShortName)
							{
								tmp.append(L" [").append(rgpi[i].strServiceShortName).append(L"]");
							}
							tmp += L" (PID: " + std::to_wstring(rgpi[i].Process.dwProcessId);
							HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, rgpi[i].Process.dwProcessId);
							if (hProcess)
							{
								FILETIME ftCreate, ftExit, ftKernel, ftUser;
								if (GetProcessTimes(hProcess, &ftCreate, &ftExit, &ftKernel, &ftUser) && rgpi[i].Process.ProcessStartTime == ftCreate)
								{
									string Name;
									if (os::GetModuleFileNameEx(hProcess, nullptr, Name))
									{
										tmp += L", " + Name;
									}
								}
								CloseHandle(hProcess);
							}
							tmp += L")";
							Msg.emplace_back(tmp);
						}
					}
				}
				Imports().RmEndSession(dwSession);
			}
		}
	}

	auto Msgs = make_vector(Description, QuoteLeadingSpace(string(Object)));
	if(!Msg.empty())
	{
		Msgs.emplace_back(LangString(MObjectLockedReason) << MSG(Reason));
		Msgs.insert(Msgs.end(), ALL_CONST_RANGE(Msg));
	}

	std::vector<string> Buttons;
	Buttons.reserve(4);
	if(SwitchBtn)
	{
		Buttons.emplace_back(MSG(MObjectLockedSwitchTo));
	}
	Buttons.emplace_back(MSG(CloseBtn? MObjectLockedClose : MDeleteRetry));
	if(AllowSkip)
	{
		Buttons.emplace_back(MSG(MDeleteSkip));
		Buttons.emplace_back(MSG(MDeleteFileSkipAll));
	}
	Buttons.emplace_back(MSG(MDeleteCancel));

	int Result = -1;
	for(;;)
	{
		Result = Message(MSG_WARNING|MSG_ERRORTYPE, MSG(Title), Msgs, Buttons);

		if(SwitchBtn)
		{
			if(Result == 0)
			{
				HWND Wnd = nullptr;
				if (pfiu && SUCCEEDED(pfiu->GetSwitchToHWND(&Wnd)))
				{
					SetForegroundWindow(Wnd);
					if (IsIconic(Wnd))
						ShowWindow(Wnd, SW_RESTORE);
				}
				continue;
			}
			else if(Result > 0)
			{
				--Result;
			}
		}

		if(CloseBtn && Result == 0)
		{
			// close & retry
			if (pfiu)
			{
				pfiu->CloseFile();
			}
		}
		break;
	}

	if (pfiu)
	{
		pfiu->Release();
	}

	return Result;
}
예제 #17
0
void Params::add(Param&& param) {
	iterator it = find(param.get_name());
	if (it == end()) emplace_back(param);
	else set_value(param.get_name(), param.get_value());
}
예제 #18
0
 explicit memberlist_t(osmium::RelationMemberList const &list) {
     for (auto const &m: list) {
         emplace_back(m.type(), m.ref(), m.role());
     }
 }