コード例 #1
0
ファイル: regexp.cpp プロジェクト: abbeyj/trilite
/** Construct a filter expression from a regular expression
 * Returns SQLITE_ERROR and sets user relevant error message on error */
int regexpPreFilter(expr **ppExpr, bool *pAll, trilite_vtab *pTrgVtab, const unsigned char *expr, int nExpr){
  int rc = SQLITE_OK;

  *ppExpr = NULL;
  
  /* Options for regular expressions */
  re2::RE2::Options options;
  options.set_log_errors(false);
  options.set_max_mem(pTrgVtab->maxRegExpMemory);

  /* Create regular expression from string */
  re2::RE2 re(re2::StringPiece((const char*)expr, nExpr), options);

  /* TODO if re.ProgramSize() > SOME_THRESHOLD return and error message  */
  /* Ideally this threshold should be a runtime setting */

  /* Provide error message if regular expression compilation failed */
  if(!re.ok()){
    /* Error codes from re2 */
    std::string msg;
    switch(re.error_code()){
      case re2::RE2::ErrorBadEscape:
        msg = "Bad escape sequence at '%s'";
        break;
      case re2::RE2::ErrorBadCharClass:
        msg = "Bad character class at '%s'";
        break;
      case re2::RE2::ErrorBadCharRange:
        msg = "Bad character range at '%s'";
        break;
      case re2::RE2::ErrorMissingBracket:
        msg = "Missing bracket in '%s'";
        break;
      case re2::RE2::ErrorMissingParen:
        msg = "Missing paranthesis in '%s'";
        break;
      case re2::RE2::ErrorTrailingBackslash:
        msg = "Trailing backslash in '%s'";
        break;
      case re2::RE2::ErrorRepeatArgument:
        msg = "Repeat argument missing in '%s'";
        break;
      case re2::RE2::ErrorRepeatSize:
        msg = "Bad repeat argument at '%s'";
        break;
      case re2::RE2::ErrorRepeatOp:
        msg = "Bad repeatition operator at '%s'";
        break;
      case re2::RE2::ErrorBadPerlOp:
        msg = "Bad perl operator at '%s'";
        break;
      case re2::RE2::ErrorBadUTF8:
        msg = "Invalid UTF-8 at '%s'";
        break;
      case re2::RE2::ErrorBadNamedCapture:
        msg = "Bad named capture group at '%s'";
        break;
      case re2::RE2::ErrorPatternTooLarge:
        msg = "Pattern '%s' is too large";
        break;
      case re2::RE2::ErrorInternal:
      default:
        msg = "Unknown internal error at '%s'";
        break;
    }
    /* Now set the error message */
    triliteError(pTrgVtab, ("REGEXP: " + msg).c_str(), re.error_arg().c_str());

    /* Return error */
    return SQLITE_ERROR;
  }

  /* Compute a prefilter */
  re2::Prefilter* pf = re2::Prefilter::FromRE2(&re);

  /* Provide error message if a filter couldn't be devised, as we shall not */
  /* permit full table scans. */
  if(!pf){
    triliteError(pTrgVtab, "REGEXP: Failed to build a filter for the regular expression");
    return SQLITE_ERROR;
  }

  rc = exprFromPreFilter(ppExpr, pAll, pTrgVtab, pf);
  assert(rc == SQLITE_OK);

  /* Release the prefilter */
  delete pf;

  return rc;
}
コード例 #2
0
ファイル: Strings.cpp プロジェクト: getcontext/zf2ns
void Strings::regexReplace(string& target, string& from, string& to) {
	boost::regex re(from);
	target = boost::regex_replace(target, re, to,
			boost::match_default | boost::format_all);
}
コード例 #3
0
ファイル: FastqFlowcell.cpp プロジェクト: Illumina/isaac2
flowcell::Layout FastqFlowcell::createFilteredFlowcell(
    const std::string &tilesFilter,
    const boost::filesystem::path &baseCallsDirectory,
    const bool compressed,
    const unsigned laneNumberMax,
    const unsigned readNameLength,
    std::string useBasesMask,
    const bool allowVariableFastqLength,
    const char fastqQ0,
    const std::string &seedDescriptor,
    const unsigned seedLength,
    const reference::ReferenceMetadataList &referenceMetadataList,
    unsigned &firstPassSeeds)
{

    FastqPathPairList flowcellFilePaths = findFastqPathPairs(compressed, laneNumberMax, baseCallsDirectory);
    if (flowcellFilePaths.empty())
    {
        const boost::format message = boost::format("\n   *** Could not find any fastq lanes in: %s ***\n") %
            baseCallsDirectory;
        BOOST_THROW_EXCEPTION(common::InvalidOptionException(message.str()));
    }

    FastqFlowcellInfo flowcellInfo = parseFastqFlowcellInfo(flowcellFilePaths, allowVariableFastqLength, fastqQ0, readNameLength);

    std::vector<unsigned int> readLengths;
    if (flowcellInfo.readLengths_.first)
    {
        readLengths.push_back(flowcellInfo.readLengths_.first);
    }
    if (flowcellInfo.readLengths_.second)
    {
        readLengths.push_back(flowcellInfo.readLengths_.second);
    }

    if ("default" == useBasesMask)
    {
        if (readLengths.size() == 1)
        {
            useBasesMask = "y*n";
        }
        else if (readLengths.size() == 2)
        {
            useBasesMask = "y*n,y*n";
        }
        else
        {
            const boost::format message =
                boost::format("\n   *** Could not guess the use-bases-mask for '%s', please supply the explicit value ***\n") %
                baseCallsDirectory.string();
            BOOST_THROW_EXCEPTION(common::InvalidOptionException(message.str()));
        }
    }

    std::vector<unsigned int> readFirstCycles;

    ParsedUseBasesMask parsedUseBasesMask;
    alignment::SeedMetadataList seedMetadataList;
    if (!readLengths.empty())
    {
        parsedUseBasesMask = parseUseBasesMask(readFirstCycles, readLengths, seedLength, useBasesMask, baseCallsDirectory);
        seedMetadataList = parseSeedDescriptor(parsedUseBasesMask.dataReads_, seedDescriptor, seedLength, firstPassSeeds);
    }

    flowcell::Layout fc(baseCallsDirectory,
                        flowcell::Layout::Fastq,
                        flowcell::FastqFlowcellData(compressed, fastqQ0),
                        laneNumberMax,
                        flowcellInfo.readNameLength_,
                        std::vector<unsigned>(),
                        parsedUseBasesMask.dataReads_,
                        seedMetadataList, flowcellInfo.flowcellId_);

    std::string regexString(tilesFilter);
    std::replace(regexString.begin(), regexString.end(), ',', '|');
    boost::regex re(regexString);
    BOOST_FOREACH(const unsigned int lane, flowcellInfo.getLanes())
    {
        std::string laneString((boost::format("s_%d") % lane).str());
        if (boost::regex_search(laneString, re))
        {
            fc.addTile(lane, 1);
        }
    }

    return fc;
}
コード例 #4
0
ファイル: palindnum.c プロジェクト: evely211/Norman
int nonre(long int s){
    if(re(s)==s)
        return 1;
    else return 0;
}
コード例 #5
0
ファイル: SecureRNG.cpp プロジェクト: Alex237/ricochet
QByteArray SecureRNG::random(int size)
{
    QByteArray re(size, 0);
    random(re.data(), size);
    return re;
}
コード例 #6
0
ファイル: Exception_Test.cpp プロジェクト: rainbru/rainbrurpg
TEST( Exception, two_param )
{
  RainbrurpgException re("aze", "poi");
  cout << re.what();
  EXPECT_STREQ( re.what(), "azepoi");
}
コード例 #7
0
void PipedProcessCtrl::OnDClick(wxMouseEvent &e)
{
    //First retrieve the link text
    if(!m_linkclicks)
        return;
    long pos=m_textctrl->PositionFromPoint(e.GetPosition());
    int style=m_textctrl->GetStyleAt(pos);
    if((style&PP_LINK_STYLE)!=PP_LINK_STYLE)
        return; //didn't click a link
    long start=pos;
    while(start>0)
    {
        style=m_textctrl->GetStyleAt(start-1);
        if((style&PP_LINK_STYLE)!=PP_LINK_STYLE)
            break;
        start--;
    }
    long end=pos;
    while(end<m_textctrl->PositionFromLine(m_textctrl->GetLineCount()-1))
    {
        style=m_textctrl->GetStyleAt(end+1);
        if((style&PP_LINK_STYLE)!=PP_LINK_STYLE)
            break;
        end++;
    }
    wxString text=m_textctrl->GetTextRange(start,end+1);

    //retrieve the file and line number parts of the link
    wxRegEx re(m_linkregex,wxRE_ADVANCED|wxRE_NEWLINE);
    wxString file;
    long line;
    if(!re.Matches(text))
        return;
    size_t ind,len;
    re.GetMatch(&ind,&len,0);
    if(re.GetMatch(&ind,&len,1))
        file=text.Mid(ind,len);
    else
        file=wxEmptyString;
    if(re.GetMatch(&ind,&len,3))
        text.Mid(ind,len).ToLong(&line);
    else
        line=0;

    //open the file in the editor
    wxFileName f(file);
    if(f.FileExists())
    {
        cbEditor* ed = Manager::Get()->GetEditorManager()->Open(f.GetFullPath());
        if (ed)
        {
            ed->Show(true);
//            if (!ed->GetProjectFile())
//                ed->SetProjectFile(f.GetFullPath());
            ed->GotoLine(line - 1, false);
            if(line>0)
                if(!ed->HasBookmark(line - 1))
                    ed->ToggleBookmark(line -1);
        }
    }

}
コード例 #8
0
ファイル: histio.c プロジェクト: SusyRa2b/Statistics
//void loadHist(const char* filename, const char* pfx, const char* pat, Bool_t doAdd, Double_t scaleFactor)
void loadHist(const char* filename="in.root", const char* pfx=0, const char* pat="*", Bool_t doAdd=kFALSE, Double_t scaleFactor=-1.0)
{
  cout << " Reading histograms from file: " << filename << endl ;
  TFile inf(filename) ;
  //inf.ReadAll() ;
  TList* list = inf.GetListOfKeys() ;
  TIterator* iter = list->MakeIterator();

  TRegexp re(pat,kTRUE) ;
  std::cout << "pat = " << pat << std::endl ;

  gDirectory->cd("Rint:") ;

  TObject* obj ;
  TKey* key ;
  std::cout << "doAdd = " << (doAdd?"T":"F") << std::endl ;
  std::cout << "loadHist: reading." ;
  while((key=(TKey*)iter->Next())) {
   
    Int_t ridx = TString(key->GetName()).Index(re) ;    
    if (ridx==-1) {
      continue ;
    }

    obj = inf.Get(key->GetName()) ;
    TObject* clone ;
    if (pfx) {

      // Find existing TH1-derived objects
      TObject* oldObj = 0 ;
      if (doAdd){
	oldObj = gDirectory->Get(Form("%s_%s",pfx,obj->GetName())) ;
	if (oldObj && !oldObj->IsA()->InheritsFrom(TH1::Class())) {
	  oldObj = 0 ;
	}
      }
      if (oldObj) {
	clone = oldObj ;
   //// ((TH1*)clone)->Add((TH1*)obj) ;
        if ( scaleFactor > 0 ) {
           ((TH1*)clone)->Sumw2() ;
           ((TH1*)clone)->Add((TH1*)obj, scaleFactor) ;
        } else {
           ((TH1*)clone)->Add((TH1*)obj) ;
        }
      } else {
	clone = obj->Clone(Form("%s_%s",pfx,obj->GetName())) ;
      }


    } else {

      // Find existing TH1-derived objects
      TObject* oldObj = 0 ;
      if (doAdd){
	oldObj = gDirectory->Get(key->GetName()) ;
	if (oldObj && !oldObj->IsA()->InheritsFrom(TH1::Class())) {
	  oldObj = 0 ;
	}
      }

      if (oldObj) {
	clone = oldObj ;
 /////  ((TH1*)clone)->Add((TH1*)obj) ;
        if ( scaleFactor > 0 ) {
           ((TH1*)clone)->Sumw2() ;
           ((TH1*)clone)->Add((TH1*)obj, scaleFactor) ;
        } else {
           ((TH1*)clone)->Add((TH1*)obj) ;
        }
      } else {
	clone = obj->Clone() ;
      }
    }
    if ( scaleFactor > 0 && !doAdd ) {
       ((TH1*) clone)->Sumw2() ;
       ((TH1*) clone)->Scale(scaleFactor) ;
    }
    if (!gDirectory->GetList()->FindObject(clone)) {
      gDirectory->Append(clone) ;
    }
    std::cout << "." ;
    std::cout.flush() ;
  }
  std::cout << std::endl;
  inf.Close() ;
  delete iter ;
}
コード例 #9
0
ファイル: misc.cpp プロジェクト: serghei/kde3-kdevelop
/**
 * Read the Makefile.am and return a map of all the variables.
 * Will take notice of backslash and += constructs.
 * @param fileName
 * @param variables
 */
void AutoProjectTool::parseMakefileam(const QString &fileName, QMap<QString, QString> *variables)
{
	QFile f(fileName);
	if (!f.open(IO_ReadOnly))
	{
		return ;
	}
	QTextStream stream(&f);

	QRegExp re("^(#kdevelop:[ \t]*)?([A-Za-z][@A-Za-z0-9_]*)[ \t]*([:\\+]?=)[ \t]*(.*)$");

	QString last;
	bool multiLine = false;
	while (!stream.atEnd())
	{
		QString s = stream.readLine().stripWhiteSpace();
		if (re.exactMatch(s))
		{
			QString lhs = re.cap(2);
			QString rhs = re.cap(4);
			if (rhs[ rhs.length() - 1 ] == '\\')
			{
				multiLine = true;
				last = lhs;
				rhs[rhs.length() - 1] = ' ';
			}

			// The need for stripWhiteSpace seems to be a Qt bug.
			// make our list nice and neat.
			QStringList bits = QStringList::split(" ", rhs);
			rhs = bits.join(" ");
			if (re.cap(3) == "+=")
			{
				((*variables)[lhs] += ' ') += rhs;
			}
			else
			{
				variables->insert(lhs, rhs);
			}
		}
		else if (multiLine)
		{
			if (s[s.length()-1] == '\\')
			{
				s[s.length()-1] = ' ';
			}
			else
			{
				multiLine = false;
			}
			QStringList bits = QStringList::split(" ", s);
			((*variables)[last] += ' ') += bits.join(" ");
		}
	}
	f.close();

	QMap<QString, QString> list;

	for (QMap<QString, QString>::iterator iter = variables->begin();iter != variables->end();iter++)
	{
		QStringList items = QStringList::split(" ", iter.data());
		QMap<QString, QString> unique;
		for (uint i = 0;i < items.size();i++)
		{
			unique.insert(items[i], "");
		}
		QString line;
		for (QMap<QString, QString>::iterator it = unique.begin();it != unique.end();it++)
		{
			line += it.key() + ' ';
		}
		if (line.length() > 1)
		{
			line.setLength(line.length() - 1);
		}

		list.insert(iter.key(), line);
	}
	*variables = list;
}
コード例 #10
0
ファイル: Record.cpp プロジェクト: ruphy/plasma-studio
AbstractCommand::ReturnCodes Record::record()
{
    if (! checkInRepository())
        return NotInRepo;
    moveToRoot(CheckFileSystem);

    if (m_mode != Unset)
        m_all = m_mode == AllChanges;
    const bool needHunks = !m_all || m_patchName.isEmpty();

    ChangeSet changeSet;
    changeSet.fillFromCurrentChanges(rebasedArguments(), needHunks);

    changeSet.waitForFinishFirstFile();
    bool shouldDoRecord = changeSet.count() > 0;
    if (!shouldDoRecord) {
        Logger::warn() << "No changes!" << endl;
        return Ok;
    }

    QString email = m_author;
    if (email.isEmpty())
        email = getenv("EMAIL");
    QStringList environment;
    if (! email.isEmpty()) {
        QRegExp re("(.*) <([@\\S]+)>");
        if (re.exactMatch(email)) { // meaning its an email AND name
            environment << "GIT_AUTHOR_NAME="+ re.cap(1);
            environment << "GIT_COMMITTER_NAME="+ re.cap(1);
            environment << "GIT_AUTHOR_EMAIL="+ re.cap(2);
            environment << "GIT_COMMITTER_EMAIL="+ re.cap(2);
        }
        else if (m_author.isEmpty()) { // if its an account or shell wide option; just use the git defs.
            environment << "GIT_AUTHOR_EMAIL="+ email;
            environment << "GIT_COMMITTER_EMAIL="+ email;
        }
        else {
            Logger::error() << "Author format invalid. Please provide author formatted like; `name <email@host>\n";
            return InvalidOptions;
        }
    }

    if (shouldDoRecord && !m_all && m_mode != Index) { // then do interview
        HunksCursor cursor(changeSet);
        cursor.setConfiguration(m_config);
        Interview interview(cursor, name());
        interview.setUsePager(shouldUsePager());
        if (! interview.start()) {
            Logger::warn() << "Cancelled." << endl;
            return UserCancelled;
        }
    }

    if (shouldDoRecord && !m_all && m_mode != Index) { // check if there is anything selected
        shouldDoRecord = changeSet.hasAcceptedChanges();
        if (! shouldDoRecord) {
            Logger::warn() << "Ok, if you don't want to record anything, that's fine!" <<endl;
            return UserCancelled;
        }
    }
    if (dryRun())
        return Ok;

    if ((m_editComment || m_patchName.isEmpty()) && getenv("EDITOR")) {
        class Deleter : public QObject {
        public:
            Deleter() : commitMessage(0) { }
            ~Deleter() {
                if (commitMessage)
                    commitMessage->remove();
            }
            QFile *commitMessage;
        };
        Deleter parent;
        QFile *commitMessage;
        int i = 0;
        do {
            commitMessage = new QFile(QString("vng-record-%1").arg(i++), &parent);
        } while (commitMessage->exists());
        parent.commitMessage = commitMessage; // make sure the file is removed from FS.
        if (! commitMessage->open(QIODevice::WriteOnly)) {
            Logger::error() << "Vng failed. Could not create a temporary file for the record message '"
                << commitMessage->fileName() << "`\n";
            return WriteError;
        }
        const char * defaultCommitMessage1 = "\n***END OF DESCRIPTION***"; // we will look for this string later
        const char * defaultCommitMessage2 = "\nPlace the long patch description above the ***END OF DESCRIPTION*** marker.\n\nThis patch contains the following changes:\n\n";
        if (! m_patchName.isEmpty())
            commitMessage->write(m_patchName);
        else
            commitMessage->write("\n", 1);
        commitMessage->write(defaultCommitMessage1, strlen(defaultCommitMessage1));
        commitMessage->write(defaultCommitMessage2, strlen(defaultCommitMessage2));
        QBuffer buffer;
        changeSet.writeDiff(buffer, m_all ? ChangeSet::AllHunks : ChangeSet::UserSelection);
        ChangeSet actualChanges;
        actualChanges.fillFromDiffFile(buffer);
        QTextStream out (commitMessage);
        for (int i=0; i < actualChanges.count(); ++i) {
            File file = actualChanges.file(i);
            file.outputWhatsChanged(out, m_config, true, false);
        }
        for (int i=0; i < changeSet.count(); ++i) {
            File file = changeSet.file(i);
            if (file.isBinary() && (m_all || file.binaryChangeAcceptance() == Vng::Accepted))
                out << "M " << QString::fromLocal8Bit(file.fileName());
            else if (file.fileName().isEmpty() && (m_all || file.renameAcceptance() == Vng::Accepted))
                out << "D " << QString::fromLocal8Bit(file.oldFileName());
        }
        out.flush();

        commitMessage->close();
        QDateTime modification = QFileInfo(*commitMessage).lastModified();
        QString command = QString("%1 %2").arg(getenv("EDITOR")).arg(commitMessage->fileName());
        int rc = system(command.toAscii().data());
        if (rc != 0) {
            // this will keep patchName empty and we fall through to the interview.
            Logger::warn() << "Vng-Warning: Could not start editor '" << getenv("EDITOR") << "`\n";
            Logger::warn().flush();
        }
        else if (modification == QFileInfo(*commitMessage).lastModified()) {
            Logger::warn() << "unchanged, won't record\n";
            return UserCancelled;
        }
        else {
            // get data until the separator line.
            commitMessage->open(QIODevice::ReadOnly);
            m_patchName = commitMessage->readAll();
            commitMessage->close();
            int cuttoff = m_patchName.indexOf(defaultCommitMessage1);
            if (cuttoff > 0)
                m_patchName.truncate(cuttoff);
            for (int i = m_patchName.length()-1; i >= 0; --i) {
                if (m_patchName[i] == '\n' || m_patchName[i] == '\r' || m_patchName[i] == ' ')
                    m_patchName.resize(i); // shrink
                else break;
            }
        }
    }
    if (m_patchName.isEmpty())
        m_patchName = Interview::ask("What is the patch name? ").toUtf8();

    ReturnCodes rc = addFilesPerAcceptance(changeSet, m_all);
    if (rc != Ok)
        return rc;

    QProcess git;
    QStringList arguments;
    arguments << "write-tree";
    GitRunner runner(git, arguments);
    rc = runner.start(GitRunner::WaitForStandardOutput);
    if (rc != Ok) {
        Logger::error() << "Git write-tree failed!, aborting record\n";
        return rc;
    }
    char buf[1024];
    Vng::readLine(&git, buf, sizeof(buf));
    QString tree(buf);
    git.waitForFinished(); // patiently wait for it to finish..
    Logger::debug() << "The tree got git ref; " << tree;
    Logger::debug().flush(); // flush since we do an ask next

    arguments.clear();
    git.setEnvironment(environment);

    arguments << "commit-tree" << tree.left(40);
    if (!m_config.isEmptyRepo())
        arguments << "-p" << "HEAD" ;

    runner.setArguments(arguments);
    rc = runner.start(GitRunner::WaitUntilReadyForWrite);
    if (rc != Ok) {
        Logger::error() << "Git commit-tree failed!, aborting record\n";
        return rc;
    }
    git.write(m_patchName);
    git.write("\n");
    git.closeWriteChannel();
    Vng::readLine(&git, buf, sizeof(buf));
    QString commit(buf);
    Logger::debug() << "commit is ref; " << commit;
    git.waitForFinished(); // patiently wait for it to finish..
    if (commit.isEmpty()) {
        Logger::error() << "Git update-ref failed to produce a reference!, aborting record\n";
        return GitFailed;
    }
    m_sha1 = commit.left(40);

    arguments.clear();
    arguments << "update-ref" << "HEAD" << m_sha1;
    runner.setArguments(arguments);
    rc = runner.start(GitRunner::WaitUntilFinished);
    if (rc != Ok) {
        Logger::error() << "Git update-ref failed!, aborting record\n";
        return rc;
    }

    // We removed files from the index in case they were freshly added, but the user didn't want it in this commit.
    // we have to re-add those files.
    arguments.clear();
    arguments << "update-index" << "--add";
    for (int i=0; i < changeSet.count(); ++i) {
        File file = changeSet.file(i);
        if (! file.oldFileName().isEmpty())
            continue; // not a new added file.
        if (file.renameAcceptance() == Vng::Rejected)
            arguments.append(file.fileName());
    }
    if (arguments.count() > 2) {
        runner.setArguments(arguments);
        runner.start(GitRunner::WaitUntilFinished);
    }

    int endOfLine = m_patchName.indexOf('\n');
    if (endOfLine > 0)
        m_patchName.truncate(endOfLine);
    Logger::warn() << "Finished recording patch `" << m_patchName << "'" << endl;
    return Ok;
}
コード例 #11
0
void OutputPane::OnBuildWindowDClick(const wxString &line, int lineno)
{
	wxString fileName, strLineNumber;
	bool match = false;

	//get the selected compiler for the current line that was DClicked
	if(lineno >= (int)m_buildLineInfo.GetCount()){
		return;
	}

	//find the project selected build configuration for the workspace selected
	//configuration
	wxString projectName = m_buildLineInfo.Item(lineno);
	
	if(projectName.IsEmpty())
		return;
		
	BuildMatrixPtr matrix = ManagerST::Get()->GetWorkspaceBuildMatrix();
	wxString projecBuildConf = matrix->GetProjectSelectedConf(matrix->GetSelectedConfigurationName(), 
																				 projectName	);
	ProjectSettingsPtr settings = ManagerST::Get()->GetProject(projectName)->GetSettings();
	if(!settings)
	{
		return;
	}
	
	BuildConfigPtr  bldConf = settings->GetBuildConfiguration(projecBuildConf);
	if( !bldConf )
	{
		return;
	}
	
	wxString cmpType = bldConf->GetCompilerType();
	CompilerPtr cmp = BuildSettingsConfigST::Get()->GetCompiler(cmpType);
	if( !cmp )
	{
		return;
	}
	
	long idx;
	//try to match an error pattern to the line
	RegexProcessor re(cmp->GetErrPattern());
	cmp->GetErrFileNameIndex().ToLong(&idx);
	if(re.GetGroup(line, idx, fileName))
	{
		//we found the file name, get the line number
		cmp->GetErrLineNumberIndex().ToLong(&idx);
		re.GetGroup(line, idx, strLineNumber);
		match = true;
	}

	//try to match warning pattern
	if(!match)
	{
		RegexProcessor re(cmp->GetWarnPattern());
		cmp->GetWarnFileNameIndex().ToLong(&idx);
		if(re.GetGroup(line, idx, fileName))
		{
			//we found the file name, get the line number
			cmp->GetWarnLineNumberIndex().ToLong(&idx);
			re.GetGroup(line, idx, strLineNumber);
			match = true;
		}
	}

	if(match)
	{
		long lineNumber = -1;
		strLineNumber.ToLong(&lineNumber);

		// open the file in the editor
		// get the project name that is currently being built
		wxString projName(wxEmptyString);
		if(lineno < (int)m_buildLineInfo.GetCount())
		{
			projName = m_buildLineInfo.Item(lineno);
		}
		
		// if no project found, dont do anything
		if(projName.IsEmpty())
		{
			return;
		}

		DirSaver ds;
		ProjectPtr pro = ManagerST::Get()->GetProject(projName);
		::wxSetWorkingDirectory(pro->GetFileName().GetPath());
		wxFileName fn(fileName);
		fn.MakeAbsolute(pro->GetFileName().GetPath());

		ManagerST::Get()->OpenFile(fn.GetFullPath(), projName, lineNumber - 1 );
	}
}
コード例 #12
0
TEST(GeoLib, SurfaceIsPointInSurface)
{
    std::vector<std::function<double(double, double)>> surface_functions;
    surface_functions.push_back(constant);
    surface_functions.push_back(coscos);

    for (auto f : surface_functions) {
        std::random_device rd;

        std::string name("Surface");
        // generate ll and ur in random way
        std::mt19937 random_engine_mt19937(rd());
        std::normal_distribution<> normal_dist_ll(-10, 2);
        std::normal_distribution<> normal_dist_ur(10, 2);
        MathLib::Point3d ll(std::array<double,3>({{
                normal_dist_ll(random_engine_mt19937),
                normal_dist_ll(random_engine_mt19937),
                0.0
            }
        }));
        MathLib::Point3d ur(std::array<double,3>({{
                normal_dist_ur(random_engine_mt19937),
                normal_dist_ur(random_engine_mt19937),
                0.0
            }
        }));
        for (std::size_t k(0); k<3; ++k)
            if (ll[k] > ur[k])
                std::swap(ll[k], ur[k]);

        // random discretization of the domain
        std::default_random_engine re(rd());
        std::uniform_int_distribution<std::size_t> uniform_dist(2, 25);
        std::array<std::size_t,2> n_steps = {{uniform_dist(re),uniform_dist(re)}};

        std::unique_ptr<MeshLib::Mesh> sfc_mesh(
            MeshLib::MeshGenerator::createSurfaceMesh(
                name, ll, ur, n_steps, f
            )
        );

        // random rotation angles
        std::normal_distribution<> normal_dist_angles(
            0, boost::math::double_constants::two_pi);
        std::array<double,3> euler_angles = {{
                normal_dist_angles(random_engine_mt19937),
                normal_dist_angles(random_engine_mt19937),
                normal_dist_angles(random_engine_mt19937)
            }
        };

        MathLib::DenseMatrix<double, std::size_t> rot_mat(getRotMat(
                    euler_angles[0], euler_angles[1], euler_angles[2]));

        std::vector<MeshLib::Node*> const& nodes(sfc_mesh->getNodes());
        GeoLib::rotatePoints<MeshLib::Node>(rot_mat, nodes);

        MathLib::Vector3 const normal(0,0,1.0);
        MathLib::Vector3 const surface_normal(rot_mat * normal);
        double const eps(1e-6);
        MathLib::Vector3 const displacement(eps * surface_normal);

        GeoLib::GEOObjects geometries;
        MeshLib::convertMeshToGeo(*sfc_mesh, geometries);

        std::vector<GeoLib::Surface*> const& sfcs(*geometries.getSurfaceVec(name));
        GeoLib::Surface const*const sfc(sfcs.front());
        std::vector<GeoLib::Point*> const& pnts(*geometries.getPointVec(name));
        // test triangle edge point of the surface triangles
        for (auto const p : pnts) {
            EXPECT_TRUE(sfc->isPntInSfc(*p));
            MathLib::Point3d q(*p);
            for (std::size_t k(0); k<3; ++k)
                q[k] += displacement[k];
            EXPECT_FALSE(sfc->isPntInSfc(q));
        }
        // test edge middle points of the triangles
        for (std::size_t k(0); k<sfc->getNTriangles(); ++k) {
            MathLib::Point3d p, q, r;
            std::tie(p,q,r) = getEdgeMiddlePoints(*(*sfc)[k]);
            EXPECT_TRUE(sfc->isPntInSfc(p));
            EXPECT_TRUE(sfc->isPntInSfc(q));
            EXPECT_TRUE(sfc->isPntInSfc(r));
        }
    }
}
コード例 #13
0
 /*!
  * see http://people.w3.org/~dom/archives/2005/09/integrating-a-new-uris-scheme-handler-to-gnome-and-firefox/
  * to learn how to handle "tel:0123456" uri scheme
  *
  * tel:number is in RFC 3966
  * callto:number is unofficial (read 7.3. in RFC 3966)
  * callto://number is unofficial and used by Skype
  * we support tel:number and callto:number
  * \return true if the parameter matches RFC 3966
  */
 bool BASELIB_EXPORT isURI(const QString &string)
 {
     QRegExp re("^(tel|callto):", Qt::CaseInsensitive);
     return (! (re.indexIn(string) < 0));
 }
コード例 #14
0
ファイル: metasql.cpp プロジェクト: Wushaowei001/xtuple
bool MetaSQLQueryPrivate::parse_query(const QString & query) {
    _top = new MetaSQLBlock(this, "generic", QString::null);
    QList<MetaSQLBlock*> _blocks;
    _blocks.append(_top);
    MetaSQLBlock * _current = _top;

    QRegExp re("<\\?(.*)\\?>");
    QRegExp nw("[^\\w]"); // will find the first non word character 
    re.setMinimal(TRUE);

    QString s;

    int lastPos = 0;
    int currPos = 0;
    while(currPos >= 0) {
        currPos = re.search(query, currPos);
        if(lastPos != currPos) {
            _current->append(new MetaSQLString(this, query.mid(lastPos, (currPos==-1?query.length():currPos)-lastPos)));
        }
        if(currPos >= 0) {
            s = re.cap(1);
            s = s.stripWhiteSpace();
            int i = nw.search(s);
            QString cmd, options;
            if(i == -1) {
                cmd = s;
                options = QString::null;
            } else {
                cmd = s.left(i);
                options = s.mid(i);
            }
            cmd = cmd.lower();

            if(cmd == "endif" || cmd == "endforeach") {
                MetaSQLBlock::Block _block = _current->type();
                if(  (cmd == "endif" && (  _block == MetaSQLBlock::BlockIf
                                        || _block == MetaSQLBlock::BlockElseIf
                                        || _block == MetaSQLBlock::BlockElse) )
                  || (cmd == "endforeach" && ( _block == MetaSQLBlock::BlockForEach ) ) ) {
                    _blocks.removeLast();
                    _current = _blocks.last();
                } else {
                    // uh oh! We encountered an end block tag when we were either not in a
                    // block or were in a block of a different type.
                    *_logger << "Encountered an unexpected " << cmd << "." << endl;
                    _valid = false;
                    return false;
                }
            } else if(cmd == "if" || cmd == "foreach") {
                // we have a control statement here and need to create a new block
                MetaSQLBlock * b = new MetaSQLBlock(this, cmd, options);
                if(b->isValid()) {
                    _current->append(b);
                    _blocks.append(b);
                    _current = b;
                } else {
                    *_logger << "Failed to create new " << cmd << " block." << endl;
                    delete b;
                    _valid = false;
                    return false;
                }
            } else if(cmd == "elseif" || cmd == "else") {
                // we need to switch up are if block to include this new alternate
                if(_current->type() == MetaSQLBlock::BlockElse) {
                    *_logger << "Encountered unexpected " << cmd << " statement within else block." << endl;
                    _valid = false;
                    return false;
                } else if(_current->type() != MetaSQLBlock::BlockIf && _current->type() != MetaSQLBlock::BlockElseIf) {
                    *_logger << "Encountered unexpected " << cmd << " statement outside of if/elseif block." << endl;
                    _valid = false;
                    return false;
                } else {
                    MetaSQLBlock * b = new MetaSQLBlock(this, cmd, options);
                    if(b->isValid()) {
                        _current->setAlternate(b);
                        _blocks.removeLast();
                        _blocks.append(b);
                        _current = b;
                    } else {
                        *_logger << "Failed to create new " << cmd << " block." << endl;
                        delete b;
                        _valid = false;
                        return false;
                    }
                }
            } else {
                // we must have a function... if not then i don't know what it could be.
                // first we must parse the options into a list of parameters for the function
                options = options.stripWhiteSpace();
                QStringList plist;
                if(!options.isEmpty()) {
                    // first if we have a '(' then we will only parse out the information between it
                    // and the following ')'
                    QChar qc = options[0];
                    bool enclosed = false;
                    bool working = !enclosed;
                    bool in_string = false;
                    QChar string_starter = '"';
                    QString wip = QString::null;
                    if(qc == '(') enclosed = true;
                    working = !enclosed;
                    for(int p = 0; p < options.length(); p++) {
                        qc = options.at(p);
                        if(!working && enclosed && qc == '(') working = true;
                        else {
                            if(in_string) {
                                if(qc == '\\') {
                                    wip += options.at(++p);
                                } else if(qc == string_starter) {
                                    in_string = false;
                                } else {
                                    wip += qc;
                                }
                            } else {
                                if(qc == ',') {
                                    plist.append(wip);
                                    wip = QString::null;
                                } else if(qc.isSpace()) {
                                    // eat white space
                                } else if(qc == '\'' || qc == '"') {
                                    in_string = true;
                                    string_starter = qc;
                                } else if(enclosed && qc == ')') {
                                    working = false;
                                    break;
                                } else {
                                    wip += qc;
                                }
                            }
                        }
                    }
                    if(wip != QString::null) plist.append(wip);
                }

                MetaSQLFunction * f = new MetaSQLFunction(this, cmd, plist);
                if(f->isValid()) {
                    _current->append(f);
                } else {
                    *_logger << "Failed to create new " << cmd << " function." << endl;
                    delete f;
                    _valid = false;
                    return false;
                }
            }

            currPos += re.matchedLength();
        }
        lastPos = currPos;
    }

    _valid = true;
    return true;
}
コード例 #15
0
    virtual void send( gloox::IQ& iq, gloox::IqHandler* ih, int context )
    {
      m_context = context;
      gloox::Tag* tag = iq.tag();
      if( !tag->hasAttribute( "id" ) )
        tag->addAttribute( "id", "id" );

      switch( m_test )
      {
        case 1:
          if( tag && tag->hasAttribute( "id", "id" ) && tag->hasAttribute( "to", g_server )
               && tag->hasAttribute( "type", "get" ) && tag->hasChild( "query", "xmlns",
                                                                       gloox::XMLNS_REGISTER ) )
            m_result = true;
          m_test = 0;
          break;
        case 4:
        {
          gloox::Tag *t = 0;
          if( tag && tag->hasAttribute( "id", "id" ) && tag->hasAttribute( "to", g_server )
              && tag->hasAttribute( "type", "set" )
              && ( t = tag->findChild( "query", "xmlns", gloox::XMLNS_REGISTER ) ) != 0
              && t->hasChildWithCData( "username", "foobar" )
              && t->hasChildWithCData( "password", "password" )
              && t->hasChildWithCData( "email", "email" ) )
          {
            gloox::IQ re( gloox::IQ::Result, iq.from(), iq.id() );
            ih->handleIqID( re, context );
          }
          break;
        }
        case 6:
        {
          gloox::Tag *t = 0;
          if( tag && tag->hasAttribute( "id", "id" ) && tag->hasAttribute( "to", g_server )
               && tag->hasAttribute( "type", "set" )
               && ( ( t = tag->findChild( "query", "xmlns", gloox::XMLNS_REGISTER ) ) != 0 )
               && t->hasChild( "x", "xmlns", gloox::XMLNS_X_DATA ) )
          {
            gloox::IQ re( gloox::IQ::Result, iq.from(), iq.id() );
            ih->handleIqID( re, context );
          }
          break;
        }
        case 7:
        {
          gloox::Tag *t = 0;
          if( tag && tag->hasAttribute( "id", "id" ) && tag->hasAttribute( "to", g_server )
              && tag->hasAttribute( "type", "set" )
              && ( ( t = tag->findChild( "query", "xmlns", gloox::XMLNS_REGISTER ) ) != 0 )
              && t->hasChild( "remove" ) )
          {
            gloox::IQ re( gloox::IQ::Result, iq.from(), iq.id() );
            ih->handleIqID( re, context );
          }
          break;
        }
        case 8:
        {
          gloox::Tag *t = 0;
          if( tag && tag->hasAttribute( "id", "id" ) && tag->hasAttribute( "to", g_server )
              && tag->hasAttribute( "type", "set" )
              && ( ( t = tag->findChild( "query", "xmlns", gloox::XMLNS_REGISTER ) ) != 0 )
              && t->hasChildWithCData( "username", "foobar" )
              && t->hasChildWithCData( "password", "newpwd" ) )
          {
            gloox::IQ re( gloox::IQ::Result, iq.from(), iq.id() );
            ih->handleIqID( re, context );
          }
          break;
        }
        default:
          break;
      }
      delete tag;
    }
コード例 #16
0
ファイル: misc.cpp プロジェクト: serghei/kde3-kdevelop
/**
 * Add entries to a variable. Will just add the variables to the existing line, removing duplicates
 * Will preserve += constructs and make sure that the variable only has one copy of the value across
 * all += constructs
 * @param fileName
 * @param variables key=value string of entries to add
 * @param add true= add these key,value pairs, false = remove. You can have empty values for an add - the whole line is
 * removed. For adding, we will not add an empty line.
 */
void AutoProjectTool::addRemoveMakefileam(const QString &fileName, QMap<QString, QString> variables,  bool add)
{
	// input file reading
	QFile fin(fileName);
	if (!fin.open(IO_ReadOnly))
	{
		return ;
	}
	QTextStream ins(&fin);

	// output file writing.
	QFile fout(fileName + "#");
	if (!fout.open(IO_WriteOnly))
	{
		fin.close();
		return ;
	}
	QTextStream outs(&fout);

	// variables
	QRegExp re("^(#kdevelop:[ \t]*)?([A-Za-z][@A-Za-z0-9_]*)[ \t]*([:\\+]?=)[ \t]*(.*)$");

	// build key=map of values to add
	// map can be empty.we never add an empty key, but do remove empty keys from the file..
	QDict< QMap<QString, bool> > interest;
	for (QMap<QString, QString>::Iterator it0 = variables.begin(); it0 != variables.end(); ++it0)
	{
		kdDebug(9020) << "key (" << add<<"): " << it0.key() << "="<< it0.data() << endl;

		QMap<QString, bool>* set = new QMap<QString, bool>();
		if (!it0.data().stripWhiteSpace().isEmpty())
		{
			QStringList variableList = QStringList::split(' ', it0.data());

			for (uint i = 0; i < variableList.count(); i++)
			{
				set->insert(variableList[i], true);
			}
		}
		interest.insert(it0.key(), set);
	}

	bool multiLine = false;
	QString lastLhs;
	QStringList lastRhs;
	QMap<QString, QString> seenLhs;
	while (!fin.atEnd())
	{
		QString s = ins.readLine();
		if (re.exactMatch(s))
		{
			QString lhs = re.cap(2);
			QMap<QString, bool>* ourRhs = interest.find(lhs);

			if (!ourRhs)
			{
				// not interested in this line at all
				// write it out as is..
				outs << s << endl;
			}
			else
			{
				// we are interested in this line..
				QString rhs = re.cap(4).stripWhiteSpace();
				if (rhs[ rhs.length() - 1 ] == '\\')
				{
					// save it for when we have the whole line..
					multiLine = true;
					lastLhs = lhs;
					rhs.setLength(rhs.length() - 1);
					lastRhs += QStringList::split(" ", rhs);
				}
				else
				{
					// deal with it now.

					QStringList bits = QStringList::split(" ", rhs);
					if (add)
					{
						// we are adding our interested values to this line and writing it

						// add this line to we we want to add to remove duplicates.
						for (uint index = 0; index < bits.size(); index++)
						{
							QMap<QString, bool>::iterator findEntry = ourRhs->find(bits[index]);
							if (findEntry == ourRhs->end())
							{
								// we haven't seen it, so add it, so we don't add it again later..
								ourRhs->insert(bits[index], true);
							}
							// else we have this value in our 'to add list' , it is either already been
							// added, so we don't want to add it again, or it hasn't been added, in which
							// case we will do so soon. so we can ignore this now..
						}
						// now write the line out if it is not going to be empty.
						QString newLine(lhs);
						if (seenLhs.find(lhs) == seenLhs.end())
						{
							newLine += " = ";
							seenLhs[lhs] = "";
						}
						else
						{
							newLine += " += ";
						}

						int len = newLine.length();
						bool added = false;
						QValueList<QString> keys = ourRhs->keys();
						for (uint count = 0; count < keys.size(); count++)
						{
							// if out entry is true, add it..
							if ((*ourRhs)[keys[count]])
							{
								added = true;
								len += keys[count].length() + 1;
								if (len > 80)
								{
									newLine += "\\\n\t";
									len = 8;
								}
								newLine += keys[count];
								newLine += ' ';
								// set our value so we don't add it again.
								(*ourRhs)[keys[count]] = false;
							}
						}
						// only print it out if there was a value to add..
						if (added)
						{
							newLine.setLength(newLine.length() - 1);
							outs << newLine << endl;
						}
					}
					else
					{
						// we are removing our interested values from this line

						// special case - no values, remove the line..
						if (!ourRhs->empty())
						{
							// check if any of these values are down to remove.
							QString newLine(lhs);
							if (seenLhs.find(lhs) == seenLhs.end())
							{
								newLine += " = ";
								seenLhs[lhs] = "";
							}
							else
							{
								newLine += " += ";
							}

							int len = newLine.length();
							bool added = false;
							for (QStringList::Iterator posIter = bits.begin(); posIter != bits.end();posIter++)
							{
								QMap<QString, bool>::iterator findEntry = ourRhs->find(*posIter);
								if (findEntry == ourRhs->end())
								{
									// we do not want to remove it..
									added = true;
									len += (*posIter).length() + 1;
									if (len > 80)
									{
										newLine += "\\\n\t";
										len = 8;
									}
									newLine += (*posIter);
									newLine += ' ';
								}
								// else we have this value in our 'to remove list', so don't add it.
							}
							// only print it out if there was a value on it..
							if (added)
							{
								newLine.setLength(newLine.length() - 1);
								outs << newLine << endl;
							}
						}
					}//if (add)
				}//if ( rhs[ rhs.length() - 1 ] == '\\'  )
			}//if ( found == interest.end())
		}
		else if (multiLine)
		{
			s = s.stripWhiteSpace();
			// we are only here if were interested in this line..
			if (s[s.length()-1] == '\\')
			{
				s.setLength(s.length() - 1);
				// still more multi line we wait for..
			}
			else
			{
				// end of the multi line..
				multiLine = false;
			}
			lastRhs += QStringList::split(" ", s);

			if (!multiLine)
			{
				// now we have to deal with this multiLine value..
				// ourRhs will always be a value, as we only get multiLine if we're interested in it..
				QMap<QString, bool>* ourRhs = interest.find(lastLhs);

				if (add)
				{
					// we are adding our interested values to this line and writing it

					// add this line to we we want to add to remove duplicates.
					for (uint index = 0; index < lastRhs.size(); index++)
					{
						QMap<QString, bool>::iterator findEntry = ourRhs->find(lastRhs[index]);
						if (findEntry == ourRhs->end())
						{
							// we haven't seen it, so add it, so we don't add it again later..
							ourRhs->insert(lastRhs[index], true);
						}
						// else we have this value in our 'to add list' , it is either already been
						// added, so we don't want to add it again, or it hasn't been added, in which
						// case we will do so soon. so we can ignore this now..
					}
					// now write the line out if it is not going to be empty.
					QString newLine(lastLhs);
					if (seenLhs.find(lastLhs) == seenLhs.end())
					{
						newLine += " = ";
						seenLhs[lastLhs] = "";
					}
					else
					{
						newLine += " += ";
					}

					int len = newLine.length();
					bool added = false;
					QValueList<QString> keys = ourRhs->keys();
					for (uint count = 0; count < keys.size(); count++)
					{
						// if out entry is true, add it..
						if ((*ourRhs)[keys[count]])
						{
							added = true;
							len += keys[count].length() + 1;
							if (len > 80)
							{
								newLine += "\\\n\t";
								len = 8;
							}
							newLine += keys[count];
							newLine += ' ';
							// set our value so we don't add it again.
							(*ourRhs)[keys[count]] = false;
						}
					}
					// only print it out if there was a value to add..
					if (added)
					{
						newLine.setLength(newLine.length() - 1);
						outs << newLine << endl;
					}
				}
				else
				{
					// we are removing our interested values from this line
					// special case - no values, remove the line..
					if (!ourRhs->empty())
					{
						// check if any of these values are down to remove.
						QString newLine(lastLhs);
						if (seenLhs.find(lastLhs) == seenLhs.end())
						{
							newLine += " = ";
							seenLhs[lastLhs] = "";
						}
						else
						{
							newLine += " += ";
						}
						int len = newLine.length();
						bool added = false;
						for (QStringList::Iterator posIter = lastRhs.begin(); posIter != lastRhs.end();posIter++)
						{
							QMap<QString, bool>::iterator findEntry = ourRhs->find(*posIter);
							if (findEntry == ourRhs->end())
							{
								// we do not want to remove it..
								added = true;
								len += (*posIter).length() + 1;
								if (len > 80)
								{
									newLine += "\\\n\t";
									len = 8;
								}
								newLine += (*posIter);
								newLine += ' ';
							}
							// else we have this value in our 'to remove list', so don't add it.
						}
						// only print it out if there was a value on it..
						if (added)
						{
							newLine.setLength(newLine.length() - 1);
							outs << newLine << endl;
						}
					}
				}

				lastLhs.setLength(0);
				lastRhs.clear();
			}
		}
		else
		{
			// can write this line out..
			// not a match, not a multi line,
			outs << s << endl;
		}
	}

	if (add)
	{
		QDictIterator<QMap<QString, bool> > it(interest);
		for (; it.current(); ++it)
		{
			QString lhs = it.currentKey();
			QMap<QString, bool>* ourRhs = it.current();

			QString newLine(lhs);
			if (seenLhs.find(lhs) == seenLhs.end())
			{
				newLine += " = ";
				seenLhs[lastLhs] = "";
			}
			else
			{
				newLine += " += ";
			}
			int len = newLine.length();
			bool added = false;
			QValueList<QString> keys = ourRhs->keys();
			for (uint count = 0; count < keys.size(); count++)
			{
				if ((*ourRhs)[keys[count]])
				{
					added = true;
					len += keys[count].length() + 1;
					if (len > 80)
					{
						newLine += "\\\n\t";
						len = 8;
					}
					newLine += keys[count];
					newLine += ' ';
					// set our value so we don't add it again.
					(*ourRhs)[keys[count]] = false;
				}
			}
			// only print it out if there was a value to add..
			if (added)
			{
				newLine.setLength(newLine.length() - 1);
				outs << newLine << endl;
			}
		}
	}
	interest.setAutoDelete(true);
	interest.clear();

	fin.close();
	fout.close();

	QDir().rename(fileName + "#", fileName);
}
コード例 #17
0
ファイル: Exception_Test.cpp プロジェクト: rainbru/rainbrurpg
TEST( Exception, one_param )
{
  RainbrurpgException re("aze");
  cout << re.what();
  EXPECT_STREQ( re.what(), "aze");
}
コード例 #18
0
ファイル: kateprinter.cpp プロジェクト: niteshnarayanlal/Kate
bool KatePrinter::print (KateDocument *doc)
{
  QPrinter printer;
  readSettings(printer);

  // docname is now always there, including the right Untitled name
  printer.setDocName(doc->documentName());

  KatePrintTextSettings *kpts = new KatePrintTextSettings;
  KatePrintHeaderFooter *kphf = new KatePrintHeaderFooter;
  KatePrintLayout *kpl = new KatePrintLayout;

  QList<QWidget*> tabs;
  tabs << kpts;
  tabs << kphf;
  tabs << kpl;

  QWidget *parentWidget=doc->widget();

  if ( !parentWidget )
    parentWidget=QApplication::activeWindow();

  QScopedPointer<QPrintDialog> printDialog(KdePrint::createPrintDialog(&printer, KdePrint::SystemSelectsPages, tabs, parentWidget));

  if ( doc->activeView()->selection() ) {
    printer.setPrintRange(QPrinter::Selection);
    printDialog->setOption(QAbstractPrintDialog::PrintSelection, true);
  }

  if ( printDialog->exec() )
  {
    writeSettings(printer);

    KateRenderer renderer(doc, doc->activeKateView());
    renderer.config()->setSchema (kpl->colorScheme());
    renderer.setPrinterFriendly(true);

    QPainter paint( &printer );
    /*
     *        We work in tree cycles:
     *        1) initialize variables and retrieve print settings
     *        2) prepare data according to those settings
     *        3) draw to the printer
     */
    uint pdmWidth = printer.width();
    uint pdmHeight = printer.height();
    int y = 0;
    uint xstart = 0; // beginning point for painting lines
    uint lineCount = 0;
    uint maxWidth = pdmWidth;
    int headerWidth = pdmWidth;
    int startCol = 0;
    int endCol = 0;
    bool pageStarted = true;
    int remainder = 0; // remaining sublines from a wrapped line (for the top of a new page)

    // Text Settings Page
    bool selectionOnly = (printDialog->printRange() == QAbstractPrintDialog::Selection);
    bool useGuide = kpts->printGuide();

    bool printLineNumbers = kpts->printLineNumbers();
    uint lineNumberWidth( 0 );

    // Header/Footer Page
    QFont headerFont(kphf->font()); // used for header/footer

    bool useHeader = kphf->useHeader();
    QColor headerBgColor(kphf->headerBackground());
    QColor headerFgColor(kphf->headerForeground());
    uint headerHeight( 0 ); // further init only if needed
    QStringList headerTagList; // do
    bool headerDrawBg = false; // do

    bool useFooter = kphf->useFooter();
    QColor footerBgColor(kphf->footerBackground());
    QColor footerFgColor(kphf->footerForeground());
    uint footerHeight( 0 ); // further init only if needed
    QStringList footerTagList; // do
    bool footerDrawBg = false; // do

    // Layout Page
    renderer.config()->setSchema( kpl->colorScheme() );
    bool useBackground = kpl->useBackground();
    bool useBox = kpl->useBox();
    int boxWidth(kpl->boxWidth());
    QColor boxColor(kpl->boxColor());
    int innerMargin = useBox ? kpl->boxMargin() : 6;

    // Post initialization
    int maxHeight = (useBox ? pdmHeight-innerMargin : pdmHeight);
    uint currentPage( 1 );
    uint lastline = doc->lastLine(); // necessary to print selection only
    uint firstline( 0 );
    const int fontHeight = renderer.fontHeight();
    KTextEditor::Range selectionRange;

    /*
    *        Now on for preparations...
    *        during preparations, variable names starting with a "_" means
    *        those variables are local to the enclosing block.
    */
    {
      if ( selectionOnly )
      {
        // set a line range from the first selected line to the last
        selectionRange = doc->activeView()->selectionRange();
        firstline = selectionRange.start().line();
        lastline = selectionRange.end().line();
        lineCount = firstline;
      }

      if ( printLineNumbers )
      {
        // figure out the horiizontal space required
        QString s( QString("%1 ").arg( doc->lines() ) );
        s.fill('5', -1); // some non-fixed fonts haven't equally wide numbers
        // FIXME calculate which is actually the widest...
        lineNumberWidth = renderer.currentFontMetrics().width( s );
        // a small space between the line numbers and the text
        int _adj = renderer.currentFontMetrics().width( "5" );
        // adjust available width and set horizontal start point for data
        maxWidth -= (lineNumberWidth + _adj);
        xstart += lineNumberWidth + _adj;
      }

      if ( useHeader || useFooter )
      {
        // Set up a tag map
        // This retrieves all tags, ued or not, but
        // none of theese operations should be expensive,
        // and searcing each tag in the format strings is avoided.
        QDateTime dt = QDateTime::currentDateTime();
        QMap<QString,QString> tags;

        KUser u (KUser::UseRealUserID);
        tags["u"] = u.loginName();

        tags["d"] = KGlobal::locale()->formatDateTime(dt, KLocale::ShortDate);
        tags["D"] =  KGlobal::locale()->formatDateTime(dt, KLocale::LongDate);
        tags["h"] =  KGlobal::locale()->formatTime(dt.time(), false);
        tags["y"] =  KGlobal::locale()->formatDate(dt.date(), KLocale::ShortDate);
        tags["Y"] =  KGlobal::locale()->formatDate(dt.date(), KLocale::LongDate);
        tags["f"] =  doc->url().fileName();
        tags["U"] =  doc->url().prettyUrl();
        if ( selectionOnly )
        {
          QString s( i18n("(Selection of) ") );
          tags["f"].prepend( s );
          tags["U"].prepend( s );
        }

        QRegExp reTags( "%([dDfUhuyY])" ); // TODO tjeck for "%%<TAG>"

        if (useHeader)
        {
          headerDrawBg = kphf->useHeaderBackground();
          headerHeight = QFontMetrics( headerFont ).height();
          if ( useBox || headerDrawBg )
            headerHeight += innerMargin * 2;
          else
            headerHeight += 1 + QFontMetrics( headerFont ).leading();

          headerTagList = kphf->headerFormat();
          QMutableStringListIterator it(headerTagList);
          while ( it.hasNext() ) {
            QString tag = it.next();
            int pos = reTags.indexIn( tag );
            QString rep;
            while ( pos > -1 )
            {
              rep = tags[reTags.cap( 1 )];
              tag.replace( (uint)pos, 2, rep );
              pos += rep.length();
              pos = reTags.indexIn( tag, pos );
            }
            it.setValue( tag );
          }

          if (!headerBgColor.isValid())
            headerBgColor = Qt::lightGray;
          if (!headerFgColor.isValid())
            headerFgColor = Qt::black;
        }

        if (useFooter)
        {
          footerDrawBg = kphf->useFooterBackground();
          footerHeight = QFontMetrics( headerFont ).height();
          if ( useBox || footerDrawBg )
            footerHeight += 2*innerMargin;
          else
            footerHeight += 1; // line only

          footerTagList = kphf->footerFormat();
          QMutableStringListIterator it(footerTagList);
          while ( it.hasNext() ) {
            QString tag = it.next();
            int pos = reTags.indexIn( tag );
            QString rep;
            while ( pos > -1 )
            {
              rep = tags[reTags.cap( 1 )];
              tag.replace( (uint)pos, 2, rep );
              pos += rep.length();
              pos = reTags.indexIn( tag, pos );
            }
            it.setValue( tag );
          }

          if (!footerBgColor.isValid())
            footerBgColor = Qt::lightGray;
          if (!footerFgColor.isValid())
            footerFgColor = Qt::black;
          // adjust maxheight, so we can know when/where to print footer
          maxHeight -= footerHeight;
        }
      } // if ( useHeader || useFooter )

      if ( useBackground )
      {
        if ( ! useBox )
        {
          xstart += innerMargin;
          maxWidth -= innerMargin * 2;
        }
      }

      if ( useBox )
      {
        if (!boxColor.isValid())
          boxColor = Qt::black;
        if (boxWidth < 1) // shouldn't be pssible no more!
          boxWidth = 1;
        // set maxwidth to something sensible
        maxWidth -= ( ( boxWidth + innerMargin )  * 2 );
        xstart += boxWidth + innerMargin;
        // maxheight too..
        maxHeight -= boxWidth;
      }
      else
        boxWidth = 0;

      // now that we know the vertical amount of space needed,
      // it is possible to calculate the total number of pages
      // if needed, that is if any header/footer tag contains "%P".
      if ( !headerTagList.filter("%P").isEmpty() || !footerTagList.filter("%P").isEmpty() )
      {
        kDebug(13020)<<"'%P' found! calculating number of pages...";
        int pageHeight = maxHeight;
        if ( useHeader )
          pageHeight -= ( headerHeight + innerMargin );
        if ( useFooter )
          pageHeight -= innerMargin;
        const int linesPerPage = pageHeight / fontHeight;
//         kDebug() << "Lines per page:" << linesPerPage;
        
        // calculate total layouted lines in the document
        int totalLines = 0;
        // TODO: right now ignores selection printing
        for (int i = firstline; i <= lastline; ++i) {
          KateLineLayoutPtr rangeptr(new KateLineLayout(doc));
          rangeptr->setLine(i);
          renderer.layoutLine(rangeptr, (int)maxWidth, false);
          totalLines += rangeptr->viewLineCount();
        }
        int totalPages = (totalLines / linesPerPage)
                      + ((totalLines % linesPerPage) > 0 ? 1 : 0);
//         kDebug() << "_______ pages:" << (totalLines / linesPerPage);
//         kDebug() << "________ rest:" << (totalLines % linesPerPage);

        // TODO: add space for guide if required
//         if ( useGuide )
//           _lt += (guideHeight + (fontHeight /2)) / fontHeight;

        // substitute both tag lists
        QString re("%P");
        QStringList::Iterator it;
        for ( it=headerTagList.begin(); it!=headerTagList.end(); ++it )
          (*it).replace( re, QString( "%1" ).arg( totalPages ) );
        for ( it=footerTagList.begin(); it!=footerTagList.end(); ++it )
          (*it).replace( re, QString( "%1" ).arg( totalPages ) );
      }
    } // end prepare block

     /*
        On to draw something :-)
     */
    while (  lineCount <= lastline  )
    {
      startCol = 0;
      endCol = 0;

      if ( y + fontHeight > maxHeight )
      {
        kDebug(13020)<<"Starting new page,"<<lineCount<<"lines up to now.";
        printer.newPage();
        paint.resetTransform();
        currentPage++;
        pageStarted = true;
        y=0;
      }

      if ( pageStarted )
      {
        if ( useHeader )
        {
          paint.setPen(headerFgColor);
          paint.setFont(headerFont);
          if ( headerDrawBg )
            paint.fillRect(0, 0, headerWidth, headerHeight, headerBgColor);
          if (headerTagList.count() == 3)
          {
            int valign = ( (useBox||headerDrawBg||useBackground) ?
            Qt::AlignVCenter : Qt::AlignTop );
            int align = valign|Qt::AlignLeft;
            int marg = ( useBox || headerDrawBg ) ? innerMargin : 0;
            if ( useBox ) marg += boxWidth;
            QString s;
            for (int i=0; i<3; i++)
            {
              s = headerTagList[i];
              if (s.indexOf("%p") != -1) s.replace("%p", QString::number(currentPage));
              paint.drawText(marg, 0, headerWidth-(marg*2), headerHeight, align, s);
              align = valign|(i == 0 ? Qt::AlignHCenter : Qt::AlignRight);
            }
          }
          if ( ! ( headerDrawBg || useBox || useBackground ) ) // draw a 1 px (!?) line to separate header from contents
          {
            paint.drawLine( 0, headerHeight-1, headerWidth, headerHeight-1 );
            //y += 1; now included in headerHeight
          }
          y += headerHeight + innerMargin;
        }

        if ( useFooter )
        {
          paint.setPen(footerFgColor);
          if ( ! ( footerDrawBg || useBox || useBackground ) ) // draw a 1 px (!?) line to separate footer from contents
            paint.drawLine( 0, maxHeight + innerMargin - 1, headerWidth, maxHeight + innerMargin - 1 );
          if ( footerDrawBg )
            paint.fillRect(0, maxHeight+innerMargin+boxWidth, headerWidth, footerHeight, footerBgColor);
          if (footerTagList.count() == 3)
          {
            int align = Qt::AlignVCenter|Qt::AlignLeft;
            int marg = ( useBox || footerDrawBg ) ? innerMargin : 0;
            if ( useBox ) marg += boxWidth;
            QString s;
            for (int i=0; i<3; i++)
            {
              s = footerTagList[i];
              if (s.indexOf("%p") != -1) s.replace("%p", QString::number(currentPage));
              paint.drawText(marg, maxHeight+innerMargin, headerWidth-(marg*2), footerHeight, align, s);
              align = Qt::AlignVCenter|(i == 0 ? Qt::AlignHCenter : Qt::AlignRight);
            }
          }
        } // done footer

        if ( useBackground )
        {
          // If we have a box, or the header/footer has backgrounds, we want to paint
          // to the border of those. Otherwise just the contents area.
          int _y = y, _h = maxHeight - y;
          if ( useBox )
          {
            _y -= innerMargin;
            _h += 2 * innerMargin;
          }
          else
          {
            if ( headerDrawBg )
            {
              _y -= innerMargin;
              _h += innerMargin;
            }
            if ( footerDrawBg )
            {
              _h += innerMargin;
            }
          }
          paint.fillRect( 0, _y, pdmWidth, _h, renderer.config()->backgroundColor());
        }

        if ( useBox )
        {
          paint.setPen(QPen(boxColor, boxWidth));
          paint.drawRect(0, 0, pdmWidth, pdmHeight);
          if (useHeader)
            paint.drawLine(0, headerHeight, headerWidth, headerHeight);
          else
            y += innerMargin;

          if ( useFooter ) // drawline is not trustable, grr.
            paint.fillRect( 0, maxHeight+innerMargin, headerWidth, boxWidth, boxColor );
        }

        if ( useGuide && currentPage == 1 )
        {  // FIXME - this may span more pages...
          // draw a box unless we have boxes, in which case we end with a box line
          int _ystart = y;
          QString _hlName = doc->highlight()->name();

          QList<KateExtendedAttribute::Ptr> _attributes; // list of highlight attributes for the legend
          doc->highlight()->getKateExtendedAttributeList(kpl->colorScheme(), _attributes);

          KateAttributeList _defaultAttributes;
          KateHlManager::self()->getDefaults ( renderer.config()->schema(), _defaultAttributes );

          QColor _defaultPen = _defaultAttributes.at(0)->foreground().color();
          paint.setPen(_defaultPen);

          int _marg = 0;
          if ( useBox )
            _marg += (2*boxWidth) + (2*innerMargin);
          else
          {
            if ( useBackground )
              _marg += 2*innerMargin;
            _marg += 1;
            y += 1 + innerMargin;
          }

          // draw a title string
          QFont _titleFont = renderer.config()->font();
          _titleFont.setBold(true);
          paint.setFont( _titleFont );
          QRect _r;
          paint.drawText( QRect(_marg, y, pdmWidth-(2*_marg), maxHeight - y),
            Qt::AlignTop|Qt::AlignHCenter,
            i18n("Typographical Conventions for %1", _hlName ), &_r );
          int _w = pdmWidth - (_marg*2) - (innerMargin*2);
          int _x = _marg + innerMargin;
          y += _r.height() + innerMargin;
          paint.drawLine( _x, y, _x + _w, y );
          y += 1 + innerMargin;

          int _widest( 0 );
          foreach (const KateExtendedAttribute::Ptr &attribute, _attributes)
            _widest = qMax(QFontMetrics(attribute->font()).width(attribute->name().section(':',1,1)), _widest);

          int _guideCols = _w/( _widest + innerMargin );

          // draw attrib names using their styles
          int _cw = _w/_guideCols;
          int _i(0);

          _titleFont.setUnderline(true);
          QString _currentHlName;
          foreach (const KateExtendedAttribute::Ptr &attribute, _attributes)
          {
            QString _hl = attribute->name().section(':',0,0);
            QString _name = attribute->name().section(':',1,1);
            if ( _hl != _hlName && _hl != _currentHlName ) {
              _currentHlName = _hl;
              if ( _i%_guideCols )
                y += fontHeight;
              y += innerMargin;
              paint.setFont(_titleFont);
              paint.setPen(_defaultPen);
              paint.drawText( _x, y, _w, fontHeight, Qt::AlignTop, _hl + ' ' + i18n("text") );
              y += fontHeight;
              _i = 0;
            }

            KTextEditor::Attribute _attr =  *_defaultAttributes[attribute->defaultStyleIndex()];
            _attr += *attribute;
            paint.setPen( _attr.foreground().color() );
            paint.setFont( _attr.font() );

            if (_attr.hasProperty(QTextFormat::BackgroundBrush) ) {
              QRect _rect = QFontMetrics(_attr.font()).boundingRect(_name);
              _rect.moveTo(_x + ((_i%_guideCols)*_cw), y);
               paint.fillRect(_rect, _attr.background() );
            }

            paint.drawText(( _x + ((_i%_guideCols)*_cw)), y, _cw, fontHeight, Qt::AlignTop, _name );

            _i++;
            if ( _i && ! ( _i%_guideCols ) )
              y += fontHeight;
          }

          if ( _i%_guideCols )
            y += fontHeight;// last row not full

          // draw a box around the legend
          paint.setPen ( _defaultPen );
          if ( useBox )
            paint.fillRect( 0, y+innerMargin, headerWidth, boxWidth, boxColor );
          else
          {
            _marg -=1;
            paint.drawRect( _marg, _ystart, pdmWidth-(2*_marg), y-_ystart+innerMargin );
          }

          y += ( useBox ? boxWidth : 1 ) + (innerMargin*2);
        } // useGuide

        paint.translate(xstart,y);
        pageStarted = false;
      } // pageStarted; move on to contents:)
コード例 #19
0
ファイル: Exception_Test.cpp プロジェクト: rainbru/rainbrurpg
TEST( Exception, three_param )
{
  RainbrurpgException re("This is a ", "real", " message");
  cout << re.what();
  EXPECT_STREQ( re.what(), "This is a real message");
}
コード例 #20
0
ファイル: ItemSetBuilder.cpp プロジェクト: Albeforia/Pitaya
	void ItemSetBuilder::report(bool graph) const {
		std::ofstream file, gfile;
		file.open("report\\lalr_states", std::ios::trunc);
		if (graph) {
			gfile.open("report\\graph\\lalr.dot", std::ios::trunc);
		}
		if (file.is_open()) {
			if (gfile.is_open()) {
				gfile << "digraph lalr_graph {\n" << "node [shape=record];\n";
			}
			std::string dot = "[>";
			for (auto& p : m_sorted) {
				auto& state = *p.second;
				file << "[state " << state.m_id << "]\n";
				std::string gitems;
				for (auto& item : state.m_closure) {
					if (!item.is_kernel()) continue;
					auto& p = m_grammar.get_production(item.production_id());
					std::string pstr(p[0].name());
					pstr.append(" ==> ");
					for (std::size_t i = 0; i <= p.rhs_count(); i++) {
						if (i == item.dot()) {
							pstr.append(dot);
						}
						if (i < p.rhs_count()) {
							pstr.append(p[i + 1].name()).append(" ");
						}
					}
					file << ">\t" << std::setw(20) << pstr << "\n\t\t";

					std::string lookaheads;
					auto cols = 4, col = 0;
					for (auto it = m_grammar.symbol_begin(); it != m_grammar.symbol_end(); it++) {
						if (item.lookaheads()[**it]) {
							file << **it << "\t";
							lookaheads.append((**it).name()).append(" ");
							if (++col == cols) {
								col = 0;
								lookaheads.append("\\n");
							}
						}
					}
					file << "\n";

					std::regex re("[|<>{}]");
					pstr = std::regex_replace(pstr, re, "\\$&");
					lookaheads = std::regex_replace(lookaheads, re, "\\$&");
					gitems.append("{ ").append(pstr).append(" | ")
						.append(lookaheads).append("}|");
				}
				file << '\n';
				if (gfile.is_open()) {
					if (gitems.size() > 0) {
						// remove the last '|'
						gitems.erase(gitems.size() - 1);
					}
					gfile << state.m_id << " [label=\"" << state.m_id << "|{"
						<< gitems << "}\"];\n";
				}

				for (auto& action : state.m_actions) {
					file << ">\t" << std::setw(30)
						<< std::left << m_grammar.get_symbol(action.first)
						<< std::right << action.second.type;
					if (action.second.type == ActionType::SHIFT
						|| action.second.type == ActionType::GOTO) {
						file << std::setw(10) << "[ state " << action.second.value << " ]";
						if (gfile.is_open()) {
							gfile << state.m_id << " -> " << action.second.value
								<< " [label=\"" << m_grammar.get_symbol(action.first) << "\"];\n";
						}
					}
					else if (action.second.type == ActionType::REDUCE) {
						file << std::setw(10) << "[ " << m_grammar.get_production(action.second.value) << " ]";
					}
					file << '\n';
				}
				file << '\n';
			}
			file << "Total conflicts: " << m_conflict_count << '\n';
			if (gfile.is_open()) {
				gfile << "}\n";
			}
		}
		file.close();
		if (graph) {
			gfile.close();
		}
	}
コード例 #21
0
ファイル: userinterfaceform.cpp プロジェクト: Grokafar/qTox
/**
 * @brief Constructor of UserInterfaceForm.
 * @param myParent Setting widget which will contain this form as tab.
 *
 * Restores all controls from the settings.
 */
UserInterfaceForm::UserInterfaceForm(SettingsWidget* myParent)
    : GenericForm(QPixmap(":/img/settings/general.png"))
{
    parent = myParent;

    bodyUI = new Ui::UserInterfaceSettings;
    bodyUI->setupUi(this);

    // block all child signals during initialization
    const RecursiveSignalBlocker signalBlocker(this);

    Settings& s = Settings::getInstance();
    const QFont chatBaseFont = s.getChatMessageFont();
    bodyUI->txtChatFontSize->setValue(QFontInfo(chatBaseFont).pixelSize());
    bodyUI->txtChatFont->setCurrentFont(chatBaseFont);
    int index = static_cast<int>(s.getStylePreference());
    bodyUI->textStyleComboBox->setCurrentIndex(index);

    bool showWindow = s.getShowWindow();

    bodyUI->showWindow->setChecked(showWindow);
    bodyUI->showInFront->setChecked(s.getShowInFront());
    bodyUI->showInFront->setEnabled(showWindow);

    bodyUI->groupAlwaysNotify->setChecked(s.getGroupAlwaysNotify());
    bodyUI->cbGroupchatPosition->setChecked(s.getGroupchatPosition());
    bodyUI->cbCompactLayout->setChecked(s.getCompactLayout());
    bodyUI->cbSeparateWindow->setChecked(s.getSeparateWindow());
    bodyUI->cbDontGroupWindows->setChecked(s.getDontGroupWindows());
    bodyUI->cbDontGroupWindows->setEnabled(s.getSeparateWindow());

    bodyUI->useEmoticons->setChecked(s.getUseEmoticons());
    for (auto entry : SmileyPack::listSmileyPacks())
        bodyUI->smileyPackBrowser->addItem(entry.first, entry.second);

    smileLabels = {bodyUI->smile1, bodyUI->smile2, bodyUI->smile3, bodyUI->smile4, bodyUI->smile5};

    int currentPack = bodyUI->smileyPackBrowser->findData(s.getSmileyPack());
    bodyUI->smileyPackBrowser->setCurrentIndex(currentPack);
    reloadSmileys();
    bodyUI->smileyPackBrowser->setEnabled(bodyUI->useEmoticons->isChecked());

    bodyUI->styleBrowser->addItem(tr("None"));
    bodyUI->styleBrowser->addItems(QStyleFactory::keys());

    QString style;
    if (QStyleFactory::keys().contains(s.getStyle()))
        style = s.getStyle();
    else
        style = tr("None");

    bodyUI->styleBrowser->setCurrentText(style);

    for (QString color : Style::getThemeColorNames())
        bodyUI->themeColorCBox->addItem(color);

    bodyUI->themeColorCBox->setCurrentIndex(s.getThemeColor());
    bodyUI->emoticonSize->setValue(s.getEmojiFontPointSize());

    QLocale ql;
    QStringList timeFormats;
    timeFormats << ql.timeFormat(QLocale::ShortFormat) << ql.timeFormat(QLocale::LongFormat)
                << "hh:mm AP"
                << "hh:mm:ss AP"
                << "hh:mm:ss";
    timeFormats.removeDuplicates();
    bodyUI->timestamp->addItems(timeFormats);

    QRegularExpression re(QString("^[^\\n]{0,%0}$").arg(MAX_FORMAT_LENGTH));
    QRegularExpressionValidator* validator = new QRegularExpressionValidator(re, this);
    QString timeFormat = s.getTimestampFormat();

    if (!re.match(timeFormat).hasMatch())
        timeFormat = timeFormats[0];

    bodyUI->timestamp->setCurrentText(timeFormat);
    bodyUI->timestamp->setValidator(validator);
    on_timestamp_editTextChanged(timeFormat);

    QStringList dateFormats;
    dateFormats << QStringLiteral("yyyy-MM-dd") // ISO 8601
                // format strings from system locale
                << ql.dateFormat(QLocale::LongFormat) << ql.dateFormat(QLocale::ShortFormat)
                << ql.dateFormat(QLocale::NarrowFormat) << "dd-MM-yyyy"
                << "d-MM-yyyy"
                << "dddd dd-MM-yyyy"
                << "dddd d-MM";

    dateFormats.removeDuplicates();
    bodyUI->dateFormats->addItems(dateFormats);

    QString dateFormat = s.getDateFormat();
    if (!re.match(dateFormat).hasMatch())
        dateFormat = dateFormats[0];

    bodyUI->dateFormats->setCurrentText(dateFormat);
    bodyUI->dateFormats->setValidator(validator);
    on_dateFormats_editTextChanged(dateFormat);

    eventsInit();
    Translator::registerHandler(std::bind(&UserInterfaceForm::retranslateUi, this), this);
}
コード例 #22
0
 /** Get vector of imaginary parts */
 vector<double> vector<complex>::imag() const 
 {
     gsl_vector_view r = gsl_vector_complex_imag(_vector);
     vector<double> re((&r.vector));
     return re;
 }
コード例 #23
0
ファイル: makeconfig.cpp プロジェクト: twsdwf/avr-waterer-ui
void MakeConfig::onDataAvailable()
{
    QMutexLocker mtxlock(mtx);
    QByteArray data =  port->readAll();
    if(data[0]==13 || data[0]==10) return;

    buf.append(data);
qDebug()<<"state"<<state<<"buf="<<buf;
    if (state == stNone) return;
    if (state == stReadCurState) {
        ui->statusBar->showMessage(QString::fromLocal8Bit("Получение текущего состояния..."));
        if (!buf.contains(";")) return;
        ui->statusBar->showMessage(QString::fromLocal8Bit("Дешифровка текущего состояния..."));
        QString s = QString(buf);
        QStringList devs = s.split(QString(","));
        if (devs.count() < 2) {
            state = stNone;
            qDebug()<<"no sensor devices found";
            buf.clear();
            return;
        }
        QString cmd;
        for (int i=0; i< devs.count()-1; ++i ) {
            cmd.append(QString("iic %1,*;").arg(devs[i]));
        }
        qDebug()<<"iic cmd: "<<cmd;
        buf.clear();
        port->write(cmd.toLocal8Bit());
        state = stReadCurState2;
        return;
    } else if (state == stReadCurState2) {
        if (!buf.contains(";")) {
            return;
        }
        qDebug()<<"got iic data:"<<buf;
        QString data(buf.trimmed());
        data.chop(1);
        QStringList parts = data.split(",");
        if (parts.length() < 3) {
            qDebug()<<"bad data:"<<data;
            buf.clear();
            return;
        }
        int r=0;
        while (r < this->ui->tblConfig->rowCount()) {
            if (! (ui->tblConfig->item(r, 2) && ui->tblConfig->item(r, 3))) {
                ++r;
                continue;
            }
            if ( (ui->tblConfig->item(r, 3)->text() == parts[1]) && (ui->tblConfig->item(r, 2)->text() == parts[0]) ) {

                QTableWidgetItem *item= new QTableWidgetItem(parts[2]);
                ui->tblConfig->setItem(r, 10, item);
                break;
            }
            ++r;
        }//while
        buf = buf.remove(0, buf.indexOf(";") + 1);
    } else if (state == stSendConfigLines) {
        //qDebug()<<buf.contains("OK");
        if (buf.contains("OK")) {
            buf.clear();
            ui->statusBar->showMessage(QString::fromLocal8Bit("Отправляем строку конфигурации №%1").arg(lsi+1));
            this->sendConfigLine(++lsi);
        } else if (buf.contains("setup()")) {
            buf.clear();
            this->sendConfigLine(lsi);
        }
        return;
    }else if (stSendSensorsCount == state) {
        //qDebug()<<buf.contains("SET");
        if (buf.contains(("SET"))) {
            state = stSendPlantNames;
            this->lsi  = 0;
            ui->statusBar->showMessage(QString::fromLocal8Bit("Начинаем отправку названий растений..."));
            this->port->write("\7");
            this->port->flush();
            sleep(1);
            this->sendPlantName(lsi);
        }
        return;
    } else if (state == stSendPlantNames) {
        //qDebug()<<buf.contains("OK");
        if (buf.contains("OK")) {
            buf.clear();
            ui->statusBar->showMessage(QString::fromLocal8Bit("Отправка названия из строки %1").arg(lsi+1));
            this->sendPlantName(++lsi);
        }
        return;
    } else if (state == stGetW2Dsizes) {
        if (buf.contains(";")) {
            QRegExp re("^.*(\\d+)\\s*\\,\\s*(\\d+).*$");
            if (re.indexIn(buf) > -1) {
                qDebug()<<re.cap(1)<< re.cap(1).toInt()<<re.cap(2)<< re.cap(2).toInt();
                ui->spinX->setMaximum(re.cap(1).toInt());
                ui->spinY->setMaximum(re.cap(2).toInt());
            } else {
                qDebug()<<"not matched";
            }
            state = stNone;
        }
    } else if (state == stReadConfig) {
        if (buf.contains(";")) {
            if (last_index == -1) {
                qDebug()<<"got pot cnt";
                buf = buf.trimmed();
                buf.chop(1);
                pots_total = buf.toInt();
                last_index = 0;
                buf.clear();
                this->port->write(QString("pot get %1;\r\n").arg(last_index).toLocal8Bit());
                this->ui->tblConfig->setRowCount(0);
                this->ui->tblConfig->setRowCount(pots_total);
            } else if (buf.length() > 10 && buf.contains(",")) {
                buf = buf.trimmed();
                buf.chop(1);
                QStringList parts = buf.split(",");
                if (parts.length() >=14) {
                    QTableWidgetItem*item;
                    SETITEM(last_index, 0, parts[1]);//флаги
                    SETITEM(last_index, 1, parts[2]);//растение
                    SETITEM(last_index, 2, parts[3]);//чип
                    SETITEM(last_index, 3, parts[4]);//пин
                    SETITEM(last_index, 4, parts[5]);// Х
                    SETITEM(last_index, 5, parts[6]);// У
                    SETITEM(last_index, 6, parts[7]);// доза
                    SETITEM(last_index, 7, parts[8]);// программа
                    SETITEM(last_index, 8, parts[9]);// мин
                    SETITEM(last_index, 9, parts[10]);// макс
                    SETITEM(last_index, 10, QString("?"));// тек.знач-ие
                    SETITEM(last_index, 11, parts[13]);// вкл/выкл
                    SETITEM(last_index, 12, (parts[12]=="1"?QString::fromLocal8Bit("сушим"):QString::fromLocal8Bit("льём")));// состояние(полив/подсушка)
                    SETITEM(last_index, 13, parts[14]);// вылито
                    ++last_index;
                    PlantData pd;
                    pd.index = parts[0].toInt();
                    pd.flags = parts[1].toInt();
                    pd.name = parts[2];
                    pd.chip = parts[3].toInt();
                    pd.pin = parts[4].toInt();
                    pd.X = parts[5].toInt();
                    pd.Y = parts[6].toInt();
                    pd.portion = parts[7].toInt();
                    pd.pgm = parts[8].toInt();
                    pd.min = parts[9].toInt();
                    pd.max = parts[10].toInt();
                    pd.en = parts[13].toInt();
                    this->pots_data.push_back(pd);
                } else {
                    qDebug()<<"re-query pot "<<last_index;
                }
                buf.clear();
                if (last_index < pots_total) {
                    qDebug()<<"query pot "<<last_index;
                    this->port->write(QString("pot get %1;\r\n").arg(last_index).toLocal8Bit());
                    //this->port->flush();
                } else {
                    state = stGetW2Dsizes;
                    this->port->write("WSZ;\r\n");
                }
            } else {
                this->port->write(QString("pot get %1;\r\n").arg(last_index).toLocal8Bit());
                buf.clear();
            }
            return;
        } else {
            return;
        }
        if (!buf.contains(";;")) return;
        buf = buf.trimmed();
        qDebug()<<"READ CONFIG"<<"\n----\n"<<buf<<"\n-----";
        QRegExp re("\\{(\\d+)\\};");
        re.indexIn(buf);
        int n_rows = re.cap(1).toInt();
        this->ui->tblConfig->setRowCount(0);
        this->ui->tblConfig->setRowCount(n_rows);

        buf= buf.replace(re, "").trimmed();
        QStringList list = buf.split(";");
        qDebug()<<list;
        QRegExp il("^(.*)\\[(.*)\\]$");
        int r = 0;
        for (int i = 0; i < list.length(); ++i) {
            //qDebug()<<list[i];
            if (il.indexIn(list[i].trimmed()) > -1) {
                QString nums = il.cap(1), name = il.cap(2);
                nums = nums.replace(QRegExp("\\s+"), "");
                //qDebug()<<"nums:"<<nums;
                QStringList numz = nums.split(",");
                QTableWidgetItem*item;
                SETITEM(r, 0, name);
                SETITEM(r, 1, numz[0]);
                SETITEM(r, 2, numz[1]);
                SETITEM(r, 3, numz[2]);
                SETITEM(r, 4, numz[3]);
                SETITEM(r, 5, numz[4]);
                SETITEM(r, 6, numz[5]);
                SETITEM(r, 7, numz[6]);
                SETITEM(r, 8, numz[7]);
                ++r;
             //   qDebug()<<numz;
            }
        }
        buf.clear();
        state = stNone;
        return;
    }
    //QStringList lines = buf.split("\n");
    //first line -- cmd echo
    //qDebug()<<data<<data.contains(';');
    if (buf.contains(';')) {
        buf = buf.trimmed();
        //qDebug()<<buf;
        if (state == stDetectPinStep1) {
            //test1.resize(0);
        } else if(state == stDetectPinStep2) {
            //test2.resize(0);
        } else {
            ui->statusBar->showMessage(QString::fromLocal8Bit("Неправильный код состояния. Возможно, идёт отсылка/приём данных..."));
            data.clear();
            return;
        }
            QString str = QString(buf);
            QTextStream st(&str,  QIODevice::ReadOnly);
            int n;
            st>>n;
            //qDebug() << "n="<<n;
            for (int i = 0; i < n; ++i) {
                int val;
                st>>val;
                if (state == stDetectPinStep1) {
                    //test1.push_back(val);
                } else if (state ==stDetectPinStep2) {
                    //test2.push_back(val);
                }
            }
            if (state == stDetectPinStep1) {
                ui->statusBar->showMessage(QString::fromLocal8Bit("Готов к шагу 2"));
            } else if (state == stDetectPinStep2) {
                qDebug()<<"state"<<state<<"buf="<<buf;
              /*  if (test1.size()!=test2.size()) {
                    ui->statusBar->showMessage(QString::fromLocal8Bit("Ошибка: не совпадает размер данных"));
                    buf.clear();
                    //qDebug()<<"state=0, ln 216";
                    state = stNone;
                    return;
                }
                int max_df = 0, max_index=-1, _cdf;
                for (int i=0;i<test1.size(); ++i) {
                    _cdf = abs(test1.at(i)-test2.at(i));
                    if (_cdf > max_df) {
                        qDebug()<<"delta: "<<_cdf;
                        max_index = i;
                        max_df = _cdf;
                    }
                }
                if (max_index >=0 ) {
                    qDebug()<<"max_index "<<max_index;
                    int pins = ui->cbChipType->itemData((ui->cbChipType->currentIndex())).toInt();
                    qDebug()<<"max_index "<<max_index;
                    ui->statusBar->showMessage(QString::fromLocal8Bit("Чип %1 пин %2").arg(max_index/pins).arg(max_index%pins));
                    this->last_found = max_index;
                }
                state = stNone;
                //qDebug()<<"state=0, ln234";
                */
            }
    }
コード例 #24
0
ファイル: Director.cpp プロジェクト: fredwulei/CSE532S
Director::Director(const string& scriptName, unsigned int playerCount, bool overRide)
{
	isOverride = overRide;
	maximum = 0;
	ifstream infile(scriptName);
	if (!infile.is_open()) {
		string error = "[ERROR]:  Open file fail: " + scriptName;
		throw CodeException(FAIL_FILE_OPEN, error.c_str());
	}
	string currentLine;
	bool followingPL;
	int scriptCounter = 1;
	int lastPartDefCount = 0;

	regex re("^\\[scene\\][\\s]([\\w\\s]*)$");
	smatch sm;
	regex re_config("^[\\s]*(.*.txt)[\\s]*$");
	smatch sm_config;
	regex re_part("^[\\s]*([\\w]+)[\\s]+(.*.txt)[\\s]*$");
	smatch sm_part;

	while (getline(infile, currentLine)) {
		// scan for scene titles
		if (regex_match(currentLine, sm, re)) {
			titles.push_back(sm[1]);
			followingPL = false;
		}
		else {
			// scan for scene fragment config files
			if (regex_match(currentLine, sm_config, re_config)) {
				scripts[scriptCounter] = script();

				if (!followingPL) {
					followingPL = true;
				}
				else {
					titles.push_back(string());
				}
				ifstream configFile(sm_config[1]);
				int partDefinitionLineCount = 0;

				if (!configFile.is_open()) {
					string temp = sm_config[1];
					string error = "[ERROR]:  Open file fail: " + temp;
					throw CodeException(FAIL_FILE_OPEN, error.c_str());
				}
				
				string partDefinitionLine;
				while (getline(configFile, partDefinitionLine)) {
					// scan for part definition files
					if (regex_match(partDefinitionLine, sm_part, re_part)) {
						partDefinitionLineCount++;
						scripts[scriptCounter][sm_part[1]] = sm_part[2];
					}
				}

				scriptCounter++;
				if (!isOverride) {
					int consecutiveSum = partDefinitionLineCount + lastPartDefCount;
					lastPartDefCount = partDefinitionLineCount;
					maximum = maximum > consecutiveSum ? maximum : consecutiveSum;
				}
			}
		}
	}

	//finish reading script
	try {
		play = playPtr(new Play(titles, finished.get_future()));
	}
	catch (exception& e) {
		throw (BAD_ALLOCATION,e);
	}
	
	// check the override option
	if (!isOverride) {
		maximum = maximum > (int)playerCount ? maximum : (int)playerCount;
	}
	else {
		maximum = (int)playerCount;
	}
	
	for (int i = 0; i < maximum; i++) {
		try {
			players.push_back(playerPtr(new Player(*play)));
		}
		catch (exception& e) {
			throw (BAD_ALLOCATION, e);
		}
		
		players[i]->activate();
	}
}
コード例 #25
0
ファイル: XFileUtils.cpp プロジェクト: Omel/xbmc
HANDLE FindFirstFile(LPCSTR szPath,LPWIN32_FIND_DATA lpFindData)
{
  if (lpFindData == NULL || szPath == NULL)
    return NULL;

  CStdString strPath(szPath);

  if (IsAliasShortcut(strPath))
    TranslateAliasShortcut(strPath);

  if (strPath.empty())
    return INVALID_HANDLE_VALUE;

  strPath.Replace("\\","/");

  // if the file name is a directory then we add a * to look for all files in this directory
#if defined(__APPLE__) || defined(__FreeBSD__)
  DIR *testDir = opendir(strPath.c_str());
#else
  DIR *testDir = opendir(szPath);
#endif
  if (testDir)
  {
    strPath += "/*";
    closedir(testDir);
  }

  int nFilePos = strPath.ReverseFind(XBMC_FILE_SEP);

  CStdString strDir = ".";
  CStdString strFiles = strPath;

  if (nFilePos > 0)
  {
    strDir = strPath.substr(0,nFilePos);
    strFiles = strPath.substr(nFilePos + 1);
  }

  if (strFiles == "*.*")
     strFiles = "*";

  strFiles = CStdString("^") + strFiles + "$";
  strFiles.Replace(".","\\.");
  strFiles.Replace("*",".*");
  strFiles.Replace("?",".");

  strFiles.MakeLower();  // Do we really want this case insensitive?
  CRegExp re(true);

  if (re.RegComp(strFiles.c_str()) == NULL)
    return(INVALID_HANDLE_VALUE);

  struct dirent **namelist = NULL;
  int n = scandir(strDir, &namelist, 0, alphasort);

  CXHandle *pHandle = new CXHandle(CXHandle::HND_FIND_FILE);
    pHandle->m_FindFileDir = strDir;

  while (n-- > 0)
  {
    CStdString strComp(namelist[n]->d_name);
    strComp.MakeLower();

    if (re.RegFind(strComp.c_str()) >= 0)
      pHandle->m_FindFileResults.push_back(namelist[n]->d_name);
    free(namelist[n]);
  }
  free(namelist);

  if (pHandle->m_FindFileResults.size() == 0)
  {
    delete pHandle;
    return INVALID_HANDLE_VALUE;
  }

  FindNextFile(pHandle, lpFindData);

  return pHandle;
}
コード例 #26
0
static void parseClass(const QString& name, const QString& in)
      {
      Class cl;
      cl.name = name;

      QStringList sl = in.split("\n");
      QStringList methodDescription;

      QRegExp re("@P ([^\\s]+)\\s+([^\\s]+)(.*)");

      // matches Q_INVOKABLE void mops(int a);   // comment
      QRegExp re1("Q_INVOKABLE +([^ ]+) +([^;]+); */*(.*)");
      QRegExp re2("Q_INVOKABLE +([^ ]+) +([^\\{]+)\\{");
      QRegExp re3("Q_INVOKABLE +([^ ]+) +(\\w+\\([^\\)]*\\))\\s+const\\s*([^\\{]*)\\{");

      QRegExp reD("//@ (.*)");
      QRegExp re4 ("class +(\\w+) *: *public +(\\w+) *\\{");
      QRegExp re4b("class +(\\w+) *: *public +(\\w+), *public");

      Q_ASSERT(re1.isValid() && re2.isValid() && re3.isValid());

      bool parseClassDescription = true;

      foreach(const QString& s, sl) {
            if (re.indexIn(s, 0) != -1) {             //@P
                  parseClassDescription = false;
                  Prop p;
                  p.name        = re.cap(1);
                  p.type        = re.cap(2);
                  p.description = re.cap(3);
                  cl.props.append(p);
                  }
            else if (re2.indexIn(s, 0) != -1) {
                  parseClassDescription = false;
                  Proc p;
                  p.type        = re2.cap(1);
                  p.name        = re2.cap(2);
                  p.description = methodDescription;
                  methodDescription.clear();
                  cl.procs.append(p);
                  }
            else if (re1.indexIn(s, 0) != -1) {
                  parseClassDescription = false;
                  Proc p;
                  p.type        = re1.cap(1);
                  p.name        = re1.cap(2);
                  p.description = methodDescription;
                  methodDescription.clear();
                  cl.procs.append(p);
                  }
            else if (re3.indexIn(s, 0) != -1) {
                  parseClassDescription = false;
                  Proc p;
                  p.type        = re3.cap(1);
                  p.name        = re3.cap(2);
                  p.description = methodDescription;
                  methodDescription.clear();
                  cl.procs.append(p);
                  }
            else if ((reD.indexIn(s, 0) != -1)) {
                  if (parseClassDescription)
                        cl.description.append(reD.cap(1));
                  else
                        methodDescription.append(reD.cap(1));
                  }
            else if (s.startsWith("///")) {
                  QString ss = s.mid(3);
                  if (parseClassDescription)
                        cl.description.append(ss);
                  else
                        methodDescription.append(ss);
                  }
            else if (re4.indexIn(s, 0) != -1) {
                  parseClassDescription = false;
                  QString parent = re4.cap(2).simplified();
                  if (name == re4.cap(1).simplified()) {
                        cl.parent = parent;
                        }
                  else {
                        printf("?<%s>!=<%s> derived from <%s>\n",
                           qPrintable(name), qPrintable(re4.cap(1).simplified()), qPrintable(parent));
                        }
                  }
            else if (re4b.indexIn(s, 0) != -1) {
                  parseClassDescription = false;
                  QString parent = re4b.cap(2).simplified();
                  if (name == re4b.cap(1).simplified()) {
                        cl.parent = parent;
                        }
                  else {
                        printf("?<%s>!=<%s> derived from <%s>\n",
                           qPrintable(name), qPrintable(re4b.cap(1).simplified()), qPrintable(parent));
                        }
                  }
            }
      classes.append(cl);
      }
コード例 #27
0
ファイル: tdump.cpp プロジェクト: jpcoles/ZM
int main( int argc, char *argv[] ) {
    bool bHelp  = false;    //!< Help was requested on the command line
    bool bError = false;    //!< An error occurred on the command line
    bool bSplit = true;     //!< Split lines
    int  iPrecision=5;
    std::string ftype="standard";
    std::string filename;
    std::string markname;
    std::string tipsyname;

    ifTipsy in;
    ofTipsy out;
    rangelist worklist;
    range workunit;

    TipsyHeader       h;
    TipsyGasParticle  g;
    TipsyDarkParticle d;
    TipsyStarParticle s;

    unsigned int i;


    //! Parse command line
    for(;;) {
        int c, option_index=0;

        static struct option long_options[] = {
            { "help",        0, 0, OPT_HELP },
            { "single",      0, 0, OPT_SINGLE },
            { "standard",    0, 0, OPT_STANDARD },
            { "std",         0, 0, OPT_STANDARD },
            { "native",      0, 0, OPT_NATIVE },
            { "nat",         0, 0, OPT_NATIVE },
            { "markfile",    1, 0, OPT_MARKFILE },
            { "tipsyout",    1, 0, OPT_TIPSYOUT },
            { "precision",   1, 0, OPT_PRECISION },
            { 0,             0, 0, 0 }
        };

        c = getopt_long( argc, argv, "h1p:",
                         long_options, &option_index );
        if ( c == -1 ) break;
        switch(c) {
        case OPT_HELP:
            bHelp = true;
            break;
	case OPT_SINGLE:
	    bSplit = false;
	    break;
	case OPT_STANDARD:
	    ftype = "standard";
	    break;
	case OPT_NATIVE:
	    ftype = "native";
	    break;
	case OPT_MARKFILE:
	    assert(optarg!=NULL);
	    markname = optarg;
	    break;
	case OPT_TIPSYOUT:
	    assert(optarg!=NULL);
	    tipsyname = optarg;
	    break;
	case OPT_PRECISION:
	    assert(optarg!=NULL);
	    iPrecision = atoi(optarg);
	    break;
        default:
            bError = true;
            break;
        }
    }

    if ( bHelp || bError ) {
	Usage(argv[0]);
	exit(1);
    }

    if ( optind < argc ) {
	std::string::size_type sep;
        filename = argv[optind++];
	if ( (sep=filename.find(':')) != std::string::npos ) {
	    ftype = filename.substr(0,sep);
	    filename = filename.substr(sep+1);
	}
    }
    else {
        std::cerr << "Missing tipsy input file" << std::endl
		  << "Try " << argv[0] << " --help" << std::endl;
        exit(2);
    }

    in.open(filename.c_str(),ftype.c_str());
    if ( ! in.is_open() ) {
	std::cerr << "Unable to open Tipsy binary " << filename << std::endl;
        exit(2);
    }

    in >> h;

    if ( h.h_nBodies != h.h_nSph + h.h_nDark + h.h_nStar 
	|| h.h_nDims < 1 || h.h_nDims > 3 ) {
	std::cerr << filename << " has crazy dimensions" << std::endl
		  << "(have you tried --std or --nat?)" << std::endl;
	exit(2);
    }


    Regex re("^([gsd])?([[:digit:]]+)(-(\\+?)([[:digit:]]+))?$");

    while( optind < argc ) {
	if ( re.Search(argv[optind]) >= 0 ) {
	    tipsypos::section_type p;
	    tipsypos::offset_type  b;
	    tipsypos::offset_type  e;

	    if ( re[0].size() == 0 ) p = tipsypos::particle;
	    else switch( re[0][0] ) {
	    case 'g': p = tipsypos::gas;  break;
	    case 'd': p = tipsypos::dark; break;
	    case 's': p = tipsypos::star; break;
	    default: assert( 0==1 /* Invalid particle type */ );
	    }

	    b = atoi(re[1].c_str());
	    if ( re[4].size() == 0 ) e = b;
	    else {
		e = atoi( re[4].c_str() );
		if ( re[3].size() != 0 ) e += b;
	    }
	    switch(p) {
	    case tipsypos::gas:
		bError = b>=h.h_nSph || e>=h.h_nSph;
		break;
	    case tipsypos::dark:
		bError = b>=h.h_nDark || e>=h.h_nDark;
		break;
	    case tipsypos::star:
		bError = b>=h.h_nStar || e>=h.h_nStar;
		break;
	    case tipsypos::particle:
		bError = b>=h.h_nBodies || e>=h.h_nBodies;
		break;
	    default:
		assert( 0==1 /* Invalid file section */ );
	    }
	    if ( bError ) {
		std::cerr << "Range " << argv[optind]
			  << " is outside the file" << std::endl;
		exit(2);
	    }

	    worklist.push_back(range(p,b,e));
	}
	else {
	    std::cerr << "Invalid particle selection: "
		      << argv[optind] << std::endl
		      << "Try " << argv[0] << " --help" << std::endl;
	    exit(2);
	}
	optind++;
    }


    if ( !markname.empty() ) {
	std::ifstream mf(markname.c_str());
	uint32_t nd, ng, ns;
	if ( !mf.is_open() ) {
	    std::cerr << "Unable to open " << markname << std::endl;
	    exit(2);
	}
	mf >> nd >> ng >> ns;
	if ( nd != h.h_nDark || ng != h.h_nSph || ns != h.h_nStar ) {
	    std::cerr << markname << " does not match the tipsy file"
		      << std::endl;
	    exit(2);
	}
	while( !mf.eof() ) {
	    mf >> i;
	    worklist.push_back(range(tipsypos::particle,i-1,i-1));
	}
    }
コード例 #28
0
ファイル: profileform.cpp プロジェクト: Artom-Kozincev/qTox
ProfileForm::ProfileForm(QWidget *parent) :
    QWidget{parent}, qr{nullptr}
{
    bodyUI = new Ui::IdentitySettings;
    bodyUI->setupUi(this);
    core = Core::getInstance();

    head = new QWidget(this);
    QHBoxLayout* headLayout = new QHBoxLayout();
    head->setLayout(headLayout);

    QLabel* imgLabel = new QLabel();
    headLayout->addWidget(imgLabel);

    nameLabel = new QLabel();
    QFont bold;
    bold.setBold(true);
    nameLabel->setFont(bold);
    headLayout->addWidget(nameLabel);
    headLayout->addStretch(1);

    imgLabel->setPixmap(QPixmap(":/img/settings/identity.png").scaledToHeight(40, Qt::SmoothTransformation));

    // tox
    toxId = new ClickableTE();
    toxId->setReadOnly(true);
    toxId->setFrame(false);
    toxId->setFont(Style::getFont(Style::Small));
    toxId->setToolTip(bodyUI->toxId->toolTip());

    QVBoxLayout *toxIdGroup = qobject_cast<QVBoxLayout*>(bodyUI->toxGroup->layout());
    delete toxIdGroup->replaceWidget(bodyUI->toxId, toxId);     // Original toxId is in heap, delete it
    bodyUI->toxId->hide();

    /* Toxme section init */
    bodyUI->toxmeServersList->addItem("toxme.io");
    QString toxmeInfo = Settings::getInstance().getToxmeInfo();
    if (toxmeInfo.isEmpty()) // User not registered
        showRegisterToxme();
    else
        showExistingToxme();

    bodyUI->qrLabel->setWordWrap(true);

    QRegExp re("[^@ ]+");
    QRegExpValidator* validator = new QRegExpValidator(re, this);
    bodyUI->toxmeUsername->setValidator(validator);

    profilePicture = new MaskablePixmapWidget(this, QSize(64, 64), ":/img/avatar_mask.svg");
    profilePicture->setPixmap(QPixmap(":/img/contact_dark.svg"));
    profilePicture->setContextMenuPolicy(Qt::CustomContextMenu);
    profilePicture->setClickable(true);
    profilePicture->installEventFilter(this);
    connect(profilePicture, SIGNAL(clicked()), this, SLOT(onAvatarClicked()));
    connect(profilePicture, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showProfilePictureContextMenu(const QPoint&)));
    QHBoxLayout *publicGrouplayout = qobject_cast<QHBoxLayout*>(bodyUI->publicGroup->layout());
    publicGrouplayout->insertWidget(0, profilePicture);
    publicGrouplayout->insertSpacing(1, 7);

    timer.setInterval(750);
    timer.setSingleShot(true);
    connect(&timer, &QTimer::timeout, this, [=]() {bodyUI->toxIdLabel->setText(bodyUI->toxIdLabel->text().replace(" ✔", "")); hasCheck = false;});

    connect(bodyUI->toxIdLabel, SIGNAL(clicked()), this, SLOT(copyIdClicked()));
    connect(toxId, SIGNAL(clicked()), this, SLOT(copyIdClicked()));
    connect(core, &Core::idSet, this, &ProfileForm::setToxId);
    connect(bodyUI->userName, SIGNAL(editingFinished()), this, SLOT(onUserNameEdited()));
    connect(bodyUI->statusMessage, SIGNAL(editingFinished()), this, SLOT(onStatusMessageEdited()));
    connect(bodyUI->renameButton, &QPushButton::clicked, this, &ProfileForm::onRenameClicked);
    connect(bodyUI->exportButton, &QPushButton::clicked, this, &ProfileForm::onExportClicked);
    connect(bodyUI->deleteButton, &QPushButton::clicked, this, &ProfileForm::onDeleteClicked);
    connect(bodyUI->logoutButton, &QPushButton::clicked, this, &ProfileForm::onLogoutClicked);
    connect(bodyUI->deletePassButton, &QPushButton::clicked, this, &ProfileForm::onDeletePassClicked);
    connect(bodyUI->changePassButton, &QPushButton::clicked, this, &ProfileForm::onChangePassClicked);
    connect(bodyUI->deletePassButton, &QPushButton::clicked, this, &ProfileForm::setPasswordButtonsText);
    connect(bodyUI->changePassButton, &QPushButton::clicked, this, &ProfileForm::setPasswordButtonsText);
    connect(bodyUI->saveQr, &QPushButton::clicked, this, &ProfileForm::onSaveQrClicked);
    connect(bodyUI->copyQr, &QPushButton::clicked, this, &ProfileForm::onCopyQrClicked);
    connect(bodyUI->toxmeRegisterButton, &QPushButton::clicked, this, &ProfileForm::onRegisterButtonClicked);
    connect(bodyUI->toxmeUpdateButton, &QPushButton::clicked, this, &ProfileForm::onRegisterButtonClicked);

    connect(core, &Core::usernameSet, this, [=](const QString& val) { bodyUI->userName->setText(val); });
    connect(core, &Core::statusMessageSet, this, [=](const QString& val) { bodyUI->statusMessage->setText(val); });

    for (QComboBox* cb : findChildren<QComboBox*>())
    {
            cb->installEventFilter(this);
            cb->setFocusPolicy(Qt::StrongFocus);
    }

    retranslateUi();
    Translator::registerHandler(std::bind(&ProfileForm::retranslateUi, this), this);
}
コード例 #29
0
ファイル: query.cpp プロジェクト: rusingineer/quazaa
void Query::buildG2Keywords( QString strPhrase )
{
	QStringList lPositive, lNegative;

	strPhrase = strPhrase.trimmed().replace( "_", " "
											 ).normalized( QString::NormalizationForm_KC
														   ).toLower().append( " " );
	QStringList lWords;
	{
		QRegularExpression re( "(-?\\\".*\\\"|-?\\w+)\\W+",
							   QRegularExpression::InvertedGreedinessOption );
		int nPos = 0, nOldPos = 0;
		bool bHasDash = false;
		QRegularExpressionMatch oMatch;

		while ( ( oMatch = re.match( strPhrase, nPos ) ).hasMatch() )
		{
			nPos = re.match( strPhrase, nPos ).capturedStart();
			QString sWord = oMatch.captured( 1 );

			if ( bHasDash &&
				 nPos - oMatch.capturedLength() - nOldPos == 0 &&
				 lWords.last().size() < 4 &&
				 sWord.size() < 4 )
			{
				lWords.last().append( "-" ).append( sWord );
			}
			else
			{
				lWords << sWord;
			}

			nOldPos = nPos;
			nPos += oMatch.capturedLength();

			if ( strPhrase.mid( nPos - 1, 1 ) == "-" )
			{
				bHasDash = true;
			}
			else
			{
				bHasDash = false;
			}
		}
	}

	lWords.removeDuplicates();

	for ( QStringList::iterator itWord = lWords.begin(); itWord != lWords.end(); )
	{
		if ( ( *itWord ).size() < 4 )
		{
			itWord = lWords.erase( itWord );
		}
		else
		{
			itWord++;
		}
	}

	QRegularExpression rx( "\\w+" );

	foreach ( const QString& sWord, lWords )
	{
		if ( sWord.at( 0 ) == '-' && sWord.at( 1 ) != '"' )
		{
			// plain negative word
			m_sG2NegativeWords.append( sWord.mid( 1 ) ).append( "," );
			lNegative.append( sWord.mid( 1 ) );
		}
		else if ( sWord.at( 0 ) == '"' )
		{
			// positive quoted phrase
			m_sG2PositiveWords.append( sWord ).append( "," );

			// extract words
			int p = 0;
			QRegularExpressionMatch oMatch;
			while ( ( oMatch = rx.match( sWord, p ) ).hasMatch() )
			{
				p = oMatch.capturedStart() + oMatch.capturedLength();
				lPositive.append( oMatch.captured() );
			}
		}
		else if ( sWord.at( 0 ) == '-' && sWord.at( 1 ) == '"' )
		{
			// negative quoted phrase
			m_sG2NegativeWords.append( sWord ).append( "," );

			// extract words
			int p = 0;
			QRegularExpressionMatch oMatch;
			while ( ( oMatch = rx.match( sWord, p ) ).hasMatch() )
			{
				p = oMatch.capturedStart() + oMatch.capturedLength();
				lNegative.append( oMatch.captured() );
			}
		}
		else
		{
			// plain positive word
			m_sG2PositiveWords.append( sWord ).append( "," );
			lPositive.append( sWord );
		}
	}

	m_sG2PositiveWords.chop( 1 );
	m_sG2NegativeWords.chop( 1 );

	foreach( const QString& sWord, lNegative )
	{
		lPositive.removeAll( sWord );
	}
コード例 #30
0
void Standard::Withdrawal() {

    string padded_acc_holder;
    string padded_acc_num;
    string padded_amount;
    string padded_new_balance;
    string temp_acc_num;
    string temp_amount;
    stringstream stream;
    float amount;
    float new_balance;
    int acc_num;

    cout << "\nWithdrawal transaction selected.\n" << endl;

    cout << "Enter your account number: ";
    cin >> temp_acc_num;

    regex re("[0-9]{0,5}");
    if (regex_match(temp_acc_num, re)) {
        acc_num = stoi(temp_acc_num);
    } else {
        cerr << "\n>>> ERROR: The account number entered is invalid.\n" << endl;
        return;
    }

    if (curr_user.GetNum() != acc_num) {
        cerr << "\n>>> ERROR: The account number does not match your account.\n" << endl;
        return;
    }

    if (transactions.is_Disabled(curr_user.GetNum())) {
        cerr << "\n>>> ERROR: The account is disabled; you may not withdraw funds.\n" << endl;
        return;
    }

    if (transactions.is_New(curr_user.GetNum())) {
        cerr << "\n>>> ERROR: Newly created accounts may not withdraw funds. Please try again in 24 hours.\n" << endl;
        return;
    }

    cout << "Enter amount to withdraw: ";
    cin >> temp_amount;

    if (transactions.is_Amount_Valid(temp_amount)) {
        amount = stof(temp_amount);
    } else {
        cerr << "\n>>> ERROR: The amount entered is invalid.\n" << endl;
        return;
    }

    if (curr_user.GetPlan() == 'S') {
        if (amount <= 0.05 + curr_user.GetBalance() && (500.00 >= amount > 0.0) && (fmod(amount, 5.0) == 0)) {

            new_balance = curr_user.GetBalance() - amount;
            curr_user.SetBalance(new_balance);

        } else {
            cerr << "\n>>> ERROR: The amount entered is invalid.\n" << endl;
            return;
        }

        if ((curr_user.GetBalance() - 0.05 - curr_user.GetDeposited()) < amount) {
            cerr << "\n>>> ERROR: You may not withdraw recently deposited funds.\n" << endl;
            return;
        }
    } else if (curr_user.GetPlan() == 'N') {
        if (amount <= 0.10 + curr_user.GetBalance() && (500.00 >= amount > 0.0) && (fmod(amount, 5.0) == 0)) {

            new_balance = curr_user.GetBalance() - amount;
            curr_user.SetBalance(new_balance);

        } else {
            cerr << "\n>>> ERROR: The amount entered is invalid.\n" << endl;
            return;
        }

        if ((curr_user.GetBalance() - 0.10 - curr_user.GetDeposited()) < amount) {
            cerr << "\n>>> ERROR: You may not withdraw recently deposited funds.\n" << endl;
            return;
        }
    } else {
        cerr << "\n>>> ERROR: Unable to retrieve transaction payment plan information.\n" << endl;
        return;
    }

    padded_acc_holder = curr_user.GetName();
    while (padded_acc_holder.length() < 20) {
        padded_acc_holder = padded_acc_holder + " ";
    }

    padded_acc_num = temp_acc_num;
    while (padded_acc_num.length() < 5) {
        padded_acc_num = "0" + padded_acc_num;
    }

    padded_amount = temp_amount;
    while (padded_amount.length() < 8) {
        padded_amount = "0" + padded_amount;
    }

    stream << fixed << setprecision(2) << new_balance;
    padded_new_balance = stream.str();
    while (padded_new_balance.length() < 8) {
        padded_new_balance = "0" + padded_new_balance;
    }

    cout << "\nFunds have been successfully withdrawn from your account." << endl;
    cout << "New balance: $" + padded_new_balance << endl;

    string transaction_line = "01 " + padded_acc_holder + " " + padded_acc_num + " " + padded_amount + "   ";
    cout << "Transaction line: " << transaction_line << endl;
    transaction_file.push_back(transaction_line);
    cout << "\nEnter a command.\n" << endl;
}