double RateMeyerHaeseler::computeFunction(double value) {
	if (!rate_mh) {
		if (value != cur_scale) {
			ptn_tree->scaleLength(value/cur_scale);
			cur_scale = value;
			ptn_tree->clearAllPartialLH();
		}
		return -ptn_tree->computeLikelihood();
	}
	int nseq = phylo_tree->leafNum;
	int nstate = phylo_tree->getModel()->num_states;
	int i, j, state1, state2;
	double lh = 0.0;
	ModelSubst *model = phylo_tree->getModel();
	Pattern *pat = & phylo_tree->aln->at(optimizing_pattern);
	
	for (i = 0; i < nseq-1; i++) if ((state1 = pat->at(i)) < nstate) 
		for (j = i+1; j < nseq; j++) if ((state2 = pat->at(j)) < nstate) 
			lh -= log(model->computeTrans(value * dist_mat[i*nseq + j], state1, state2));
	return lh;
}
Example #2
0
void CreateWithPatternCommand::run(World* world)
{
  if(world != NULL){
    Factories<Pattern>& pattern_factories = Factories<Pattern>::getInstance();
    Factories<Command>& command_factories = Factories<Command>::getInstance();

    Factory<Command>* command_factory;
    Factory<Pattern>* pattern_factory = pattern_factories[concrete_type];
    Pattern* pattern;
    Command* command;

    FactoryParams::iterator it = params.begin();

    pattern_factory = pattern_factories[concrete_type];

    //use first string for pattern params
    FactoryParams pattern_params;
    pattern_params.push_back(*it++);
    pattern = pattern_factory->create(pattern_params);

    //use second string for command params
    command_factory = command_factories[*it++];

    //remaining params go to the object to be created
    FactoryParams template_params;
    template_params.insert(template_params.begin(),it,params.end());

    //create objects, tacking on pattern params
    while(!pattern->isEmpty()){
      FactoryParams command_params = template_params;
      FactoryParams pattern_data = pattern->getNext();
      for(size_t i=0; i<pattern_data.size(); ++i){
        command_params.push_back(pattern_data[i]);
      }
      command = command_factory->create(command_params);
      command->run(world);
      delete command;
    }
  }
}
Example #3
0
bool NeuralNet::checkGradient (NNTYPE& E, NNTYPE& E_delta, NNTYPE& E_delta_gradient, const Pattern& pattern, NNTYPE delta, NNTYPE limit)
{

//    m_net.clear (e_dE);

    calculateSample (pattern.beginInput (), pattern.endInput ());

    // compute the error
    E = m_net.errorFunction (pattern.beginOutput (), pattern.endOutput (), pattern.weight ());
    

    int numWeights = std::distance (m_net.begin (), m_net.end ());


    m_net.compute_dE ();
    m_net.update_dE (false);

    int changeWeightPosition = randomInt (numWeights);
    auto it = m_net.begin ();
    std::advance (it, changeWeightPosition);
    Synapsis& syn = *it;

    NNTYPE dE = syn.dE;

    NNTYPE myDelta = -E/dE;

    syn.weight += myDelta;
    
    calculateSample (pattern.beginInput (), pattern.endInput ());
    E_delta = m_net.errorFunction (pattern.beginOutput (), pattern.endOutput (), pattern.weight ());

    E_delta_gradient = E + myDelta*dE;

    NNTYPE relDiff = fabs (E_delta-E_delta_gradient)/E;

    syn.weight -= myDelta;


    return relDiff <= limit;
}
Example #4
0
	void readPapers(int papers, Scanner scanIn) {
		int paper;
		for (paper = 1; paper <= papers; paper++) {
			String paperAuthors;

			paperAuthors = scanIn.nextLine();
			#ifdef DEBUG
				printf("paper #%d %s\n", paper, paperAuthors);
			#endif

			Author authors[] = new Author[Author.MAX_PAPER_AUTHORS];
			int authorsIndex = 0;

			Pattern p = Pattern.compile("\\s*(\\S*)[,]\\s*(\\S*)[,:]");
			Matcher m = p.matcher(paperAuthors);
			while (m.find()) {
				String lname = m.group(1);
				String fname = m.group(2);

				if (debug) {
					printf("\t'%s' => '%s', '%s'\n", paperAuthors, lname, fname);
				}

				authors[authorsIndex] = Author.find(fname, lname);
				if (authors[authorsIndex] == null) {
					if (lname.length() == 0 || fname.length() == 0) {
						continue;
					}
					authors[authorsIndex] = new Author(fname, lname);
				}
				authorsIndex++;
			}

			for (int i = 0; i < authorsIndex; i++) {
				for (int j = 0; j < authorsIndex; j++) {
					authors[i].publicouCom(authors[j]);
				}
			}
		}
	}
Example #5
0
void Window::showDetails() {
    Pattern* pattern = m_board->pattern();
    if (!pattern) {
        return;
    }
    QString patternid = QSettings().value("Current/Pattern", 0).toString();
    static const QStringList sizes = QStringList() << NewGameDialog::tr("Low")
                                     << NewGameDialog::tr("Medium")
                                     << NewGameDialog::tr("High")
                                     << NewGameDialog::tr("Very High");
    QString number = "4"
                     + m_board->words()->language()
                     + patternid
                     + QString::number(pattern->wordCount())
                     + QString("%1").arg(int(pattern->wordLength() - 4), 2, 16, QLatin1Char('0'))
                     + QString::number(pattern->seed(), 16);
    QMessageBox dialog(QMessageBox::Information,
                       tr("Details"),
                       QString("<p><b>%1</b> %2<br><b>%3</b> %4<br><b>%5</b> %6<br><b>%7</b> %8<br><b>%9</b> %10</p>")
                       .arg(tr("Pattern:")).arg(pattern->name())
                       .arg(NewGameDialog::tr("Language:")).arg(LocaleDialog::languageName(m_board->words()->language()))
                       .arg(NewGameDialog::tr("Amount of Words:")).arg(sizes.value(pattern->wordCount()))
                       .arg(NewGameDialog::tr("Word Length:")).arg(NewGameDialog::tr("%n letter(s)", "", pattern->wordLength() + 1))
                       .arg(tr("Game Number:")).arg(number),
                       QMessageBox::NoButton,
                       this);
    dialog.setIconPixmap(QIcon(QString(":/patterns/%1.png").arg(patternid)).pixmap(96,96));
    dialog.exec();
}
Example #6
0
bool
PatternCutoff::operator()(const Pattern &p) const {
  if (p.attributes.find(key) == p.attributes.end())
    throw BadKeyException(key, p.get_accession());
  string val = p.attributes.find(key)->second;
  if (reverse && numeric) 
    return atof(val.c_str()) > atof(value.c_str());
  else if (reverse) 
    return val > value;
  else if (numeric) 
    return atof(val.c_str()) < atof(value.c_str());
  else return val < value;
}
Example #7
0
File: Path.cpp Project: tapio/Wendy
PathList Path::childrenMatching(const Pattern& pattern) const
{
  PathList children;

#if WENDY_SYSTEM_WIN32
  WIN32_FIND_DATA data;
  HANDLE search;

  search = FindFirstFile(m_string.c_str(), &data);
  if (search == INVALID_HANDLE_VALUE)
    return PathList();

  do
  {
    if (pattern.matches(data.cFileName))
      children.push_back(operator + (data.cFileName));
  }
  while (FindNextFile(search, &data));

  FindClose(search);
#else
  DIR* stream;
  dirent* entry;

  stream = opendir(m_string.c_str());
  if (!stream)
    return PathList();

  while ((entry = readdir(stream)))
  {
    if (pattern.matches(entry->d_name))
      children.push_back(operator + (entry->d_name));
  }

  closedir(stream);
#endif

  return children;
}
Example #8
0
std::pair<VarDecl *, PatternBindingDecl *>
DerivedConformance::declareDerivedProperty(TypeChecker &tc, Decl *parentDecl,
                                           NominalTypeDecl *typeDecl,
                                           Identifier name,
                                           Type propertyInterfaceType,
                                           Type propertyContextType,
                                           bool isStatic,
                                           bool isFinal) {
  auto &C = tc.Context;
  auto parentDC = cast<DeclContext>(parentDecl);

  VarDecl *propDecl = new (C) VarDecl(/*IsStatic*/isStatic, VarDecl::Specifier::Var,
                                      /*IsCaptureList*/false, SourceLoc(), name,
                                      propertyContextType, parentDC);
  propDecl->setImplicit();
  propDecl->copyFormalAccessAndVersionedAttrFrom(typeDecl);
  propDecl->setInterfaceType(propertyInterfaceType);

  // If this is supposed to be a final property, mark it as such.
  assert(isFinal || !parentDC->getAsClassOrClassExtensionContext());
  if (isFinal && parentDC->getAsClassOrClassExtensionContext() &&
      !propDecl->isFinal())
    propDecl->getAttrs().add(new (C) FinalAttr(/*IsImplicit=*/true));

  Pattern *propPat = new (C) NamedPattern(propDecl, /*implicit*/ true);
  propPat->setType(propertyContextType);
  propPat = new (C) TypedPattern(propPat,
                                 TypeLoc::withoutLoc(propertyContextType),
                                 /*implicit*/ true);

  auto pbDecl = PatternBindingDecl::create(C, SourceLoc(),
                                           StaticSpellingKind::None,
                                           SourceLoc(), propPat, nullptr,
                                           parentDC);
  pbDecl->setImplicit();

  return {propDecl, pbDecl};
}
Example #9
0
void
LTBDots::printStrip(char *title, bool dotsOnly)
{
	Serial.print("\n<<STRIP -   "); Serial.print(title); Serial.println(" - STRIP >> ");
	if (dotsOnly)
		Serial.println("*** DOTS ONLY ***");
	else
	{
		Serial.print("this    = 0x"); Serial.println((uint16_t)this, 16);
		Serial.print("MaxPix  =   "); Serial.println(nPix);
		Serial.print("dots  =   0x"); Serial.println((uint16_t)dots);
		Serial.print("lastMS  =   "); Serial.println(lastMsec);
	}
	Serial.println("Pix\tTag\tBlu\tGrn\tRed");
	for (int i = 0; i < nPix; i++)
	{
		Serial.print(""); Serial.print(i);
		Serial.print("\t0x"); Serial.print(  dots[i * 4 +0], HEX);
		Serial.print("\t0x"); Serial.print(  dots[i * 4 +1], HEX);
		Serial.print("\t0x"); Serial.print(  dots[i * 4 +2], HEX);
		Serial.print("\t0x"); Serial.println(dots[i * 4 +3], HEX);
	}

	if (pats == NULL)
		Serial.println("No Patterns");
	else
	{
		Pattern *ptr = pats;

		while (true)
		{
			ptr->printPat(title);
			if (ptr->isLast())
				break;
			ptr = ptr->Nxt();
		}
	}
}
/// InstantiateNonterminal - This method takes the nonterminal specified by
/// NT, which should not be completely resolved, clones it, applies ResultTy
/// to its root, then runs the type inference stuff on it.  This should
/// produce a newly resolved nonterminal, which we make a record for and
/// return.  To be extra fancy and efficient, this only makes one clone for
/// each type it is instantiated with.
Record *InstrSelectorEmitter::InstantiateNonterminal(Pattern *NT,
                                                     MVT::ValueType ResultTy) {
  assert(!NT->isResolved() && "Nonterminal is already resolved!");

  // Check to see if we have already instantiated this pair...
  Record* &Slot = InstantiatedNTs[std::make_pair(NT, ResultTy)];
  if (Slot) return Slot;
  
  Record *New = new Record(NT->getRecord()->getName()+"_"+getName(ResultTy));

  // Copy over the superclasses...
  const std::vector<Record*> &SCs = NT->getRecord()->getSuperClasses();
  for (unsigned i = 0, e = SCs.size(); i != e; ++i)
    New->addSuperClass(SCs[i]);

  DEBUG(std::cerr << "  Nonterminal '" << NT->getRecord()->getName()
                  << "' for type '" << getName(ResultTy) << "', producing '"
                  << New->getName() << "'\n");

  // Copy the pattern...
  Pattern *NewPat = NT->clone(New);

  // Apply the type to the root...
  NewPat->getTree()->updateNodeType(ResultTy, New->getName());

  // Infer types...
  NewPat->InferAllTypes();

  // Make sure everything is good to go now...
  if (!NewPat->isResolved())
    NewPat->error("Instantiating nonterminal did not resolve all types!");

  // Add the pattern to the patterns map, add the record to the RecordKeeper,
  // return the new record.
  Patterns[New] = NewPat;
  Records.addDef(New);
  return Slot = New;
}
Example #11
0
void track_proxy_data(t_track_proxy *x, t_symbol *s, int argc, t_atom *argv)
{
    if(argc == 1 && IS_A_SYMBOL(argv,0) && argv[0].a_w.w_symbol == gensym("end"))
    {
        pd_unbind(&x->x_obj.ob_pd, gensym(TRACK_SELECTOR));
        return;
    }
    if(argc < 3 || !IS_A_SYMBOL(argv,0) || !IS_A_FLOAT(argv,1) || !IS_A_FLOAT(argv,2))
    {
        pd_error(x, "unrecognized format for in-patch data");
        return;
    }
    t_symbol *pat = argv[0].a_w.w_symbol;
    t_int rows = (t_int) argv[1].a_w.w_float;
    t_int cols = (t_int) argv[2].a_w.w_float;
    if(argc != (3 + rows * cols))
    {
        pd_error(x, "unrecognized format for in-patch data (malformed data?)");
        return;
    }
    Track *t = x->track;
    t->addPattern(rows, cols, pat->s_name);
    Pattern *p = t->getPattern(pat->s_name);
    if(!p)
    {
        pd_error(x, "fatal error: cannot create patern");
        return;
    }
    int a = 3;
    for(int r = 0; r < rows; r++)
    {
        for(int c = 0; c < cols; c++)
        {
            p->setCell(r, c, argv[a]);
            a++;
        }
    }
}
Example #12
0
// worker methods
bool Pattern::operator==(const Pattern & obj) const {
	bool match = true;
	if (&obj == 0) {
		std::cout << "Pattern::operator ==: obj is null" << std::endl;
		return false;
	}

	match = match && (this->getPattern() == obj.getPattern());
	if (match == false) {
		std::cout << "Pattern::equals: vector mismatch" << std::endl;
		return false;
	}
	return true;
}
	void testInlineAutomation()
	{
		auto song = Engine::getSong();

		InstrumentTrack* instrumentTrack =
				dynamic_cast<InstrumentTrack*>(Track::create(Track::InstrumentTrack, song));

		Pattern* notePattern = dynamic_cast<Pattern*>(instrumentTrack->createTCO(0));
		notePattern->changeLength(MidiTime(4, 0));
		Note* note = notePattern->addNote(Note(MidiTime(4, 0)), false);
		note->createDetuning();

		DetuningHelper* dh = note->detuning();
		auto pattern = dh->automationPattern();
		pattern->setProgressionType( AutomationPattern::LinearProgression );
		pattern->putValue(MidiTime(0, 0), 0.0);
		pattern->putValue(MidiTime(4, 0), 1.0);

		QCOMPARE(pattern->valueAt(MidiTime(0, 0)), 0.0f);
		QCOMPARE(pattern->valueAt(MidiTime(1, 0)), 0.25f);
		QCOMPARE(pattern->valueAt(MidiTime(2, 0)), 0.5f);
		QCOMPARE(pattern->valueAt(MidiTime(4, 0)), 1.0f);
	}
Example #14
0
double Pattern::compare(const Pattern & obj) const {

	const std::vector<bool> this_pat = this->getPattern();
	const std::vector<bool> obj_pat = obj.getPattern();
	int this_sz = this_pat.size();
	int obj_sz = obj_pat.size();

#ifdef PATTERN_DEBUG // DEBUG
	std::cout << "Pattern::compare: this: ";
	common::Misc::print(std::cout, this_pat);
	std::cout << std::endl;
	std::cout << "Pattern::compare: obj: ";
	common::Misc::print(std::cout, obj_pat);
	std::cout << std::endl;
#endif // DEBUG
	if (this_sz == 0) {
		std::cout << "Pattern::compare: this zero pattern mismatch" << std::endl;
		return 0;
	} else {
		if (obj_sz == 0) {
			std::cout << "Pattern::compare: obj zero pattern mismatch" << std::endl;
			return 0;
		}
	}
	if (this_sz != obj_sz) {

		std::cout << "Pattern::compare: size mismatch " << std::endl;
		return 0;
	}
	double fraction = static_cast<double>(1) / static_cast<double>(this_sz);
	double match = 0;

	std::vector<bool>::const_iterator it_this_vec = this_pat.begin();
	const std::vector<bool>::const_iterator it_this_vec_end = this_pat.end();
	std::vector<bool>::const_iterator it_obj_vec = obj_pat.begin();
	const std::vector<bool>::const_iterator it_obj_vec_end = obj_pat.end();

	while (it_this_vec != it_this_vec_end && it_obj_vec != it_obj_vec_end) {
		if (*it_this_vec == *it_obj_vec) {
			match += fraction;
		}
		++it_this_vec;
		++it_obj_vec;
	}
#ifdef PATTERN_DEBUG // DEBUG
	std::cout << "Pattern::compare: match: " << match << std::endl;
#endif // DEBUG
	return match;

}
Example #15
0
bool CheckString::CheckNot(const SourceMgr &SM, StringRef Buffer,
                           const std::vector<const Pattern *> &NotStrings,
                           StringMap<StringRef> &VariableTable) const {
  for (unsigned ChunkNo = 0, e = NotStrings.size();
       ChunkNo != e; ++ChunkNo) {
    const Pattern *Pat = NotStrings[ChunkNo];
    assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");

    size_t MatchLen = 0;
    size_t Pos = Pat->Match(Buffer, MatchLen, VariableTable);

    if (Pos == StringRef::npos) continue;

    SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()+Pos),
                    SourceMgr::DK_Error,
                    Prefix + "-NOT: string occurred!");
    SM.PrintMessage(Pat->getLoc(), SourceMgr::DK_Note,
                    Prefix + "-NOT: pattern specified here");
    return true;
  }

  return false;
}
Example #16
0
Row ClusterRepository::search(Pattern pattern, double threshold){
	std::vector<double> origin(pattern.size());
	Converter<Pattern> converter;

	std::fill(origin.begin(), origin.end(), (double)1);
	double feature = Math::cosSimilarity(origin, converter.convert(pattern));

	//しきい値以下のクラスタ
	std::vector<Row> result = this->sqlite.execute(this->getSelectClusterQuery(feature, threshold));
	
	if(result.empty()) throw std::exception("not found");

	return result[0];
}
Example #17
0
void GateTrigger::processBlock (AudioSampleBuffer& buffer, 
                                MidiBuffer& midiMessages)
{
    float threshold = library->getThreshold();
    int64 releaseTicks = library->getReleaseTicks();
    float velocityScale = library->getVelocityScale();
    
    int windowSize = buffer.getNumSamples();
    for (int i = 0; i < buffer.getNumSamples(); i += windowSize) {
        float rms = 0;
        for (int chan = 0; chan < buffer.getNumChannels(); chan++) {
            rms += buffer.getMagnitude (chan, i, jmin(windowSize, buffer.getNumSamples() - i)); 
        }
        rms = rms / buffer.getNumChannels() * 100;
        if (rms - lastRms > threshold) {
            if (Time::getHighResolutionTicks() - lastTriggerTick > releaseTicks) {
                Pattern* pattern = sequencer->getPattern();
                Instrument* instrument = pattern->getActiveInstrument();
                // play note
                float velocity = (rms - lastRms) / velocityScale;
                DBG("RMS: " + String(rms) + " lastRMS: " + String(lastRms) + " velocity: " + String(velocity));
                int noteNumber = instrument->getNoteNumber();
                MidiMessage m = MidiMessage::noteOn (1, noteNumber, velocity);
                midiMessages.addEvent (m, i);
                // insert into sequencer pattern
                int step = round(sequencer->getPreciseStep());
                step = step % pattern->getNumSteps();
                Cell* cell = pattern->getCellAt (0, step);
                delayedInserterThread->insertNote (cell, velocity, instrument);
                // Retrigger the reset timer
                resetTimer->retrigger();
                lastTriggerTick = Time::getHighResolutionTicks();
            }
        }
        lastRms = rms;
    }   
}
Example #18
0
double RateMeyerDiscrete::computeFunction(double value) {
	if (!is_categorized) return RateMeyerHaeseler::computeFunction(value);
	if (!rate_mh) {
		if (value != cur_scale) {
			ptn_tree->scaleLength(value/cur_scale);
			cur_scale = value;
			ptn_tree->clearAllPartialLH();
		}
		return -ptn_tree->computeLikelihood();
	}

	double lh = 0.0;
	int nseq = phylo_tree->leafNum;
	int nstate = phylo_tree->getModel()->num_states;
	int i, j, k, state1, state2;
	ModelSubst *model = phylo_tree->getModel();
    int trans_size = nstate * nstate;
	double *trans_mat = new double[trans_size];
	int *pair_freq = new int[trans_size];

	for (i = 0; i < nseq-1; i++) 
		for (j = i+1; j < nseq; j++) {
			memset(pair_freq, 0, trans_size * sizeof(int));
			for (k = 0; k < size(); k++) {
				if (ptn_cat[k] != optimizing_cat) continue;
				Pattern *pat = & phylo_tree->aln->at(k);
				if ((state1 = pat->at(i)) < nstate && (state2 = pat->at(j)) < nstate)
					pair_freq[state1*nstate + state2] += pat->frequency;
			}
			model->computeTransMatrix(value * dist_mat[i*nseq + j], trans_mat);
			for (k = 0; k < trans_size; k++) if (pair_freq[k])
				lh -= pair_freq[k] * log(trans_mat[k]);
		}
	delete [] pair_freq;
	delete [] trans_mat;
	return lh;
}
Example #19
0
void StateWriter::getState (MemoryBlock& destData)
{
    DBG("StateWriter::getState(): Saving state.")
    
    ValueTree settingsTree ("settings");
    
    ValueTree libTree ("library");
    libTree.setProperty ("threshold", library->getThreshold(), nullptr);
    libTree.setProperty ("release", library->getReleaseTicks(), nullptr);
    libTree.setProperty ("velocity", library->getVelocityScale(), nullptr);
    settingsTree.addChild (libTree, -1, nullptr);

    ValueTree patternsTree ("patterns");
    for (int i = 0; i < library->getNumPatterns(); i++) {
        Pattern* pattern = library->getPattern (i);
        ValueTree patternTree ("pattern");
        ValueTree instrumentsTree ("instruments");
        for (int j = 0; j < pattern->getNumInstruments(); j++) {
            Instrument* instrument = pattern->getInstrumentAt (j);
            ValueTree instrumentTree ("instrument");
            instrumentTree.setProperty ("index", instrument->getIndex(), nullptr);
            instrumentTree.setProperty ("name", instrument->getName(), nullptr);
            instrumentTree.setProperty ("noteNumber", instrument->getNoteNumber(), nullptr);            
            instrumentsTree.addChild (instrumentTree, -1, nullptr);
        }
        patternTree.addChild (instrumentsTree, -1, nullptr);
        patternsTree.addChild (patternTree, -1, nullptr);
    }
    settingsTree.addChild (patternsTree, -1, nullptr);
    
    ValueTree seqTree ("sequencer");
    seqTree.setProperty ("sequencerNum", sequencer->getSequencerNum(), nullptr);
    settingsTree.addChild (seqTree, -1, nullptr);
        
    MemoryOutputStream stream (destData, false);
    settingsTree.writeToStream (stream);
}
std::vector<int> MatchableStringB::match(Pattern &p, bool parallel) const {
	if (!p.isPreprocessed()) {
		p.preprocess();
	}

	std::vector<int> occurrences;
    
	if (!parallel) {
		auto tmp = matchSubstr(p, str, length, 0);
		occurrences = std::move(*tmp);
		delete tmp;
	}
	else {
		const int parts = tbb::task_scheduler_init::default_num_threads();
		std::vector<std::vector<int>*> occurrencesArray(parts);

		tbb::parallel_for(tbb::blocked_range<int>(0, parts),
			[this, &occurrencesArray, &p, parts](const tbb::blocked_range<int>& range) {
			for (int i = range.begin(); i != range.end(); ++i) {
				occurrencesArray[i] = matchSubstr(p, parts, i);
			}
		});

		size_t fullSize = 0;
		for (int i = 0; i < parts; i++) {
			fullSize += occurrencesArray[i]->size();
		}

		occurrences.reserve(fullSize);
		for (int i = 0; i < parts; i++) {
			occurrences.insert(occurrences.end(), occurrencesArray[i]->begin(), occurrencesArray[i]->end());
			delete occurrencesArray[i];
		}
	}
		
    return occurrences;
}
Example #21
0
void
LTBDots::showLights(bool force)
{
	Pattern *ptr = pats;
	bool changed = false;

	uint16_t deltaMsec = millis() - lastMsec;
	lastMsec = millis();
	/**  Loop through all pats and update timed actions **/
	//	while(ptr)			// first loop through all patterns and update timed actions
	//	{
	//		changed = (changed || ptr->doActions(deltaMsec));
	//		ptr=ptr->Nxt();
	//	}	

	if (changed || force)
	{
		ptr = pats;
		curStrip= dots;
		/**  Loop through all pats and light them **/
		while (ptr)
		{
			curStrip = ptr->fillRGB(curStrip);
			ptr = ptr->Nxt();
		}
	}
	printStrip("prePaint");
	sendLeader();
	dp= dots;

	while (dp != curStrip)
		SPI.transfer(*dp++);
	sendTrailer();

	return;
}
Example #22
0
	int readCases(int names, Scanner *scanIn, Collection<Entry<String, Author>> *theMap,
			Set<Author> *targets) {
		int nameInd;
		for (nameInd = 1; nameInd <= names; nameInd++) {
			String bigname;

			bigname = scanIn.nextLine();
			#ifdef DEBUG
				printf("\tname #%d %s\n", nameInd, bigname);
			#endif

			Pattern p = Pattern.compile("\\s*(\\S*)[,]\\s*(\\S*)");
			Matcher m = p.matcher(bigname);
			if (m.find()) {
				String lname = m.group(1);
				String fname = m.group(2);

				#ifdef DEBUG
					printf("\tmatcher2'%s' => '%s', '%s'\n", bigname, lname, fname);
				#endif

				Author a = Author.find(fname, lname);response

				theMap.add(new MyEntry(bigname, a));
				if (a != null) {
					targets.add(a);
					#ifdef DEBUG
						printf("\tauthor case '%s' is #%d\n", a.lname, targets.size());
					#endif
				}
			} else {
				theMap.add(new Entry<String, Author>(bigname, null));
			}
		}
		return nameInd;
	}
Example #23
0
	void pastePattern(int x, int y, bool isReverse, Pattern const & pattern)
	{
		if ((0 <= x) && ((x + pattern.getWidth()) < CELL_LENGTH_1) && (0 <= y) && ((y + pattern.getHeight()) < CELL_LENGTH_0))
		{
			int i = 0;
			for (auto const & row : *pattern.getPattern())
			{
				int j = 0;
				for (auto const e : row)
				{
					if (isReverse)
					{
						(*cell)[y + j][x + i] = !e;
					}
					else
					{
						(*cell)[y + j][x + i] = e;
					}
					++j;
				}
				++i;
			}
		}
	}
Example #24
0
std::pair<VarDecl *, PatternBindingDecl *>
DerivedConformance::declareDerivedReadOnlyProperty(TypeChecker &tc,
                                                   Decl *parentDecl,
                                                   NominalTypeDecl *typeDecl,
                                                   Identifier name,
                                                   Type propertyInterfaceType,
                                                   Type propertyContextType,
                                                   FuncDecl *getterDecl,
                                                   bool isStatic) {
  auto &C = tc.Context;
  auto parentDC = cast<DeclContext>(parentDecl);

  VarDecl *propDecl = new (C) VarDecl(isStatic, /*let*/ false,
                                      SourceLoc(), name,
                                      propertyContextType,
                                      parentDC);
  propDecl->setImplicit();
  propDecl->makeComputed(SourceLoc(), getterDecl, nullptr, nullptr,
                         SourceLoc());
  propDecl->setAccessibility(typeDecl->getFormalAccess());
  propDecl->setInterfaceType(propertyInterfaceType);

  Pattern *propPat = new (C) NamedPattern(propDecl, /*implicit*/ true);
  propPat->setType(propertyContextType);
  propPat = new (C) TypedPattern(propPat,
                                 TypeLoc::withoutLoc(propertyContextType),
                                 /*implicit*/ true);

  auto pbDecl = PatternBindingDecl::create(C, SourceLoc(),
                                           StaticSpellingKind::None,
                                           SourceLoc(), propPat, nullptr,
                                           parentDC);
  pbDecl->setImplicit();

  return {propDecl, pbDecl};
}
Example #25
0
Matrix clipped_Hebbian(const Pattern& Z, const Topology& W)
{
	Matrix J(W.n, W.n, 0); // Create a nxn Matrix filled with 0

	// clipped Hebbian Definition: Jij=Wij * Zp(i) * Zp(j)
	// Redefinition:
	// 	If there is a connection between neuron i and neuron j,
	// 	check if neuron i and neuron j are both in pattern p
	// ----------------------------
	// 1. Go through all the patterns
	for (Pattern::const_iterator p=Z.begin(); p!=Z.end(); ++p)
		// 2. Go through all connections of the topology
		for (Topology::const_iterator i=W.begin(); i!=W.end(); ++i)
		{
		// 3. Check if neuron 'i' is in pattern
		if (find(p->begin(), p->end(), i->first)!=p->end())
			// 4. If so, then check if any of the neurons connected to 'i' is in the pattern 'p' as well
			for (NeuronList::const_iterator j=i->second.begin(); j!=i->second.end(); ++j)
				if (find(p->begin(), p->end(), *j)!=p->end())
					// If so, Jij is equal to 1
					J(i->first,*j)=1;
		}
	return J;
}
Example #26
0
size_t CheckString::Check(const SourceMgr &SM, StringRef Buffer,
                          bool IsLabelScanMode, size_t &MatchLen,
                          StringMap<StringRef> &VariableTable) const {
  size_t LastPos = 0;
  std::vector<const Pattern *> NotStrings;

  // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
  // bounds; we have not processed variable definitions within the bounded block
  // yet so cannot handle any final CHECK-DAG yet; this is handled when going
  // over the block again (including the last CHECK-LABEL) in normal mode.
  if (!IsLabelScanMode) {
    // Match "dag strings" (with mixed "not strings" if any).
    LastPos = CheckDag(SM, Buffer, NotStrings, VariableTable);
    if (LastPos == StringRef::npos)
      return StringRef::npos;
  }

  // Match itself from the last position after matching CHECK-DAG.
  StringRef MatchBuffer = Buffer.substr(LastPos);
  size_t MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
  if (MatchPos == StringRef::npos) {
    PrintCheckFailed(SM, *this, MatchBuffer, VariableTable);
    return StringRef::npos;
  }

  // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
  // or CHECK-NOT
  if (!IsLabelScanMode) {
    StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);

    // If this check is a "CHECK-NEXT", verify that the previous match was on
    // the previous line (i.e. that there is one newline between them).
    if (CheckNext(SM, SkippedRegion))
      return StringRef::npos;

    // If this check is a "CHECK-SAME", verify that the previous match was on
    // the same line (i.e. that there is no newline between them).
    if (CheckSame(SM, SkippedRegion))
      return StringRef::npos;

    // If this match had "not strings", verify that they don't exist in the
    // skipped region.
    if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
      return StringRef::npos;
  }

  return LastPos + MatchPos;
}
Example #27
0
static void PrintCheckFailed(const SourceMgr &SM, const SMLoc &Loc,
                             const Pattern &Pat, StringRef Buffer,
                             StringMap<StringRef> &VariableTable) {
  // Otherwise, we have an error, emit an error message.
  SM.PrintMessage(Loc, SourceMgr::DK_Error,
                  "expected string not found in input");

  // Print the "scanning from here" line.  If the current position is at the
  // end of a line, advance to the start of the next line.
  Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));

  SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
                  "scanning from here");

  // Allow the pattern to print additional information if desired.
  Pat.PrintFailureInfo(SM, Buffer, VariableTable);
}
Example #28
0
void CustomPatternsModel::loadFromDB()
{
    layoutAboutToBeChanged();
    QSqlQuery query;
    myData.clear();
    query.exec("SELECT * from custompatterns ORDER BY name");
    while (query.next())
    {
        Pattern pattern;
        pattern.setName(query.value("name").toString());
        pattern.setArtistRegex(query.value("artistregex").toString());
        pattern.setArtistCaptureGrp(query.value("artistcapturegrp").toInt());
        pattern.setTitleRegex(query.value("titleregex").toString());
        pattern.setTitleCaptureGrp(query.value("titlecapturegrp").toInt());
        pattern.setDiscIdRegex(query.value("discidregex").toString());
        pattern.setDiscIdCaptureGrp(query.value("discidcapturegrp").toInt());
        myData.append(pattern);
    }
    layoutChanged();
}
Example #29
0
void insertIntoEdgeFreq(NodeX* src, int destNodeID, double destNodeLabel, double edgeLabel, tr1::unordered_map<string, void* >& edgeToFreq, bool addSrcOnly)
{
	string key;
	if(src->getLabel()>destNodeLabel)
	{
		stringstream sstmGF;
		if(src->getLabel()==destNodeLabel)
			sstmGF << src->getLabel()<<destNodeLabel<<","<<edgeLabel<<",";
		else
			sstmGF << src->getLabel()<<","<<destNodeLabel<<","<<edgeLabel<<",";
		key = sstmGF.str();
	}
	else
	{
		stringstream sstmGF;
		if(destNodeLabel==src->getLabel())
			sstmGF <<destNodeLabel<<src->getLabel()<<","<<edgeLabel<<",";
		else
			sstmGF <<destNodeLabel<<","<<src->getLabel()<<","<<edgeLabel<<",";
		key = sstmGF.str();
	}

	tr1::unordered_map<string, void* >::iterator iter = edgeToFreq.find(key);
	Pattern* pattern;
	if(iter==edgeToFreq.end())
	{
		GraphX* graph = new GraphX();
		NodeX* node1 = graph->AddNode(0, src->getLabel());
		NodeX* node2 = graph->AddNode(1, destNodeLabel);
		graph->addEdge(node1, node2, edgeLabel);
		pattern = new Pattern(graph);
		delete graph;

		edgeToFreq[key] = pattern;
	}
	else
	{
		pattern = (Pattern*)((*iter).second);
	}

	if(pattern->getGraph()->getNodeWithID(0)->getLabel()==src->getLabel())
	{
		pattern->addNode(src->getID(), 0);
		if(!addSrcOnly) pattern->addNode(destNodeID, 1);
	}
	else
	{
		pattern->addNode(src->getID(), 1);
		if(!addSrcOnly) pattern->addNode(destNodeID, 0);
	}
}
Example #30
0
// Determine the locality of the supplied atom
AtomAddress Model::locateAtom(Atom* i)
{
	Messenger::enter("Model::locateAtom");
	int patternno, molno, atomno, id;
	Pattern* p;
	AtomAddress result;
	if (!createPatterns())
	{
		Messenger::print("Model::locateAtom : No valid pattern available for model.");
		Messenger::exit("Model::locateAtom");
		return result;
	}
	id = i->id();
	// First, find the pattern the atom is covered by
	patternno = -1;
	p = patterns_.first();
	while (p != NULL)
	{
		if ((id >= p->startAtom()) && (id <= p->endAtom()))
		{
			patternno = p->id();
			break;
		}
		p = p->next;
	}
	if (patternno == -1)
	{
		printf("Fatal error - could not find owner pattern for atom!\n");
		Messenger::exit("Model::locateAtom");
		return result;
	}
	// Next, find its molecule id
	id -= p->startAtom();
	molno = id / p->nAtoms();
	// Finally, get the atom offset
	atomno = id % p->nAtoms();
	// Store values, and return
	result.setPattern(p);
	result.setMolecule(molno);
	result.setOffset(atomno);
	Messenger::exit("Model::locateAtom");
	return result;
}