/**
 * @brief  Get the identification of the permission to remove.
 *
 * @return The identification of the permission to remove.
 */
QString SqsRemovePermissionRequest::label() const
{
    return parameter(LABEL).toString();
}
示例#2
0
int tex_font_metric_rep::x_height () { return parameter (4); }
示例#3
0
int tex_font_metric_rep::spc_extra () { return parameter (6); }
void Interpreter::handleLoadParams()
{
    DBG("loading...");
    uint i;
    char *id, *desc;
    uint32_t len;
    uint32_t flags;
    int response, res;
    uint8_t *data, *argList;
    int running;

    // if we're running, stop so this doesn't take too long....
    // (ie it would proceed with 1 property to returned frame, which could take 1 second or 2)
    running = m_running;
    if (running==1) // only if we're running and not in forced state (running==2)
        sendStop();

    for (i=0; true; i++)
    {
        QString category;

        res = m_chirp->callSync(m_getAll_param, UINT16(i), END_OUT_ARGS, &response, &flags, &argList, &id, &desc, &len, &data, END_IN_ARGS);
        if (res<0)
            break;

        if (response<0)
            break;

        QString sdesc(desc);
        Parameter parameter(id, (PType)argList[0]);
        parameter.setProperty(PP_FLAGS, flags);
        handleProperties(argList, &parameter, &sdesc);
        parameter.setHelp(sdesc);

        // deal with param category

        if (strlen((char *)argList)>1)
        {
            QByteArray a((char *)data, len);
            parameter.set(a);
        }
        else
        {
            if (argList[0]==CRP_INT8 || argList[0]==CRP_INT16 || argList[0]==CRP_INT32)
            {
                int32_t val = 0;
                Chirp::deserialize(data, len, &val, END);
                parameter.set(val);
            }
            else if (argList[0]==CRP_FLT32)
            {
                float val;
                Chirp::deserialize(data, len, &val, END);
                parameter.set(val);
            }
            else // not sure what to do with it, so we'll save it as binary
            {
                QByteArray a((char *)data, len);
                parameter.set(a);
            }
        }
        // it's changed! (ie, it's been loaded)
        parameter.setDirty(true);
        m_pixyParameters.add(parameter);
    }

    // if we're running, we've stopped, now resume
    if (running==1)
    {
        sendRun();
        m_fastPoll = false; // turn off fast polling...
    }

    DBG("loaded");
    emit paramLoaded();
    sendMonModulesParamChange();
    m_pixyParameters.clean();

}
示例#5
0
int tex_font_metric_rep::spc_stretch () { return parameter (2); }
示例#6
0
void LoopBpmConfidence::configure() {
  _envelope->configure("sampleRate", parameter("sampleRate").toInt(),
                       "attackTime", 10.0,
                       "releaseTime", 10.0);
}
示例#7
0
  /// OaDecomposition method
  double
  OaFeasibilityChecker::performOa(OsiCuts & cs, solverManip &lpManip,
      BabInfo * babInfo, double &cutoff,const CglTreeInfo & info) const
  {
    bool isInteger = true;
    bool feasible = 1;

    OsiSolverInterface * lp = lpManip.si();
    OsiBranchingInformation branch_info(lp,false);
    //int numcols = lp->getNumCols();
    double milpBound = -COIN_DBL_MAX;
    int numberPasses = 0;
    double * nlpSol =  NULL;
    int numberCutsBefore = cs.sizeRowCuts();
   
    while (isInteger && feasible ) {
      numberPasses++;

      //setup the nlp

      //Fix the variable which have to be fixed, after having saved the bounds
      double * colsol = const_cast<double *>(lp->getColSolution());
      branch_info.solution_ = colsol;
      fixIntegers(*nlp_,branch_info, parameters_.cbcIntegerTolerance_,objects_, nObjects_);


      //Now solve the NLP get the cuts, and intall them in the local LP
      nlp_->resolve(txt_id);
      if (post_nlp_solve(babInfo, cutoff)) {
        //nlp solved and feasible
        // Update the cutoff
        double ub = nlp_->getObjValue();
        cutoff = ub > 0 ? ub *(1 - parameters_.cbcCutoffIncrement_) : ub*(1 + parameters_.cbcCutoffIncrement_);
        // Update the lp solver cutoff
        lp->setDblParam(OsiDualObjectiveLimit, cutoff);
      }
      // Get the cuts outer approximation at the current point

      nlpSol = const_cast<double *>(nlp_->getColSolution());

      const double * toCut = (parameter().addOnlyViolated_)?
                             colsol:NULL;
      if(cut_count_ <= maximum_oa_cuts_ && type_ == OA)
        nlp_->getOuterApproximation(cs, nlpSol, 1, toCut,
                                    true);
      else {//if (type_ == Benders)
        nlp_->getBendersCut(cs, parameter().global_);
      }
      if(pol_ == DetectCycles)
        nlp_->getBendersCut(savedCuts_, parameter().global_);

      int numberCuts = cs.sizeRowCuts() - numberCutsBefore;
      cut_count_ += numberCuts;
      if (numberCuts > 0)
        installCuts(*lp, cs, numberCuts);

      lp->resolve();
      double objvalue = lp->getObjValue();
      //milpBound = max(milpBound, lp->getObjValue());
      feasible = (lp->isProvenOptimal() &&
          !lp->isDualObjectiveLimitReached() && (objvalue<cutoff)) ;
      //if value of integers are unchanged then we have to get out
      bool changed = true;//if lp is infeasible we don't have to check anything
      isInteger = 0;
      //	  if(!fixed)//fathom on bounds
      //           milpBound = 1e200;
      if (feasible) {
        changed = isDifferentOnIntegers(*nlp_, objects_, nObjects_,
                                        0.1,
                                        nlp_->getColSolution(), lp->getColSolution());
      }
      if (changed) {
       branch_info.solution_ = lp->getColSolution();
       isInteger = integerFeasible(*lp,branch_info, parameters_.cbcIntegerTolerance_,
                                     objects_, nObjects_);
      }
      else {
        isInteger = 0;
        //	  if(!fixed)//fathom on bounds
         milpBound = 1e200;
      }
#ifdef OA_DEBUG
      printf("Obj value after cuts %g, %d rows\n",lp->getObjValue(),
          numberCuts) ;
#endif
    }
    int num_cuts_now = cs.sizeRowCuts();
    if(pol_ == KeepAll){
      for(int i = numberCutsBefore ; i < num_cuts_now ; i++){
        cs.rowCut(i).setEffectiveness(99.9e99);
      }
    }

#ifdef OA_DEBUG
    debug_.printEndOfProcedureDebugMessage(cs, true, cutoff, milpBound, isInteger, feasible, std::cout);
    std::cout<<"milpBound found: "<<milpBound<<std::endl;
#endif
    return milpBound;
  }
示例#8
0
int Interpret(int, char* [])
{
  MockDb db = {};
  MockDb::_serializer_context_t printer = {};

  const auto f = test::TabFoo{};
  const auto t = test::TabBar{};
  select(t.alpha.as(t.beta));

  serialize(insert_into(t).columns(t.beta, t.gamma), printer).str();
  {
    auto i = insert_into(t).columns(t.gamma, t.beta);
    i.values.add(t.gamma = true, t.beta = "cheesecake");
    serialize(i, printer).str();
    i.values.add(t.gamma = false, t.beta = sqlpp::tvin("coffee"));
    i.values.add(t.gamma = false, t.beta = sqlpp::tvin(std::string()));
    serialize(i, printer).str();
    i.values.add(t.gamma = sqlpp::default_value, t.beta = sqlpp::null);
    serialize(i, printer).str();
  }

  serialize(t.alpha = sqlpp::null, printer).str();
  serialize(t.alpha = sqlpp::default_value, printer).str();
  serialize(t.alpha, printer).str();
  serialize(-t.alpha, printer).str();
  serialize(+t.alpha, printer).str();
  serialize(-(t.alpha + 7), printer).str();
  serialize(t.alpha = 0, printer).str();
  serialize(t.alpha = sqlpp::tvin(0), printer).str();
  serialize(t.alpha == 0, printer).str();
  serialize(t.alpha == sqlpp::tvin(0), printer).str();
  serialize(t.alpha != 0, printer).str();
  serialize(t.gamma != sqlpp::tvin(false), printer).str();
  serialize(t.alpha == 7, printer).str();
  serialize(t.delta = sqlpp::tvin(0), printer).str();
  serialize(t.beta + "kaesekuchen", printer).str();

  serialize(sqlpp::select(), printer).str();
  serialize(sqlpp::select().flags(sqlpp::distinct), printer).str();
  serialize(select(t.alpha, t.beta).flags(sqlpp::distinct), printer).str();
  serialize(select(t.alpha, t.beta), printer).str();
  serialize(select(t.alpha, t.beta).from(t), printer).str();
  serialize(select(t.alpha, t.beta).from(t).where(t.alpha == 3), printer).str();
  serialize(select(t.alpha, t.beta).from(t).where(t.alpha == 3).group_by(t.gamma), printer).str();
  serialize(select(t.alpha, t.beta).from(t).where(t.alpha == 3).group_by(t.gamma).having(t.beta.like("%kuchen")),
            printer).str();
  serialize(select(t.alpha, t.beta)
                .from(t)
                .where(t.alpha == 3)
                .group_by(t.gamma)
                .having(t.beta.like("%kuchen"))
                .order_by(t.beta.asc()),
            printer).str();
  serialize(select(t.alpha, t.beta)
                .from(t)
                .where(t.alpha == 3)
                .group_by(t.gamma)
                .having(t.beta.like("%kuchen"))
                .order_by(t.beta.asc())
                .limit(17)
                .offset(3),
            printer).str();

  serialize(parameter(sqlpp::bigint(), t.alpha), printer).str();
  serialize(parameter(t.alpha), printer).str();
  serialize(t.alpha == parameter(t.alpha), printer).str();
  serialize(t.alpha == parameter(t.alpha) and (t.beta + "gimmick").like(parameter(t.beta)), printer).str();

  serialize(insert_into(t), printer).str();
  serialize(insert_into(f).default_values(), printer).str();
  serialize(insert_into(t).set(t.gamma = true), printer).str();
  // serialize(insert_into(t).set(t.gamma = sqlpp::tvin(false)), printer).str(); cannot test this since gamma cannot be
  // null and a static assert is thrown

  serialize(update(t), printer).str();
  serialize(update(t).set(t.gamma = true), printer).str();
  serialize(update(t).set(t.gamma = true).where(t.beta.in("kaesekuchen", "cheesecake")), printer).str();
  serialize(update(t).set(t.gamma = true).where(t.beta.in()), printer).str();

  serialize(remove_from(t), printer).str();
  serialize(remove_from(t).using_(t), printer).str();
  serialize(remove_from(t).where(t.alpha == sqlpp::tvin(0)), printer).str();
  serialize(remove_from(t).using_(t).where(t.alpha == sqlpp::tvin(0)), printer).str();

  // functions
  serialize(sqlpp::value(7), printer).str();
  serialize(sqlpp::verbatim<sqlpp::integral>("irgendwas integrales"), printer).str();
  serialize(sqlpp::value_list(std::vector<int>({1, 2, 3, 4, 5, 6, 8})), printer).str();
  serialize(exists(select(t.alpha).from(t)), printer).str();
  serialize(any(select(t.alpha).from(t)), printer).str();
  serialize(some(select(t.alpha).from(t)), printer).str();
  serialize(count(t.alpha), printer).str();
  serialize(min(t.alpha), printer).str();
  serialize(max(t.alpha), printer).str();
  serialize(avg(t.alpha), printer).str();
  serialize(sum(t.alpha), printer).str();
  serialize(sqlpp::verbatim_table("whatever"), printer).str();

  // alias
  serialize(t.as(t.alpha), printer).str();
  serialize(t.as(t.alpha).beta, printer).str();

  // select alias
  serialize(select(t.alpha).from(t).where(t.beta > "kaesekuchen").as(t.gamma), printer).str();

  serialize(t.alpha.is_null(), printer).str();

  // join
  serialize(t.inner_join(t.as(t.alpha)).on(t.beta == t.as(t.alpha).beta), printer).str();
  {
    auto inner = t.inner_join(t.as(t.alpha)).on(t.beta == t.as(t.alpha).beta);
    serialize(select(t.alpha).from(inner), printer).str();
  }

  // multi_column
  serialize(multi_column(t.alpha, (t.beta + "cake").as(t.gamma)).as(t.alpha), printer).str();
  serialize(multi_column(all_of(t)).as(t), printer).str();
  serialize(all_of(t).as(t), printer).str();

  // dynamic select
  {
    auto s = dynamic_select(db).dynamic_flags().dynamic_columns().from(t);
    s.selected_columns.add(t.beta);
    s.selected_columns.add(t.gamma);
    serialize(s, printer).str();
  }
  {
    auto s = dynamic_select(db).dynamic_flags().dynamic_columns().from(t);
    s.select_flags.add(sqlpp::distinct);
    s.selected_columns.add(t.beta);
    s.selected_columns.add(t.gamma);
    serialize(s, printer).str();
  }
  {
    // Behold, dynamically constructed queries might compile but be illegal SQL
    auto s = dynamic_select(db).dynamic_flags(sqlpp::distinct).dynamic_columns(t.alpha);
    s.select_flags.add(sqlpp::all);
    s.selected_columns.add(without_table_check(t.beta));
    s.selected_columns.add(without_table_check(t.gamma));
    serialize(s, printer).str();
  }

  // distinct aggregate
  serialize(count(sqlpp::distinct, t.alpha % 7), printer).str();
  serialize(avg(sqlpp::distinct, t.alpha - 7), printer).str();
  serialize(sum(sqlpp::distinct, t.alpha + 7), printer).str();

  serialize(select(all_of(t)).from(t).unconditionally(), printer).str();

  for (const auto& row : db(select(all_of(t)).from(t).unconditionally()))
  {
    serialize(row.alpha, printer);
    serialize(row.beta, printer);
    serialize(row.gamma, printer);
  }

  get_sql_name(t);
  get_sql_name(t.alpha);

  flatten(t.alpha == 7, db);

  auto x = boolean_expression(db, t.alpha == 7);
  x = sqlpp::boolean_expression<MockDb>(t.beta.like("%cheesecake"));
  x = x and boolean_expression(db, t.gamma);
  std::cerr << "----------------------------" << std::endl;
  printer.reset();
  std::cerr << serialize(x, printer).str() << std::endl;

  printer.reset();
  std::cerr << serialize(select(all_of(t)).from(t).where(t.alpha.in(select(f.epsilon).from(f).unconditionally())),
                         printer).str() << std::endl;

  printer.reset();
  std::cerr << serialize(select(all_of(t)).from(t).where(t.alpha.in()), printer).str() << std::endl;

  printer.reset();
  std::cerr << serialize(select(all_of(t)).from(t).where(t.alpha.not_in()), printer).str() << std::endl;

  auto schema = db.attach("lorem");
  auto s = schema_qualified_table(schema, t).as(sqlpp::alias::x);

  printer.reset();
  std::cerr << serialize(select(all_of(s)).from(s).unconditionally(), printer).str() << std::endl;

  printer.reset();
  std::cerr << serialize(sqlpp::case_when(true).then(t.alpha).else_(t.alpha + 1).as(t.beta), printer).str()
            << std::endl;

  return 0;
}
示例#9
0
    GreeterApp::GreeterApp(int &argc, char **argv) : QGuiApplication(argc, argv) {
        // point instance to this
        self = this;

        // Parse arguments
        bool testing = false;

        if (arguments().contains("--test-mode"))
            testing = true;

        // get socket name
        QString socket = parameter(arguments(), "--socket", "");

        // get theme path
        QString themePath = parameter(arguments(), "--theme", "");

        // create view
        m_view = new QQuickView();
        m_view->setResizeMode(QQuickView::SizeRootObjectToView);

        m_view->engine()->addImportPath(IMPORTS_INSTALL_DIR);

        // read theme metadata
        m_metadata = new ThemeMetadata(QString("%1/metadata.desktop").arg(themePath));

        // Translations
        // Components translation
        m_components_tranlator = new QTranslator();
        if (m_components_tranlator->load(QLocale::system(), "", "", COMPONENTS_TRANSLATION_DIR))
            installTranslator(m_components_tranlator);

        // Theme specific translation
        m_theme_translator = new QTranslator();
        if (m_theme_translator->load(QLocale::system(), "", "",
                           QString("%1/%2/").arg(themePath, m_metadata->translationsDirectory())))
            installTranslator(m_theme_translator);

        // get theme config file
        QString configFile = QString("%1/%2").arg(themePath).arg(m_metadata->configFile());

        // read theme config
        m_themeConfig = new ThemeConfig(configFile);

        // create models

        m_sessionModel = new SessionModel();
        m_screenModel = new ScreenModel();
        m_userModel = new UserModel();
        m_proxy = new GreeterProxy(socket);
        m_keyboard = new KeyboardModel();

        if(!testing && !m_proxy->isConnected()) {
            qCritical() << "Cannot connect to the daemon - is it running?";
            exit(EXIT_FAILURE);
        }

        // Set numlock upon start
        if (m_keyboard->enabled()) {
            if (mainConfig.Numlock.get() == MainConfig::NUM_SET_ON)
                m_keyboard->setNumLockState(true);
            else if (mainConfig.Numlock.get() == MainConfig::NUM_SET_OFF)
                m_keyboard->setNumLockState(false);
        }

        m_proxy->setSessionModel(m_sessionModel);

        // connect proxy signals
        QObject::connect(m_proxy, SIGNAL(loginSucceeded()), m_view, SLOT(close()));

        // set context properties
        m_view->rootContext()->setContextProperty("sessionModel", m_sessionModel);
        m_view->rootContext()->setContextProperty("screenModel", m_screenModel);
        m_view->rootContext()->setContextProperty("userModel", m_userModel);
        m_view->rootContext()->setContextProperty("config", *m_themeConfig);
        m_view->rootContext()->setContextProperty("sddm", m_proxy);
        m_view->rootContext()->setContextProperty("keyboard", m_keyboard);

        // get theme main script
        QString mainScript = QString("%1/%2").arg(themePath).arg(m_metadata->mainScript());

        // set main script as source
        m_view->setSource(QUrl::fromLocalFile(mainScript));

        // connect screen update signals
        connect(m_screenModel, SIGNAL(primaryChanged()), this, SLOT(show()));

        show();
    }
示例#10
0
文件: jit.cpp 项目: dmsh/factor
void jit::emit_with_parameter(cell code_template_, cell argument_) {
	data_root<array> code_template(code_template_,parent);
	data_root<object> argument(argument_,parent);
	parameter(argument.value());
	emit(code_template.value());
}
示例#11
0
bool CLyricGetter::ProcessFile(const std::string& tempFile)
{
	std::string xml = "";
	SallyAPI::Network::NETWORK_RETURN errorCode = GetXML(&xml);

	if (errorCode != SallyAPI::Network::SUCCESS)
	{
		SallyAPI::System::CLogger* logger = SallyAPI::Core::CGame::GetLogger();
		logger->Debug("CLyricGetter::ProcessFile::GetXML not successful");
		logger->Debug(errorCode);
		logger->Debug(GetRequestURL());

		switch (errorCode)
		{
		case SallyAPI::Network::ERROR_PREPARE:
			m_strErrorText = "Network preparation failed";
		case SallyAPI::Network::ERROR_OPEN:
			m_strErrorText = "Network open failed";
		case SallyAPI::Network::ERROR_HTTP_TIMEOUT:
			m_strErrorText = "HTTP Timeout";
		case SallyAPI::Network::ERROR_NOTHING_READ:
			m_strErrorText = "Nothing read";
		default:
			break;
		}

		return false;
	}

	if (xml.length() == 0)
	{
		m_strErrorText = "Invalide Server response";
		return false;
	}

	SallyAPI::File::FileHelper::AddLineToFile(tempFile, xml);

	if (!SallyAPI::File::FileHelper::FileExists(tempFile))
	{
		m_strErrorText = "Invalide Server response";
		return false;
	}

	XMLNode xMainNode = XMLNode::parseFile(tempFile.c_str());
	if (xMainNode.isEmpty())
	{
		m_strErrorText = "Invalide Server response";
		return false;
	}

	XMLNode itemGetLyricResult = xMainNode.getChildNode("GetLyricResult");
	if (itemGetLyricResult.isEmpty())
	{
		m_strErrorText = "No Lyric found";
		return false;
	}

	XMLNode lyric = itemGetLyricResult.getChildNode("Lyric");
	if (lyric.isEmpty())
	{
		m_strErrorText = "No Lyric found";
		return false;
	}

	const char* lyricsText = lyric.getText();

	if (lyricsText == NULL)
	{
		m_strErrorText = "No Lyric found";
		return false;
	}

	SallyAPI::GUI::SendMessage::CParameterKeyValue parameter(this->GetId(), lyricsText);
	m_pParent->SendMessageToParent(m_pParent, 0, GUI_APP_LYRICS_LOADED, &parameter);
	return true;
}
示例#12
0
void FadeDetection::configure() {
  _frameRate = parameter("frameRate").toReal();
  _cutoffHigh = parameter("cutoffHigh").toReal();
  _cutoffLow = parameter("cutoffLow").toReal();
  _minLength = parameter("minLength").toReal();
}
示例#13
0
void FadeDetection::configure() {
  _fadeAlgo->configure("frameRate", parameter("frameRate").toReal(),
                       "cutoffHigh", parameter("cutoffHigh").toReal(),
                       "cutoffLow", parameter("cutoffLow").toReal(),
                       "minLength", parameter("minLength").toReal());
}
/**
 * @brief  Get the URL of the Amazon SQS queue to take action on.
 *
 * @return The queue URL, or an empty string if not set.
 */
QString SqsRemovePermissionRequest::queueUrl() const
{
    return parameter(QUEUE_URL).toString();
}
示例#15
0
Expr* PrimInliner::tryInline() {
  // Returns the failure result or the result of the primitive (if the
  // primitive can't fail) if the primitive has been inlined; returns
  // NULL otherwise. If the primitive has been inlined but can't fail,
  // the bci in the MethodDecoder is set to the first instruction after
  // the failure block.
  // NB: The comparisons below should be replaced with pointer comparisons
  // comparing with the appropriate vmSymbol. Should fix this at some point.
  char* name  = _pdesc->name();
  Expr* res = NULL;
  switch (_pdesc->group()) {
    case IntArithmeticPrimitive:
      if (number_of_parameters() == 2) {
        Expr* x = parameter(0);
        Expr* y = parameter(1);
        if (equal(name, "primitiveAdd:ifFail:"))			{ res = smi_ArithmeticOp(tAddArithOp, x, y);	break; }
        if (equal(name, "primitiveSubtract:ifFail:"))			{ res = smi_ArithmeticOp(tSubArithOp, x, y);	break; }
        if (equal(name, "primitiveMultiply:ifFail:"))			{ res = smi_ArithmeticOp(tMulArithOp, x, y);	break; }
        if (equal(name, "primitiveDiv:ifFail:"))			{ res = smi_Div(x, y);				break; }
        if (equal(name, "primitiveMod:ifFail:"))			{ res = smi_Mod(x, y);				break; }
        if (equal(name, "primitiveBitAnd:ifFail:"))			{ res = smi_BitOp(tAndArithOp, x, y);		break; }
        if (equal(name, "primitiveBitOr:ifFail:"))			{ res = smi_BitOp(tOrArithOp , x, y);		break; }
        if (equal(name, "primitiveBitXor:ifFail:"))			{ res = smi_BitOp(tXOrArithOp, x, y);		break; }
        if (equal(name, "primitiveRawBitShift:ifFail:"))		{ res = smi_Shift(x, y);			break; }
      }
      break;
    case IntComparisonPrimitive:
      if (number_of_parameters() == 2) {
        Expr* x = parameter(0);
        Expr* y = parameter(1);
        if (equal(name, "primitiveSmallIntegerEqual:ifFail:"))		{ res = smi_Comparison(EQBranchOp, x, y);	break; }
        if (equal(name, "primitiveSmallIntegerNotEqual:ifFail:"))	{ res = smi_Comparison(NEBranchOp, x, y);	break; }
        if (equal(name, "primitiveLessThan:ifFail:"))			{ res = smi_Comparison(LTBranchOp, x, y);	break; }
        if (equal(name, "primitiveLessThanOrEqual:ifFail:"))		{ res = smi_Comparison(LEBranchOp, x, y);	break; }
        if (equal(name, "primitiveGreaterThan:ifFail:"))		{ res = smi_Comparison(GTBranchOp, x, y);	break; }
        if (equal(name, "primitiveGreaterThanOrEqual:ifFail:"))		{ res = smi_Comparison(GEBranchOp, x, y);	break; }
      }
      break;
    case FloatArithmeticPrimitive:
      break;
    case FloatComparisonPrimitive:
      break;
    case ObjArrayPrimitive:
      if (equal(name, "primitiveIndexedObjectSize"))			{ res = array_size();						break; }
      if (equal(name, "primitiveIndexedObjectAt:ifFail:"))		{ res = array_at_ifFail(ArrayAtNode::object_at);		break; }
      if (equal(name, "primitiveIndexedObjectAt:put:ifFail:"))		{ res = array_at_put_ifFail(ArrayAtPutNode::object_at_put);	break; }
      break;
    case ByteArrayPrimitive:
      if (equal(name, "primitiveIndexedByteSize"))			{ res = array_size();						break; }
      if (equal(name, "primitiveIndexedByteAt:ifFail:"))		{ res = array_at_ifFail(ArrayAtNode::byte_at);			break; }
      if (equal(name, "primitiveIndexedByteAt:put:ifFail:"))		{ res = array_at_put_ifFail(ArrayAtPutNode::byte_at_put);	break; }
      break;
    case DoubleByteArrayPrimitive:
      if (equal(name, "primitiveIndexedDoubleByteSize"))		{ res = array_size();						break; }
      if (equal(name, "primitiveIndexedDoubleByteAt:ifFail:"))		{ res = array_at_ifFail(ArrayAtNode::double_byte_at);		break; }
      if (equal(name, "primitiveIndexedDoubleByteCharacterAt:ifFail:"))	{ res = array_at_ifFail(ArrayAtNode::character_at);		break; }
      if (equal(name, "primitiveIndexedDoubleByteAt:put:ifFail:"))	{ res = array_at_put_ifFail(ArrayAtPutNode::double_byte_at_put);break; }
      break;
    case BlockPrimitive:
      if (strncmp(name, "primitiveValue", 14) == 0) 			{ res = block_primitiveValue();		break; }
      break;
    case NormalPrimitive:
      if (strncmp(name, "primitiveNew", 12) == 0) 			{ res = obj_new();			break; }
      if (equal(name, "primitiveShallowCopyIfFail:ifFail:"))		{ res = obj_shallowCopy();		break; }
      if (equal(name, "primitiveEqual:"))				{ res = obj_equal();			break; }
      if (equal(name, "primitiveClass"))				{ res = obj_class(true);		break; }
      if (equal(name, "primitiveClassOf:"))				{ res = obj_class(false);		break; }
      if (equal(name, "primitiveHash"))					{ res = obj_hash(true);			break; }
      if (equal(name, "primitiveHashOf:"))				{ res = obj_hash(false);		break; }
      if (equal(name, "primitiveProxyByteAt:ifFail:"))			{ res = proxy_byte_at();		break; }
      if (equal(name, "primitiveProxyByteAt:put:ifFail:"))		{ res = proxy_byte_at_put();		break; }
      break;
   default:
      fatal1("bad primitive group %d", _pdesc->group());
      break;
  }
 
  if (CompilerDebug) {
    cout(PrintInlining && (res != NULL))->print("%*sinlining %s %s\n", _scope->depth + 2, "", _pdesc->name(),
						_usingUncommonTrap ? "(unc. failure)" : (_cannotFail ? "(cannot fail)" :  ""));
  }
  if (!_usingUncommonTrap && !_cannotFail) theCompiler->reporter->report_prim_failure(_pdesc);
  return res;
}
示例#16
0
文件: SGD.cpp 项目: sigvebs/VMC2
SGD::SGD() {
    double tPrev, t, step;
    rowvec parameter(2), gradient(2), gradientLocal(2), gradientOld(2), nVar(2);
    double localE;
    int correlationLength;
    long idum;
    writeToFile = false;

    //--------------------------------------------------------------------------
    // MPI
    int myRank, nNodes;
    MPI_Comm_size(MPI_COMM_WORLD, &nNodes);
    MPI_Comm_rank(MPI_COMM_WORLD, &myRank);

    //--------------------------------------------------------------------------
    // Reading data from QD.ini
    if (myRank == 0) {
        cout << "Reading configuration from file " << endl;
        ini INIreader("QD.ini");

        McSamples = (int) INIreader.GetDouble("SGD", "McSamples");
        importanceSampling = INIreader.GetBool("SGD", "importanceSampling");
        thermalization = (int) INIreader.GetDouble("SGD", "thermalization");
        SGDSamples = INIreader.GetInt("SGD", "SGDSamples");

        dim = INIreader.GetInt("SGD", "dim");
        alpha = INIreader.GetDouble("SGD", "alpha");
        beta = INIreader.GetDouble("SGD", "beta");
        w = INIreader.GetDouble("SGD", "w");
        nParticles = INIreader.GetInt("SGD", "nParticles");
        m = INIreader.GetInt("SGD", "m");
        correlationLength = INIreader.GetInt("SGD", "correlationLength");

        usingJastrow = INIreader.GetBool("SGD", "usingJastrow");
        writeToFile = INIreader.GetBool("SGD", "writeToFile");
        fileName = INIreader.GetString("SGD", "fileName");

        fMax = INIreader.GetDouble("SGD", "fMax");
        fMin = INIreader.GetDouble("SGD", "fMin");
        omega = INIreader.GetDouble("SGD", "omega");
        expo = INIreader.GetDouble("SGD", "expo");
        A = INIreader.GetDouble("SGD", "A");
        a = INIreader.GetDouble("SGD", "a");
        maxStep = INIreader.GetDouble("SGD", "maxStep");
    }

    //--------------------------------------------------------------------------
    // Broadcasting data to all nodes.
    if (myRank == 0)
        cout << "Broadcasting data to nodes." << endl;

    MPI_Bcast(&McSamples, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&SGDSamples, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&importanceSampling, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&thermalization, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&dim, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&alpha, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Bcast(&beta, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Bcast(&w, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Bcast(&nParticles, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&usingJastrow, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&m, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&correlationLength, 1, MPI_INT, 0, MPI_COMM_WORLD);

    MPI_Bcast(&fMax, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Bcast(&fMin, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Bcast(&omega, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Bcast(&expo, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Bcast(&A, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Bcast(&a, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Bcast(&maxStep, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);

#if 0
    cout
            << "\t A = " << A
            << "\t a = " << a
            << "\t maxStep = " << maxStep
            << "\t expo = " << expo
            << "\t omega = " << omega
            << "\t fMin = " << fMin
            << "\t fMax = " << fMax
            << endl;
#endif
    //--------------------------------------------------------------------------
    //Initializing and thermalizing walkers.

    if (myRank == 0)
        cout << "Initializing and thermalizing walkers." << endl;

    WaveFunction * walker[m];

    idum = -1 - myRank - time(NULL);

    Orbital *orbital = new QDOrbital(dim, alpha, w);
    Jastrow * jastrow = NULL;
    if (usingJastrow)
        jastrow = new QDJastrow(dim, nParticles, beta);

    Hamiltonian *hamiltonian = new QDHamiltonian(dim, nParticles, w, usingJastrow);
    WaveFunction *wf = new WaveFunction(dim, nParticles, idum, orbital, jastrow, hamiltonian);

    // If we are using brute force sampling we have to calculate 
    // the optimal step length.
    if (!importanceSampling)
        wf->setOptimalStepLength();


    // Thermalizing walker.
    int k = 0;
    int thermCorr = m*correlationLength;

    for (int i = 0; i <= thermalization + thermCorr; i++) {
        for (int j = 0; j < nParticles; j++) {
            if (importanceSampling)
                wf->tryNewPosition(j);
            else
                wf->tryNewPositionBF(j);
        }

        // Storing walker.
        if (i > thermalization) {
            if ((i - thermalization) % (correlationLength) == 0) {
                if (myRank == 999)
                    cout << "k = " << k << endl;
                walker[k] = wf->clone();
                k++;
            }
        }
    }

    /*
     for (int k = 0; k < m; k++) {
            // Giving each walker a unique seed.
            idum = -1 - myRank - time(NULL) - k;
        
            Orbital *orbital = new QDOrbital(dim, alpha, w);
            Jastrow * jastrow = NULL;
            if (usingJastrow)
                jastrow = new QDJastrow(dim, nParticles, beta);

            Hamiltonian *hamiltonian = new QDHamiltonian(dim, nParticles, w, usingJastrow);
            WaveFunction *wf = new WaveFunction(dim, nParticles, idum, orbital, jastrow, hamiltonian);

            // If we are using brute force sampling we have to calculate 
            // the optimal step length.
            if (!importanceSampling)
                wf->setOptimalStepLength();

            // Thermalizing walker.
            for (int i = 0; i < thermalization; i++) {
                for (int j = 0; j < nParticles; j++) {
                    if (importanceSampling)
                        wf->tryNewPosition(j);
                    else
                        wf->tryNewPositionBF(j);
                }
            }

            // Storing walker.
            walker[k] = wf;
        }
     **/
    //--------------------------------------------------------------------------
    ofstream outStream;
    if (myRank == 0) {
        cout << "Starting minimizing process " << endl;
        cout << "SGA samples = " << SGDSamples;
        cout << "\t omega = " << w;
        cout << "\t alpha_0 = " << alpha;
        cout << "\t beta_0 = " << beta;
        cout << endl;

        outStream.open((const char*) &fileName[0]);

        // Writing to file
        outStream << SGDSamples << " " << McSamples << " " << m*nNodes << " " << nParticles << " " << w << endl;
    }
    //--------------------------------------------------------------------------
    tPrev = 0;
    parameter(0) = alpha;
    parameter(1) = beta;
    nVar(0) = 5;
    nVar(1) = 5;
    gradientOld = zeros(1, 2);
    //-------------------------------------------------------------------------- 
    // Starting SGD algortithm.
    //-------------------------------------------------------------------------- 
    for (int sample = 1; sample <= SGDSamples; sample++) {

        // Moving walkers        
        E = 0;
        accepted = 0;
        gradient = zeros(1, 2);
        gradientLocal = zeros(1, 2);

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < McSamples; j++) {
                for (int k = 0; k < nParticles; k++) {
                    if (importanceSampling) {
                        accepted += walker[i]->tryNewPosition(k);
                    } else {
                        accepted += walker[i]->tryNewPositionBF(k);
                    }
                }
                localE = walker[i]->sampleEnergy();
                E += localE; // / nParticles;
                gradient += walker[i]->getVariationGradient();
                gradientLocal += walker[i]->getVariationGradient() * localE;
                //}
            }
        }

        //----------------------------------------------------------------------
        // Collecting results.
        MPI_Allreduce(MPI_IN_PLACE, &E, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
        MPI_Allreduce(MPI_IN_PLACE, &gradient(0), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
        MPI_Allreduce(MPI_IN_PLACE, &gradient(1), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
        MPI_Allreduce(MPI_IN_PLACE, &gradientLocal(0), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
        MPI_Allreduce(MPI_IN_PLACE, &gradientLocal(1), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
        E /= (nNodes * m * McSamples);
        gradient /= (nNodes * m * McSamples);
        gradientLocal /= (nNodes * m * McSamples);

        // The total variational gradient
        gradient = 2 * (gradientLocal - gradient * E);
        //----------------------------------------------------------------------
        // Algoritm for the new step length
        //----------------------------------------------------------------------
        double x = -dot(gradient, gradientOld);
        f = fMin + (fMax - fMin) / (1 - (fMax / fMin) * exp(-x / omega));
        t = tPrev + f;

        if (t < 0)
            t = 0;
        //----------------------------------------------------------------------
        // Printing progress
        if (myRank == 0 && sample % 100) {
            fflush(stdout);
            cout
                    << "SGA cycle = " << sample
                    << "\t alpha = " << parameter(0)
                    << "\t beta = " << parameter(1)
                    << "\t E = " << E
                    << "\t t = " << t
                    << "\t step = " << step
                    << "\xd";
        }

        //----------------------------------------------------------------------
        for (int i = 0; i < 2; i++) {
            if (gradient(i) * gradientOld(i) < 0)
                nVar(i)++;

            // Calulating new step lengths.
#if 0
            step = gradient(i) * a / pow(nVar(i), expo);
            if (fabs(step) > maxStep)
                step *= maxStep / fabs(step);

#else
            // Calculating new step lengths.
            double gamma = a / pow(t + A, expo);
            step = gamma * gradient(i);
            if (fabs(step) > maxStep)
                step *= maxStep / fabs(step);
#endif
            parameter(i) -= step;

            // We don't allow negative parameters
            parameter(i) = abs(parameter(i));
        }

        //----------------------------------------------------------------------
        // Setting the new parameters
        for (int i = 0; i < m; i++)
            walker[i]->setNewVariationalParameters(parameter(0), parameter(1));

        // Writing to file
        if (myRank == 0)
            outStream << parameter(0) << " " << parameter(1) << endl;
        //----------------------------------------------------------------------
        // Storing previous values.
        tPrev = t;
        gradientOld = gradient;
    }

    if (myRank == 0) {
        cout
                << endl
                << "Finished. Ending parameters: "
                << "\t alpha = " << parameter(0)
                << "\t beta = " << parameter(1)
                << "\xd";
        //<< endl;
        outStream.close();
    }
    //--------------------------------------------------------------------------
    // Cleaning up
    //for (int i = 0; i < m; i++)
    //delete walker[i];

}
示例#17
0
// Allocates memory (parameter(), literal(), emit_epilog, emit_with_literal)
void quotation_jit::iterate_quotation() {
  bool stack_frame = stack_frame_p();

  set_position(0);

  if (stack_frame) {
    emit(parent->special_objects[JIT_SAFEPOINT]);
    emit(parent->special_objects[JIT_PROLOG]);
  }

  cell length = array_capacity(elements.untagged());
  bool tail_call = false;

  for (cell i = 0; i < length; i++) {
    set_position(i);
    data_root<object> obj(nth(i), parent);

    switch (obj.type()) {
      case WORD_TYPE:
        // Sub-primitives
        if (to_boolean(obj.as<word>()->subprimitive)) {
          tail_call = emit_subprimitive(obj.value(),     // word
                                        i == length - 1, // tail_call_p
                                        stack_frame);    // stack_frame_p
        }                                                // Everything else
        else if (i == length - 1) {
          emit_epilog(stack_frame);
          tail_call = true;
          word_jump(obj.value());
        } else
          word_call(obj.value());
        break;
      case WRAPPER_TYPE:
        push(obj.as<wrapper>()->object);
        break;
      case BYTE_ARRAY_TYPE:
        // Primitive calls
        if (primitive_call_p(i, length)) {
// On x86-64 and PowerPC, the VM pointer is stored in a register;
// on other platforms, the RT_VM relocation is used and it needs
// an offset parameter
#ifdef FACTOR_X86
          parameter(tag_fixnum(0));
#endif
          parameter(obj.value());
          parameter(false_object);
#ifdef FACTOR_PPC_TOC
          parameter(obj.value());
          parameter(false_object);
#endif
          emit(parent->special_objects[JIT_PRIMITIVE]);

          i++;
        } else
          push(obj.value());
        break;
      case QUOTATION_TYPE:
        // 'if' preceded by two literal quotations (this is why if and ? are
        // mutually recursive in the library, but both still work)
        if (fast_if_p(i, length)) {
          emit_epilog(stack_frame);
          tail_call = true;
          emit_quotation(nth(i));
          emit_quotation(nth(i + 1));
          emit(parent->special_objects[JIT_IF]);
          i += 2;
        } // dip
        else if (fast_dip_p(i, length)) {
          emit_quotation(obj.value());
          emit(parent->special_objects[JIT_DIP]);
          i++;
        } // 2dip
        else if (fast_2dip_p(i, length)) {
          emit_quotation(obj.value());
          emit(parent->special_objects[JIT_2DIP]);
          i++;
        } // 3dip
        else if (fast_3dip_p(i, length)) {
          emit_quotation(obj.value());
          emit(parent->special_objects[JIT_3DIP]);
          i++;
        } else
          push(obj.value());
        break;
      case ARRAY_TYPE:
        // Method dispatch
        if (mega_lookup_p(i, length)) {
          tail_call = true;
          emit_mega_cache_lookup(nth(i), untag_fixnum(nth(i + 1)), nth(i + 2));
          i += 3;
        } // Non-optimizing compiler ignores declarations
        else if (declare_p(i, length))
          i++;
        else
          push(obj.value());
        break;
      default:
        push(obj.value());
        break;
    }
  }

  if (!tail_call) {
    set_position(length);
    emit_epilog(stack_frame);
    emit(parent->special_objects[JIT_RETURN]);
  }
}
示例#18
0
GLProgram *GLCompiler::make( )
{
    bool errors= false;
    bool shaders= false;
    for(unsigned int i= 0; i < GLProgram::SHADERTYPE_LAST; i++)
    {
        if(sources[i].source.empty()) continue;
        
        // construit le source
        shaders= true;
        sources[i].build= build_source(i);
        
        // cree le program
        if(program == GLProgram::null())
            program= (new GLProgram(program_label))->create();
        
        // cree le shader
        GLuint shader= program->shaders[i];
        if(shader == 0)
        {
            shader= glCreateShader(GLProgram::types[i]);
            glAttachShader(program->name, shader);
            program->shaders[i]= shader;
        }
        
        // compile le shader
        const char *text[]= { sources[i].build.c_str() };
        glShaderSource(shader, 1, text, NULL);
        glCompileShader(shader);
        
        GLint status= 0;
        glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
        if(status == GL_FALSE)
        {
            errors= true;
            GLint length= 0;
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
            if(length > 0)
            {
                char *log= new char[length +1];
                glGetShaderInfoLog(shader, length, NULL, log);
                ERROR("error compiling %s shader:\n", GLProgram::labels[i]);
                printErrors(log, sources[i]);
                ERROR("shader defines:\n%s\n", sources[i].definitions.c_str());
                delete [] log;
            }
            else
                MESSAGE("error compiling %s shader: no log. failed.\n", GLProgram::labels[i]);
        }
        
        #if 0
        {
            GLint length= 0;
            glGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &length);
            if(length > 0)
            {
                char log[4096];
                glGetShaderSource(shader, sizeof(log), NULL, log);
                DEBUGLOG("shader:\n%s\n", log);
            }
        }
        #endif
    }
    
    if(shaders == false || program == GLProgram::null())
    {
        ERROR("no shader. failed.\n");
        return program;
    }
    
    if(errors == true)
    {
        program->resources();
        program->errors= true;
        return program;
    }
    
    // link
    GLint status= 0;
    glLinkProgram(program->name);
    glGetProgramiv(program->name, GL_LINK_STATUS, &status);
    if(status == GL_FALSE)
    {
        GLint length= 0;
        glGetProgramiv(program->name, GL_INFO_LOG_LENGTH, &length);
        if(length > 0)
        {
            char *log= new char[length +1];
            glGetProgramInfoLog(program->name, length, NULL, log);
            MESSAGE("error linking program:\n%s\nfailed.\n", log);
            delete [] log;
        }
        else
            MESSAGE("error linking program: no log. failed.\n");
        
        program->errors= true;

        return program;
    }
    
    //~ #ifdef GK_OPENGL4
    #if 0
    {
        // interface matching
        // introspection opengl >= 4.3
        // recompile chaque shader dans un program separe et recupere les varyings avec queryinterface(program_inputs / program_outputs)...
        
        std::vector<parameter> stage_inputs[GLProgram::SHADERTYPE_LAST];
        std::vector<parameter> stage_outputs[GLProgram::SHADERTYPE_LAST];
        
        for(unsigned int i= 0; i < GLProgram::SHADERTYPE_LAST; i++)
        {
            if(program->shaders[i] == 0)
                continue;
            
            // recupere le source du shader
            GLint stage_length= 0;
            glGetShaderiv(program->shaders[i], GL_SHADER_SOURCE_LENGTH, &stage_length);
            std::vector<GLchar> stage_source(stage_length +1);
            glGetShaderSource(program->shaders[i], stage_source.size(), NULL, &stage_source.front());

            // construit un program pipeline avec uniquement ce shader
            const GLchar *sources[]= { &stage_source.front() };
            GLuint stage= glCreateShader(GLProgram::types[i]);
            glShaderSource(stage, 1, sources, NULL);
            glCompileShader(stage);
            
            GLuint pipeline= glCreateProgram();
            glProgramParameteri(pipeline, GL_PROGRAM_SEPARABLE, GL_TRUE);
            glAttachShader(pipeline, stage);
            glLinkProgram(pipeline);
            glValidateProgram(pipeline);
            
            // recupere les varyings in / out
            GLint inputs;
            glGetProgramInterfaceiv(pipeline, GL_PROGRAM_INPUT, GL_ACTIVE_RESOURCES, &inputs);
            for(int k= 0; k < inputs; k++)
            {
                GLenum properties[3]= { GL_TYPE, GL_LOCATION, GL_LOCATION_COMPONENT };
                GLint values[3]= { 0, -1, -1 };
                glGetProgramResourceiv(pipeline, GL_PROGRAM_INPUT, k, 3, properties, 3, NULL, values);
                
                GLchar name[4096]= { 0 };
                glGetProgramResourceName(pipeline, GL_PROGRAM_INPUT, k, sizeof(name), NULL, name);
                
                stage_inputs[i].push_back( parameter(name, k, values[0], values[1], -1, values[2]) );
            }
            std::stable_sort(stage_inputs[i].begin(), stage_inputs[i].end());
            
            GLint outputs;
            glGetProgramInterfaceiv(pipeline, GL_PROGRAM_OUTPUT, GL_ACTIVE_RESOURCES, &outputs);
            for(int k= 0; k < outputs; k++)
            {
                GLenum properties[4]= { GL_TYPE, GL_LOCATION, GL_LOCATION_INDEX, GL_LOCATION_COMPONENT };
                GLint values[4]= { 0, -1, -1, -1 };
                glGetProgramResourceiv(pipeline, GL_PROGRAM_OUTPUT, k, 4, properties, 4, NULL, values);
                
                GLchar name[4096]= { 0 };
                glGetProgramResourceName(pipeline, GL_PROGRAM_OUTPUT, k, sizeof(name), NULL, name);
                
                stage_outputs[i].push_back( parameter(name, k, values[0], values[1], values[2], values[3]) );
            }
            std::stable_sort(stage_outputs[i].begin(), stage_outputs[i].end());
            
            // nettoyage
            glDeleteShader(stage);
            glDeleteProgram(pipeline);
        }
        
        // affichage : les sorties d'un shader doivent correspondre aux entrees du shader suivant dans le pipeline
        printf("program interfaces...\n");
        for(unsigned int i= 0; i < GLProgram::SHADERTYPE_LAST; i++)
        {
            if(stage_inputs[i].size())
            {
                printf("  %s shader inputs:\n", GLProgram::labels[i]);
                for(unsigned int k= 0; k < stage_inputs[i].size(); k++)
                {
                    const char *type= glsl::type_string(stage_inputs[i][k].type);
                    if(type)
                        printf("    %02d/-1: '%s', type '%s'\n", 
                            stage_inputs[i][k].location, stage_inputs[i][k].name.c_str(), type);
                    else
                        printf("    %02d/-1: '%s', type 0x%x\n", 
                            stage_inputs[i][k].location, stage_inputs[i][k].name.c_str(), stage_inputs[i][k].type);
                }
            }
            
            if(stage_outputs[i].size())
            {
                printf("  %s shader outputs:\n", GLProgram::labels[i]);
                for(unsigned int k= 0; k < stage_outputs[i].size(); k++)
                {
                    const char *type= glsl::type_string(stage_outputs[i][k].type);
                    if(type)
                        printf("    %02d/%02d: '%s', type '%s'\n", 
                            stage_outputs[i][k].location, stage_outputs[i][k].location_index, stage_outputs[i][k].name.c_str(), type);
                    else
                        printf("    %02d/%02d: '%s', type 0x%x\n", 
                            stage_outputs[i][k].location, stage_outputs[i][k].location_index, stage_outputs[i][k].name.c_str(), stage_outputs[i][k].type);
                }
            }
            
            //! \todo verification des interfaces
        }
    }
    #endif
    
    program->resources();
    program->errors= false;
    
    MESSAGE("done.\n");
    return program;
}
示例#19
0
void LoopBpmConfidence::compute() {
  const Real& bpmEstimate = _bpmEstimate.get();
  Real& confidence = _confidence.get();

  if (bpmEstimate == 0){
    // if estimated bpm is 0, we already know that the confidence will be 0
    confidence = 0.0;
  } else {
    const vector<Real>& signal = _signal.get();

    // Get original duration
    int duration_samples = signal.size();

    // Compute envelope
    vector<Real> envelope;
    _envelope->input("signal").set(signal);
    _envelope->output("signal").set(envelope);
    _envelope->compute();

    // Compute threshold
    Real threshold = *std::max_element(envelope.begin(), envelope.end()) * 0.05;

    // Find start position
    int start_position = 0;
    for (int i=0; i<envelope.size(); i++){
      if (envelope[i] >= threshold){
        start_position = i;
        break;
      }
    }

    // Find end position
    int end_position = 0;
    for (int i=envelope.size() - 1; i>=0; i--){
      if (envelope[i] >= threshold){
        end_position = i;
        break;
      }
    }

    // Build vector with all durations to check
    std::vector<int> durations_to_check;
    durations_to_check.resize(4);
    durations_to_check[0] = duration_samples;
    durations_to_check[1] = duration_samples - start_position;
    durations_to_check[2] = end_position;
    durations_to_check[3] = end_position - start_position;

    // Check all durations
    std::vector<Real> confidences;
    confidences.resize(4);
    Real beatDuration = (60.0 * parameter("sampleRate").toReal()) / bpmEstimate;
    Real lambdaThreshold = beatDuration * 0.5;
    for (int i=0; i<durations_to_check.size(); i++){
      int duration = durations_to_check[i];
      int minDistance = duration_samples; // Set maximum duration
      for (int j=1; j<128; j++) { // Iterate over possible beat lengths (1-127)
        int nBeatDuration = (int)round(beatDuration * j);
        int distance = abs(duration - nBeatDuration);
        if (distance < minDistance) {
          minDistance = distance;
        }
      }
      if (minDistance > lambdaThreshold) {
        confidences[i] = 0.0;
      } else {
        confidences[i] = 1.0 - (Real)minDistance / lambdaThreshold;
      }
    }  
    confidence = *std::max_element(confidences.begin(), confidences.end());
  }
}
示例#20
0
void MultiPitchKlapuri::configure() {

  _sampleRate                = parameter("sampleRate").toReal();
  _frameSize                 = parameter("frameSize").toInt();
  _hopSize                   = parameter("hopSize").toInt();
  _referenceFrequency        = parameter("referenceFrequency").toReal();
  _binResolution             = parameter("binResolution").toReal();
  _numberHarmonics           = parameter("numberHarmonics").toInt();

  Real magnitudeThreshold   = parameter("magnitudeThreshold").toReal();
  Real magnitudeCompression = parameter("magnitudeCompression").toReal();
  Real harmonicWeight       = parameter("harmonicWeight").toReal();
  Real minFrequency         = parameter("minFrequency").toReal();
  Real maxFrequency         = parameter("maxFrequency").toReal();

  _numberHarmonicsMax        = floor(_sampleRate / maxFrequency);
  _numberHarmonicsMax        = min(_numberHarmonics, _numberHarmonicsMax);
  
  _binsInSemitone      = floor(100.0 / _binResolution);
  _centToHertzBase     = pow(2, _binResolution / 1200.0);
  _binsInOctave        = 1200.0 / _binResolution;
  _referenceTerm       = 0.5 - _binsInOctave * log2(_referenceFrequency);

  _numberBins = frequencyToCentBin(_sampleRate/2);
  _centSpectrum.resize(_numberBins);

  string windowType = "hann";
  _zeroPaddingFactor = 4;
  int maxSpectralPeaks = 100;

  // Pre-processing
  _frameCutter->configure("frameSize", _frameSize,
                          "hopSize", _hopSize,
                          "startFromZero", false);

  _windowing->configure("size", _frameSize,
                        "zeroPadding", (_zeroPaddingFactor-1) * _frameSize,
                        "type", windowType);
  // Spectral peaks
  _spectrum->configure("size", _frameSize * _zeroPaddingFactor);


  _spectralPeaks->configure(
              "minFrequency", 1,  // to avoid zero frequencies
              "maxFrequency", 20000,
              "maxPeaks", maxSpectralPeaks,
              "sampleRate", _sampleRate,
              "magnitudeThreshold", 0,
              "orderBy", "magnitude");
  
  // Spectral whitening
  _spectralWhitening->configure("sampleRate", _sampleRate);
  
  // Pitch salience contours
  _pitchSalienceFunction->configure("binResolution", _binResolution,
                  "referenceFrequency", _referenceFrequency,
                  "magnitudeThreshold", magnitudeThreshold,
                  "magnitudeCompression", magnitudeCompression,
                  "numberHarmonics", _numberHarmonics,
                  "harmonicWeight", harmonicWeight);

  // pitch salience function peaks are considered F0 cadidates -> limit to considered frequency range
  _pitchSalienceFunctionPeaks->configure("binResolution", _binResolution,
                     "referenceFrequency", _referenceFrequency,
                     "minFrequency", minFrequency,
                     "maxFrequency", maxFrequency);
}
示例#21
0
  // Write image response
  void writeImage( QgsServerResponse &response, QImage &img, const QString &formatStr,
                   int imageQuality )
  {
    ImageOutputFormat outputFormat = parseImageFormat( formatStr );
    QImage  result;
    QString saveFormat;
    QString contentType;
    switch ( outputFormat )
    {
      case PNG:
        result = img;
        contentType = "image/png";
        saveFormat = "PNG";
        break;
      case PNG8:
      {
        QVector<QRgb> colorTable;
        medianCut( colorTable, 256, img );
        result = img.convertToFormat( QImage::Format_Indexed8, colorTable,
                                      Qt::ColorOnly | Qt::ThresholdDither |
                                      Qt::ThresholdAlphaDither | Qt::NoOpaqueDetection );
      }
      contentType = "image/png";
      saveFormat = "PNG";
      break;
      case PNG16:
        result = img.convertToFormat( QImage::Format_ARGB4444_Premultiplied );
        contentType = "image/png";
        saveFormat = "PNG";
        break;
      case PNG1:
        result = img.convertToFormat( QImage::Format_Mono,
                                      Qt::MonoOnly | Qt::ThresholdDither |
                                      Qt::ThresholdAlphaDither | Qt::NoOpaqueDetection );
        contentType = "image/png";
        saveFormat = "PNG";
        break;
      case JPEG:
        result = img;
        contentType = "image/jpeg";
        saveFormat = "JPEG";
        break;
      default:
        QgsMessageLog::logMessage( QString( "Unsupported format string %1" ).arg( formatStr ) );
        saveFormat = UNKN;
        break;
    }

    if ( outputFormat != UNKN )
    {
      response.setHeader( "Content-Type", contentType );
      if ( saveFormat == "JPEG" )
      {
        result.save( response.io(), qPrintable( saveFormat ), imageQuality );
      }
      else
      {
        result.save( response.io(), qPrintable( saveFormat ) );
      }
    }
    else
    {
      QgsWmsParameter parameter( QgsWmsParameter::FORMAT );
      parameter.mValue = formatStr;
      throw QgsBadRequestException( QgsServiceException::OGC_InvalidFormat,
                                    parameter );
    }
  }
示例#22
0
    GreeterApp::GreeterApp(int &argc, char **argv) : QGuiApplication(argc, argv) {
        // point instance to this
        self = this;

        // Parse arguments
        bool testing = false;

        if (arguments().contains(QStringLiteral("--test-mode")))
            testing = true;

        // get socket name
        QString socket = parameter(arguments(), QStringLiteral("--socket"), QString());

        // get theme path (fallback to internal theme)
        m_themePath = parameter(arguments(), QStringLiteral("--theme"), QString());
        if (m_themePath.isEmpty())
            m_themePath = QLatin1String("qrc:/theme");

        // read theme metadata
        m_metadata = new ThemeMetadata(QStringLiteral("%1/metadata.desktop").arg(m_themePath));

        // Translations
        // Components translation
        m_components_tranlator = new QTranslator();
        if (m_components_tranlator->load(QLocale::system(), QString(), QString(), QStringLiteral(COMPONENTS_TRANSLATION_DIR)))
            installTranslator(m_components_tranlator);

        // Theme specific translation
        m_theme_translator = new QTranslator();
        if (m_theme_translator->load(QLocale::system(), QString(), QString(),
                           QStringLiteral("%1/%2/").arg(m_themePath, m_metadata->translationsDirectory())))
            installTranslator(m_theme_translator);

        // get theme config file
        QString configFile = QStringLiteral("%1/%2").arg(m_themePath).arg(m_metadata->configFile());

        // read theme config
        m_themeConfig = new ThemeConfig(configFile);

        // set default icon theme from greeter theme
        if (m_themeConfig->contains(QStringLiteral("iconTheme")))
            QIcon::setThemeName(m_themeConfig->value(QStringLiteral("iconTheme")).toString());

        // create models

        m_sessionModel = new SessionModel();
        m_userModel = new UserModel();
        m_proxy = new GreeterProxy(socket);
        m_keyboard = new KeyboardModel();

        if(!testing && !m_proxy->isConnected()) {
            qCritical() << "Cannot connect to the daemon - is it running?";
            exit(EXIT_FAILURE);
        }

        // Set numlock upon start
        if (m_keyboard->enabled()) {
            if (mainConfig.Numlock.get() == MainConfig::NUM_SET_ON)
                m_keyboard->setNumLockState(true);
            else if (mainConfig.Numlock.get() == MainConfig::NUM_SET_OFF)
                m_keyboard->setNumLockState(false);
        }

        m_proxy->setSessionModel(m_sessionModel);

        // create views
        QList<QScreen *> screens = primaryScreen()->virtualSiblings();
        Q_FOREACH (QScreen *screen, screens)
            addViewForScreen(screen);

        // handle screens
        connect(this, &GreeterApp::screenAdded, this, &GreeterApp::addViewForScreen);
        connect(this, &GreeterApp::primaryScreenChanged, this, [this](QScreen *) {
            activatePrimary();
        });
    }
示例#23
0
int tex_font_metric_rep::spc () { return parameter (1); }
示例#24
0
parameter fpa_decl_plugin::translate(parameter const & p, decl_plugin & target) {
    SASSERT(p.is_external());
    fpa_decl_plugin & _target = static_cast<fpa_decl_plugin&>(target);
    return parameter(_target.mk_id(m_values[p.get_ext_id()]), true);
}
示例#25
0
int tex_font_metric_rep::spc_shrink () { return parameter (3); }
示例#26
0
func_decl * fpa_decl_plugin::mk_to_fp(decl_kind k, unsigned num_parameters, parameter const * parameters,
                                        unsigned arity, sort * const * domain, sort * range) {
    if (m_bv_plugin && arity == 3 &&
        is_sort_of(domain[0], m_bv_fid, BV_SORT) &&
        is_sort_of(domain[1], m_bv_fid, BV_SORT) &&
        is_sort_of(domain[2], m_bv_fid, BV_SORT)) {
        // 3 BVs -> 1 FP
        unsigned ebits = domain[1]->get_parameter(0).get_int();
        unsigned sbits = domain[2]->get_parameter(0).get_int() + 1;
        parameter ps[] = { parameter(ebits), parameter(sbits) };
        sort * fp = mk_float_sort(ebits, sbits);
        symbol name("to_fp");
        return m_manager->mk_func_decl(name, arity, domain, fp, func_decl_info(m_family_id, k, 2, ps));
    }
    else if (m_bv_plugin && arity == 1 && is_sort_of(domain[0], m_bv_fid, BV_SORT)) {
        // 1 BV -> 1 FP
        if (num_parameters != 2)
            m_manager->raise_exception("invalid number of parameters to to_fp");
        if (!parameters[0].is_int() || !parameters[1].is_int())
            m_manager->raise_exception("invalid parameter type to to_fp");

        int ebits = parameters[0].get_int();
        int sbits = parameters[1].get_int();

        if (domain[0]->get_parameter(0).get_int() != (ebits + sbits))
            m_manager->raise_exception("sort mismatch; invalid bit-vector size, expected bitvector of size (ebits+sbits)");

        sort * fp = mk_float_sort(ebits, sbits);
        symbol name("to_fp");
        return m_manager->mk_func_decl(name, arity, domain, fp, func_decl_info(m_family_id, k, num_parameters, parameters));
    }
    else if (m_bv_plugin && arity == 2 &&
             is_sort_of(domain[0], m_family_id, ROUNDING_MODE_SORT) &&
             is_sort_of(domain[1], m_bv_fid, BV_SORT)) {
        // RoundingMode + 1 BV -> 1 FP
        if (num_parameters != 2)
            m_manager->raise_exception("invalid number of parameters to to_fp");
        if (!parameters[0].is_int() || !parameters[1].is_int())
            m_manager->raise_exception("invalid parameter type to to_fp");
        int ebits = parameters[0].get_int();
        int sbits = parameters[1].get_int();

        sort * fp = mk_float_sort(ebits, sbits);
        symbol name("to_fp");
        return m_manager->mk_func_decl(name, arity, domain, fp, func_decl_info(m_family_id, k, num_parameters, parameters));
    }
    else if (arity == 2 &&
             is_sort_of(domain[0], m_family_id, ROUNDING_MODE_SORT) &&
             is_sort_of(domain[1], m_family_id, FLOATING_POINT_SORT)) {
        // Rounding + 1 FP -> 1 FP
        if (num_parameters != 2)
            m_manager->raise_exception("invalid number of parameters to to_fp");
        if (!parameters[0].is_int() || !parameters[1].is_int())
            m_manager->raise_exception("invalid parameter type to to_fp");
        int ebits = parameters[0].get_int();
        int sbits = parameters[1].get_int();
        if (!is_rm_sort(domain[0]))
            m_manager->raise_exception("sort mismatch, expected first argument of RoundingMode sort");
        if (!is_sort_of(domain[1], m_family_id, FLOATING_POINT_SORT))
            m_manager->raise_exception("sort mismatch, expected second argument of FloatingPoint sort");

        sort * fp = mk_float_sort(ebits, sbits);
        symbol name("to_fp");
        return m_manager->mk_func_decl(name, arity, domain, fp, func_decl_info(m_family_id, k, num_parameters, parameters));
    }
    else if (arity == 3 &&
        is_sort_of(domain[0], m_family_id, ROUNDING_MODE_SORT) &&
        is_sort_of(domain[1], m_arith_fid, REAL_SORT) &&
        is_sort_of(domain[2], m_arith_fid, INT_SORT))
    {
        // Rounding +  1 Real + 1 Int -> 1 FP
        if (!(num_parameters == 2 && parameters[0].is_int() && parameters[1].is_int()))
            m_manager->raise_exception("expecting two integer parameters to to_fp");

        sort * fp = mk_float_sort(parameters[0].get_int(), parameters[1].get_int());
        symbol name("to_fp");
        return m_manager->mk_func_decl(name, arity, domain, fp, func_decl_info(m_family_id, k, num_parameters, parameters));
    }
    else if (arity == 3 &&
             is_sort_of(domain[0], m_family_id, ROUNDING_MODE_SORT) &&
             is_sort_of(domain[1], m_arith_fid, INT_SORT) &&
             is_sort_of(domain[2], m_arith_fid, REAL_SORT))
    {
        // Rounding +  1 Int + 1 Real -> 1 FP
        if (!(num_parameters == 2 && parameters[0].is_int() && parameters[1].is_int()))
            m_manager->raise_exception("expecting two integer parameters to to_fp");

        sort * fp = mk_float_sort(parameters[0].get_int(), parameters[1].get_int());
        symbol name("to_fp");
        return m_manager->mk_func_decl(name, arity, domain, fp, func_decl_info(m_family_id, k, num_parameters, parameters));
    }
    else if (arity == 1 &&
             is_sort_of(domain[0], m_arith_fid, REAL_SORT))
    {
        // 1 Real -> 1 FP
        if (!(num_parameters == 2 && parameters[0].is_int() && parameters[1].is_int()))
            m_manager->raise_exception("expecting two integer parameters to to_fp");
        if (domain[1] != m_real_sort)
            m_manager->raise_exception("sort mismatch, expected one argument of Real sort");

        sort * fp = mk_float_sort(parameters[0].get_int(), parameters[1].get_int());
        symbol name("to_fp");
        return m_manager->mk_func_decl(name, arity, domain, fp, func_decl_info(m_family_id, k, num_parameters, parameters));
    }
    else if (arity == 2 &&
             is_sort_of(domain[0], m_family_id, ROUNDING_MODE_SORT) &&
             is_sort_of(domain[1], m_arith_fid, REAL_SORT))
    {
        // Rounding + 1 Real -> 1 FP
        if (!(num_parameters == 2 && parameters[0].is_int() && parameters[1].is_int()))
            m_manager->raise_exception("expecting two integer parameters to to_fp");

        sort * fp = mk_float_sort(parameters[0].get_int(), parameters[1].get_int());
        symbol name("to_fp");
        return m_manager->mk_func_decl(name, arity, domain, fp, func_decl_info(m_family_id, k, num_parameters, parameters));
    }
    else if (arity == 2 &&
             is_sort_of(domain[0], m_family_id, ROUNDING_MODE_SORT) &&
             is_sort_of(domain[1], m_arith_fid, INT_SORT)) {
        // Rounding + 1 Int -> 1 FP
        if (!(num_parameters == 2 && parameters[0].is_int() && parameters[1].is_int()))
            m_manager->raise_exception("expecting two integer parameters to to_fp");

        sort * fp = mk_float_sort(parameters[0].get_int(), parameters[1].get_int());
        symbol name("to_fp");
        return m_manager->mk_func_decl(name, arity, domain, fp, func_decl_info(m_family_id, k, num_parameters, parameters));
    }
    else {
        m_manager->raise_exception("Unexpected argument combination for (_ to_fp eb sb). Supported argument combinations are: "
                                   "((_ BitVec 1) (_ BitVec eb) (_ BitVec sb-1)), "
                                   "(_ BitVec (eb+sb)), "
                                   "(Real), "
                                   "(RoundingMode (_ BitVec (eb+sb))), "
                                   "(RoundingMode (_ FloatingPoint eb' sb')), "
                                   "(RoundingMode Int Real), "
                                   "(RoundingMode Real Int), "
                                   "(RoundingMode Int), and "
                                   "(RoundingMode Real)."
                                   );
    }

    return nullptr;
}
示例#27
0
int tex_font_metric_rep::spc_quad () { return parameter (5); }
示例#28
0
sort * fpa_util::mk_float_sort(unsigned ebits, unsigned sbits) {
    parameter ps[2] = { parameter(ebits), parameter(sbits) };
    return m().mk_sort(m_fid, FLOATING_POINT_SORT, 2, ps);
}
示例#29
0
文件: request.hpp 项目: aldrin/cpp
 template <typename T> T parameter_as(const std::string &k) const
 { return boost::lexical_cast<T>(parameter(k)); }
示例#30
0
AlgorithmStatus MetadataReader::process() {
  if (_filename == "" || !_newlyConfigured) return PASS;

  TagLib::FileRef f(_filename.c_str());

  //Pool tagPool;

  if (f.isNull()) {
    // in case TagLib can't get metadata out of this file, try some basic PCM approach
    int pcmSampleRate = 0;
    int pcmChannels = 0;
    int pcmBitrate = 0;

    try {
      pcmMetadata(_filename, pcmSampleRate, pcmChannels, pcmBitrate);
    }
    catch (EssentiaException& e) {
      if (parameter("failOnError").toBool())
        throw EssentiaException("MetadataReader: File does not exist or does not seem to be of a supported filetype. ", e.what());
    }
    string ns = "";
    _title.push(ns);
    _artist.push(ns);
    _album.push(ns);
    _comment.push(ns);
    _genre.push(ns);
    _track.push(ns);
    _date.push(ns);
    //_tagPool.push(tagPool);
    _duration.push(0);
    _bitrate.push(pcmBitrate);
    _sampleRate.push(pcmSampleRate);
    _channels.push(pcmChannels);
  }
  else {
    TagLib::PropertyMap tags = f.file()->properties();

    _title.push(formatString(tags["TITLE"]));
    _artist.push(formatString(tags["ARTIST"]));
    _album.push(formatString(tags["ALBUM"]));
    _comment.push(formatString(tags["COMMENT"]));
    _genre.push(formatString(tags["GENRE"]));
    _track.push(formatString(tags["TRACKNUMBER"]));
    _date.push(formatString(tags["DATE"]));


    /*
    // populate tag pool
    for(PropertyMap::Iterator it = tags.begin(); it != tags.end(); ++it) {
      for(StringList::Iterator str = it->second.begin(); str != it->second.end(); ++str) {
        tagPool.add(it->first.to8Bit(true), str->to8Bit(true));
      }
    }
    _tagPool.push(tagPool);
    */

    _duration.push((int)f.audioProperties()->length());

    int bitrate = f.audioProperties()->bitrate();
    // fix for taglib incorrectly returning the bitrate for wave files
    string ext = toLower(_filename.substr(_filename.size()-3));
    if (ext == "wav") {
      bitrate = bitrate * 1024 / 1000;
    }

    _bitrate.push((int)bitrate);
    _sampleRate.push((int)f.audioProperties()->sampleRate());
    _channels.push((int)f.audioProperties()->channels());
  }

  _newlyConfigured = false;
  shouldStop(true);
  return OK;
}