Exemplo n.º 1
0
void Task::processTemplate() {
    Template* temp = readTemplate(*_templateName);
    std::vector<string> subtasks = temp->subTaskList();
    int subId = 1;
    for (std::vector<string>::iterator iterSub = subtasks.begin(); iterSub != subtasks.end(); iterSub++) {
        string subtask = *iterSub;
        int posPar = subtask.find('(');
        int posFin = subtask.find(')');

        string tempSub = subtask.substr(posPar + 1, posFin - posPar - 1);
        string subTaskName = subtask.substr(0, posPar);

        Task* sub = new Task(_project);
        std::stringstream ssId;
        ssId << *id() << "." << subId++;
        sub->setId(new string(ssId.str()));
        sub->setDuration(Duration(1, 0, 0));
        sub->setEndDate(endDate());
        sub->setShortDescription(new string(subTaskName));
        sub->setStartDate(startDate());
        sub->setStatus(status());
        sub->setTemplateName(new string(tempSub));

        _project->addTask(sub);
        if (errorOcurred()) {
            return;
        }
        sub->processTemplate();
    }
}
Exemplo n.º 2
0
    float compare(const Template &a, const Template &b) const
    {
        if (a.size() != distances.size() ||
            b.size() != distances.size())
            return -std::numeric_limits<float>::max();

        QList<float> scores;
        for (int i=0; i<distances.size(); i++) {
            float weight;
            weights.isEmpty() ? weight = 1. : weight = weights[i];
            if (weight != 0)
                scores.append(weight*distances[i]->compare(Template(a.file, a[i]),Template(b.file, b[i])));
        }

        switch (operation) {
          case Mean:
            return std::accumulate(scores.begin(),scores.end(),0.0)/(float)scores.size();
            break;
          case Sum:
            return std::accumulate(scores.begin(),scores.end(),0.0);
            break;
          case Min:
            return *std::min_element(scores.begin(),scores.end());
            break;
          case Max:
            return *std::max_element(scores.begin(),scores.end());
            break;
          default:
            qFatal("Invalid operation.");
        }
        return 0;
    }
    void write(const Template &t) const
    {
        QFile f(file);
        QtUtils::touchDir(f);
        if (!f.open(QFile::WriteOnly))
            qFatal("Failed to open %s for writing.", qPrintable(file));

        Mat m;
        if (!raw) {
            if (t.m().type() != CV_32FC1)
                t.m().convertTo(m, CV_32F);
            else m = t.m();

            if (m.channels() != 1) qFatal("Only supports single channel matrices.");

            f.write((const char *) &m.rows, 4);
            f.write((const char *) &m.cols, 4);
        }
        else m =  t.m();

        qint64 rowSize = m.cols * sizeof(float);
        for (int i=0; i < m.rows; i++)
        {
            f.write((const char *) m.row(i).data, rowSize);
        }
        f.close();
    }
Exemplo n.º 4
0
    float compare(const Template &a, const Template &b) const
    {
        QList<int> indices;
        for (int i=0; i<a.size(); i++)
            indices << i;

        QList<float> scores;
        do {
            QList<float> permScores;
            for (int i=0; i<a.size(); i++)
                permScores.append(distance->compare(Template(a.file, a[indices[i]]),Template(b.file, b[i])));
            scores.append(std::accumulate(permScores.begin(),permScores.end(),0.0));
        } while ( next_permutation(indices.begin(),indices.end()) );

        switch (operation) {
          case Mean:
            return std::accumulate(scores.begin(),scores.end(),0.0)/(float)scores.size();
            break;
          case Sum:
            return std::accumulate(scores.begin(),scores.end(),0.0);
            break;
          case Min:
            return *std::min_element(scores.begin(),scores.end());
            break;
          case Max:
            return *std::max_element(scores.begin(),scores.end());
            break;
          default:
            qFatal("Invalid operation.");
        }
        return 0;
    }
Exemplo n.º 5
0
TEST(template_unittest, test_template_efficiency) {
  std::vector<Template *> repos;
  repos.push_back(new Template("1={w0}"));
  repos.push_back(new Template("2={p0}"));
  repos.push_back(new Template("3={w0}-{p0}"));
  repos.push_back(new Template("4={w1}"));
  repos.push_back(new Template("5={p1}"));
  repos.push_back(new Template("6={w1}-{p1}"));

  string payload;
  payload.reserve(128);
  long start_time = clock();
  int kNumRepeats = 1024 * 1024;
  int kNumTemplates = repos.size();

  for (int t = 0; t < 1024 * 1024; ++ t) {
    Template::Data data;
    data.set("w0", "am");
    data.set("p0", "v");
    data.set("w1", "I");
    data.set("p1", "r");
    for (int i = 0; i < repos.size(); ++ i) {
      Template* T = repos[i];
      T->render(data, payload);
    }
  }

  long throughput_per_millisecond = ((kNumRepeats * kNumTemplates)
      / ((clock() -start_time) / 1000));
  std::cout << throughput_per_millisecond << std::endl;
}
Exemplo n.º 6
0
void TestCachingLoader::testRenderAfterError()
{
  Engine engine;
  engine.setPluginPaths(QStringList() << QStringLiteral(GRANTLEE_PLUGIN_PATH));

  QSharedPointer<InMemoryTemplateLoader> loader(new InMemoryTemplateLoader);
  loader->setTemplate(QStringLiteral("template1"),
                      QStringLiteral("This template has an error {{ va>r }}"));
  loader->setTemplate(QStringLiteral("template2"), QStringLiteral("Ok"));
  loader->setTemplate(QStringLiteral("main"),
                      QStringLiteral("{% include template_var %}"));

  QSharedPointer<Grantlee::CachingLoaderDecorator> cache(
      new Grantlee::CachingLoaderDecorator(loader));

  engine.addTemplateLoader(cache);

  Context c;
  Template t;
  t = engine.loadByName(QStringLiteral("main"));

  c.insert(QStringLiteral("template_var"), QLatin1String("template1"));
  QCOMPARE(t->render(&c), QString());
  QCOMPARE(t->error(), TagSyntaxError);

  c.insert(QStringLiteral("template_var"), QLatin1String("template2"));
  QCOMPARE(t->render(&c), QLatin1String("Ok"));
  QCOMPARE(t->error(), NoError);
}
Exemplo n.º 7
0
void DisjointMetadata::load(const ImageInfo &info)
{
    CaptionsMap commentMap;
    CaptionsMap titleMap;

    {
        CoreDbAccess access;
        ImageComments comments = info.imageComments(access);
        commentMap             = comments.toCaptionsMap();
        titleMap               = comments.toCaptionsMap(DatabaseComment::Title);
    }

    Template tref = info.metadataTemplate();
    Template t    = TemplateManager::defaultManager()->findByContents(tref);
    //qCDebug(DIGIKAM_GENERAL_LOG) << "Found Metadata Template: " << t.templateTitle();

    load(info.dateTime(),
         titleMap,
         commentMap,
         info.colorLabel(),
         info.pickLabel(),
         info.rating(),
         t.isNull() ? tref : t);

    QList<int> tagIds = info.tagIds();
    loadTags(tagIds);
}
Exemplo n.º 8
0
string SAMSUser::asString () const
{
  string res = "";
  Template *tpl = TemplateList::getTemplate (this->getCurrentTemplateId());
  if (!tpl)
    {
      WARNING ("User with id " << _id << " lost template");
      return res;
    }

  if (tpl->getAuth() == Proxy::AUTH_IP)
    {
      res = _ip.asString ();
    }
  else
    {
      if (!_domain.empty () && Proxy::useDomain ())
        {
          res = _domain + Proxy::getSeparator ();
        }
      res += _nick;
    }

  return res;
}
Exemplo n.º 9
0
void RequestError::stdException(Request* request, const std::exception& e)
{
#ifndef DEBUG
	if (!request->headersSent())
		request->setStatus(500);
	Template* tpl = new Template("Errors/500.html", nullptr, request);
	tpl->render();
	delete tpl;
	return;
#endif

	/*try
	{
		View tpl = new Template("Sys::Exception.html", nullptr, request);
		tpl["exceptionName"] = (typeid e).name();
		tpl["exceptionMessage"] = e.what();
		tpl["webcppVersion"] = System::get()->version();
		tpl["serverName"] = request->env("SERVER_NAME", "");

		if (!request->headersSent())
			request->setStatus(500);
		tpl->render();
	}
	catch (const Exception& e2)
	{*/ fallbackErrorPage(request, e, ""); /* e, e2.type() */ /*}
	catch (const std::exception& e2)
	{ fallbackErrorPage(request, e, typeid(e2).name()); }*/
}
Exemplo n.º 10
0
janus_error janus_detect(const janus_image image, janus_attributes *attributes_array, const size_t num_requested, size_t *num_actual)
{
    TemplateList src, dst;

    Template t;
    cv::Mat input(image.height,
                  image.width,
                  image.color_space == JANUS_GRAY8 ? CV_8UC1 : CV_8UC3,
                  image.data);

    t.append(input);
    src.append(t);
    detect->project(src, dst);
    *num_actual = dst.size();
    if (dst.size() == 0)
        return JANUS_FAILURE_TO_DETECT;

    // Sort by confidence, descending
    std::sort(dst.begin(), dst.end(), compareConfidence);

    size_t count = 0;
    foreach (const Template &temp, dst) {
        QRectF rect = temp.file.rects().first();
        attributes_array->face_x = rect.x();
        attributes_array->face_y = rect.y();
        attributes_array->face_width = rect.width();
        attributes_array->face_height = rect.height();
        attributes_array->detection_confidence = temp.file.get<float>("Confidence");
        attributes_array++;
        if (++count >= num_requested)
            break;
    }
Exemplo n.º 11
0
bool Task::isClosed() const {
    Template* tpl = readTemplate(*this->templateName());
    if (tpl != NULL) {
        return (tpl->closedStatus()->compare(*_status) == 0);
    } else {
        return false;
    }
}
int main()
{
	Template * pTemplate = new Boy();
	pTemplate->DoFood();
	delete pTemplate;

	return 0;
}
Exemplo n.º 13
0
Template* TemplateMap::getTemplate(const char *text)
{
	for (Template *ptr = entries; ptr != NULL; ptr = ptr->getNext())
		if (ptr->equals(text))
			return ptr;

	return 0;
}
Exemplo n.º 14
0
void NewDocumentWizard::accept()
// ----------------------------------------------------------------------------
//   Copy template into user's document folder
// ----------------------------------------------------------------------------
{
    QString docName = field("docName").toString();
    QString docLocation = field("docLocation").toString();
    QString dstPath = docLocation + "/" + docName;

    QDir dst(dstPath);
    if (dst.exists())
    {
        QString dstPathNative = QDir::toNativeSeparators(dstPath);
        int r = QMessageBox::warning(this, tr("Folder exists"),
                    tr("Document folder:\n%1\nalready exists. "
                       "Do you want to use it anyway (current content "
                       "will be deleted)?\n"
                       "Click No to choose another location.")
                       .arg(dstPathNative),
                       QMessageBox::Yes | QMessageBox::No);
        if (r != QMessageBox::Yes)
            return;
    }

    Template t = templates.at(field("templateIdx").toInt());

    bool ok = t.copyTo(dst);
    if (!ok)
    {
        QMessageBox::warning(this, tr("Error"),
                             tr("Failed to copy document template."));
        return;
    }

    docPath = dstPath;
    if (t.mainFile != "")
    {
        QString oldName = t.mainFile.replace(QRegExp("\\.ddd$"), "");
        QString newName = docName;
        if (oldName != newName)
        {
            // Rename template main file to doc name.
            // We need to remove the destination file if it is there
            QDir dstDir = QDir(dstPath);
            Rename(dstDir, oldName, newName, ".ddd");
            Rename(dstDir, oldName, newName, ".ddd.sig");
            Rename(dstDir, oldName, newName, ".json");
            docPath = dstDir.filePath(newName + ".ddd");
        }
    }

#if !defined(CFG_NOGIT)
    // Create project to avoid prompt when document is first opened
    RepositoryFactory::repository(dstPath, RepositoryFactory::Create);
#endif
    QDialog::accept();
}
Exemplo n.º 15
0
bool Task::AddTemplate(const QString &template_path)
{
	Template *t = new Template();
	if (t && t->Initialize(template_path)) {
		return AddTemplate(t);
	} else {
		return false;
	}
}
Exemplo n.º 16
0
//=============================================================================
// 生成
//=============================================================================
bool Template::Create(Template** outPointer)
{
	Template* pointer = new Template();
	if(!pointer->Initialize())
		return false;

	*outPointer = pointer;
	return true;
}
int main()
{
    Template* t;
    t=new ConcreteClassA(8,2);
    t->templateMethod();
    t=new ConcreteClassB(10,5);
    t->templateMethod();
    return 0;
}
Exemplo n.º 18
0
  void createPageMenus( void )
  {
    // find the menus associated with this page
    siteObject thisSite;
    thisSite.id - site_id;
    thisSite.key(site_id);
    if( thisSite.get_data() )
    {
      Template tmplt;
      tmplt.id = template_id;
      tmplt.key(template_id);
      if( tmplt.get_data() )
      {
        // build a path to the Template
        string fullPath = thisSite.path;
        fullPath += "/Templates/";
        fullPath += tmplt.path;

        cgiTemplates cTemp;
        if( cTemp.load(fullPath.c_str()) )
        {
          // get the control section
          xmlParser parser( cTemp.getParagraph("control") );
          parser.parse();
          node_vector::iterator & it = parser.findFirstNodeByName( "menu" );
          int order=0;
          while( it !=  parser.states.nodes.end() )
          {
            xmlNode & node = *it;
            string open_tag = node.attr["open"];
            string close_tag = node.attr["close"];

            class menu mnu;
            string clause = "reference_template = '";
            clause += tmplt.path;
            clause += "' and template_open_tag = '";
            clause += open_tag;
            clause += "' and  template_close_tag = '";
            clause +=  close_tag;
            clause += "'";

            if( mnu.get_data(clause) )
            {
              page_menus_Obj pg_mnu;
              pg_mnu.site_id = site_id;
              pg_mnu.menu_id = mnu.id;
              pg_mnu.page_id = id;
              pg_mnu.place_order = order++;
              pg_mnu.collapsible = false;
              pg_mnu.db_insert();
            }
            it = parser.findNextNodeByName( "menu" );
          }
        }
      }
    }
  }
Exemplo n.º 19
0
int main() {

	static Template<String> t;


	t.methodThatUsesAnotherMethod();

	return 0;
}
Exemplo n.º 20
0
Template* TemplateMap::getTemplate(const char *text) {
	Template *ptr;
	for (ptr=entries; ptr!=NULL; ptr=ptr->getNext()) {
		if (ptr->equals(text)) {
			break;
		}
	}
	return ptr;
}
Exemplo n.º 21
0
void DialogSettings::loadTemplates() {
    vector<Template*>* templates = readTemplates();
    QStringList list;
    for (vector<Template*>::iterator iter = templates->begin(); iter != templates->end(); iter++) {
        Template* tpl = *iter;
        QString description(tpl->description()->c_str());
        list.append(description);
    }
    ui->templatesList->addItems(list);
}
Exemplo n.º 22
0
    double residualReconstructionError(const Template &src) const
    {
        Template proj;
        project(src, proj);

        Eigen::Map<const Eigen::VectorXf> srcMap(src.m().ptr<float>(), src.m().rows*src.m().cols);
        Eigen::Map<Eigen::VectorXf> projMap(proj.m().ptr<float>(), keep);

        return (srcMap - mean).squaredNorm() - projMap.squaredNorm();
    }
Exemplo n.º 23
0
Template* readTemplate(const string& name) {
    vector<Template*>* templates = readTemplates();
    for (vector<Template*>::iterator it = templates->begin(); it != templates->end(); it++) {
        Template* t = *it;
        if (t->name()->compare(name) == 0) {
            return t;
        }
    }
    return NULL;
}
Exemplo n.º 24
0
void SetupTemplate::setTemplate(const Template& t)
{
    if (!t.isNull())
    {
        TemplateListItem* const item = d->listView->find(t.templateTitle());
        d->listView->setCurrentItem(item);
        return;
    }

    populateTemplate(t);
}
Exemplo n.º 25
0
/*-------------------------------------------*/
int main()
{
	//(char*)(PWD + (string)"Rep_Input.txt").c_str()
	string PWD = getenv("PWD");

	FCComps::write_text = 0;
	FCComps::write_hdf5 = 1;
	
// Get and display special parameters for Reprocess :
	File repInput = "Rep_Input.txt";
	Template temp;
	mapType m;
	m=temp.readFile(repInput);
	SepEffDict sepeff = getSepEff(temp, repInput);

	cout << endl;
	cout << "Separation Efficiency Dictionnary :" << endl;
	cout << endl;
	PrintS(sepeff);
	cout << endl;

	File load = "load.txt";
	FCComps::load_isos2track_text(load);

// Get the MassStream :

	MassStream inStream;	

	if (m["IsosIn_type"].compare("text") == 0)
		{
			//(char*)m["IsosIn"].c_str())
			inStream.load_from_text((char*)m["IsosIn"].c_str());
		}
	else if (m["IsosIn_type"].compare("hdf5") == 0)
		{	
			//m[PWD + "IsosIn"]
			inStream.load_from_hdf5(m["IsosIn"], "/IsosOut");
		}

	inStream.mass = -1;
	inStream.norm_comp_dict();
	
	cout << endl;
	inStream.Print();
	cout << endl;

	Reprocess rep(sepeff,"Rep");
	rep.PassNum = atoi((char*)m["PassNumber"].c_str());
	rep.doCalc(inStream);
	
	rep.writeout();

	return 0;
}
Exemplo n.º 26
0
    void project(const Template &src, Template &dst) const
    {
        dst = cv::Mat(1, keep, CV_32FC1);

        // Map Eigen into OpenCV
        Eigen::Map<const Eigen::MatrixXf> inMap(src.m().ptr<float>(), src.m().rows*src.m().cols, 1);
        Eigen::Map<Eigen::MatrixXf> outMap(dst.m().ptr<float>(), keep, 1);

        // Do projection
        outMap = eVecs.transpose() * (inMap - mean);
    }
Exemplo n.º 27
0
 void projectUpdate(const Template &src, Template &dst)
 {
     dst.file = src.file;
     QList<Mat> mats;
     for (int i=0; i<src.size(); i++) {
         transforms[i%transforms.size()]->projectUpdate(Template(src.file, src[i]), dst);
         mats.append(dst);
         dst.clear();
     }
     dst.append(mats);
 }
Exemplo n.º 28
0
void JSONTest::testTemplate()
{
	Template tpl;
	tpl.parse("Hello world! From <?= person.name ?>\n<?if person.toOld ?>You're too old<?endif?>\n");

	Object::Ptr data = new Object();
	Object::Ptr person = new Object();
	data->set("person", person);
	person->set("name", "Franky");
	person->set("toOld", true);
	tpl.render(data, std::cout);
}
Exemplo n.º 29
0
void PanelView::contentsMouseDoubleClickEvent( QMouseEvent *e )
{
    //qWarning( "PanelView::contentsMouseDoubleClickEvent: %d, %d",
    //        e->pos().x(), e->pos().y() );
    Template * i = NULL;
    if(( i = findItemOnTop( e ) ) != NULL ) {
        // forward mouse event to the template
        i->mouseDoubleClickEvent( e );
        // shedule canvas for repaint
        canvas()->update();
    }
}
Exemplo n.º 30
0
 float compare(const Template &a, const Template &b) const
 {
     uchar *aData = a.m().data;
     uchar *bData = b.m().data;
     if (!a.m().data || !b.m().data) return -std::numeric_limits<float>::max();
     int score, error;
     if      (algorithm == LFML) error = NEC_LFML_Verify(bData, b.m().total(), aData, a.m().total(), &score);
     else if (algorithm == ELFT) error = NEC_ELFT_Verify(bData, aData, &score, 1);
     else                        error = NEC_ELFT_M_Verify(bData, aData, &score, 1);
     if (error)
         qWarning("NECLatent1CompareDistance error %d", error);
     return score;
 }