Ejemplo n.º 1
0
   	 if(nIndex<0 || nIndex>=m_count) return (char*)" "; 

  	 STRINGLIST::iterator plist;

     plist=m_lst.begin();

	 for(int i=0;i<nIndex;i++) plist++;

     return (char*)plist->c_str();

}



void CSList::SetAt(char *buffer,int nIndex)

{

     if(nIndex<0 || nIndex>=m_count) return;

     STRINGLIST::iterator plist;

     plist=m_lst.begin();

     for(int i=0;i<nIndex;i++)

	    plist++;
Ejemplo n.º 2
0
ustring DataValue::serializeStrList(void *value) {
	ustring result("#");
	StringList list;
	list = *(ustring*)value;
	for(StringList::iterator line = list.begin(); line != list.end(); line++)
		result += int_to_str(line->size()) + ":" + *line + "|";
	return result;
}
Ejemplo n.º 3
0


CSList::~CSList()

{

	m_lst.clear();
Ejemplo n.º 4
0
Command::Command(const char* first, const char* last) throw(parse_error)
		: from(INVALID_SID), to(INVALID_SID), dirty(false), full(first, last)
{
	initNumPosParams();
	// optimize later
	// this is lazy due to a DC++ bug that sends empty parameters...
	// ideally, we should not be using it
	StringList sl = Util::lazyStringTokenize(full);
	full += '\n';
	if(full.size() < 5 || sl[0].size() != 4)
		throw parse_error("invalid message type");
	action = sl[0][0];
	cmd = (CmdInt)(stringToFourCC(sl[0]) & 0xFFFFFF00);
	StringList::size_type loc;	// message parameters start at this index

	switch(action) {
	case 'F':
		from = ADC::toSid(sl[1]);
		features = sl[2];
		checkFeatures();
		loc = 3;
		break;
	case 'D':
	case 'E':
		from = ADC::toSid(sl[1]);
		to = ADC::toSid(sl[2]);
		loc = 3;
		break;
	case 'B':
	case 'S':
		from = ADC::toSid(sl[1]);
		loc = 2;
		break;
	case 'I':
	case 'H':
	case 'L':
		loc = 1;
		break;
	default:
		throw parse_error(string("invalid action type '") + action + '\'');
	}

	if (loc >= sl.size())
		throw parse_error("not enough tokens for message type");
	if (numPosParams.count(cmd)) {
		// known command -- check that positional and named params are correct
		if (loc + numPosParams[cmd] > sl.size())
			throw parse_error("missing parameters");
		for (StringList::iterator i = sl.begin() + loc + numPosParams[cmd]; i != sl.end(); ++i) {
			// param name parts can't be escaped chars
			if (i->size() < 2 || ADC::CSE(i->substr(0, 2)).size() != 2)
				throw parse_error("invalid named parameter: " + *i);
		}
	}
	params.resize(sl.size() - loc);
	transform(sl.begin() + loc, sl.end(), params.begin(), &ADC::CSE);
}
Ejemplo n.º 5
0
Console::~Console() // Destructor
{
  if (print_on_delete) {
    StringList::iterator i;
    for (i = loglines.end();;) {
      --i;
      printf("%s\n", i->c_str());
      if (i == loglines.begin()) {
        break;
      }
    }
  }
  if (save_to_file) {
    out.close();
  }
}
Ejemplo n.º 6
0
void	Kernel::LoadPlugins (std::string & dir)
{
	StringList files ;
	ListFiles (dir.c_str(), "*.so", files) ;
	for (StringList::iterator it = files.begin(); it != files.end(); ++it) {
		string full = dir + "/" + it->c_str() ;
		Plugin *p = new Plugin (full) ;
		if (p->Register(*this) ) {
			this->_loadedPlugins.insert(PluginMap::value_type(*it, p)) ;
      DOMOASTER_INFO << "\t- " << it->c_str() << " : OK";
		} else {
			delete p ;
      DOMOASTER_WARN << "\t- " << it->c_str() << " : KO";
		}
	}
}
Ejemplo n.º 7
0
int main(int argc, char **argv) {

    const char *xml = "<verse osisID=\"John.1.1\" type=\'test type\' yeah = \"stuff\" />";
    cout << ((argc > 1) ? argv[1]: xml) << "\n";

    XMLTag x((argc > 1) ? argv[1] : xml);

    cout << x.toString() << "\n";
    x.setAttribute("addedAttribute", "with a \" quote");
    cout << x.toString() << "\n";
    cout << "Tag name: [" << x.getName() << "]\n";
    StringList attributes = x.getAttributeNames();
    for (StringList::iterator it = attributes.begin(); it != attributes.end(); it++) {
        const char *name = it->c_str();
        cout << " - attribute: [" << name << "] = [";
        cout << x.getAttribute(name) << "]\n";
        int count = x.getAttributePartCount(name, ' ');
        cout << "\t" << count << " parts:\n";
        int i = (count > 1) ? 0 : -1;        // -1 for whole value cuz it's faster, but does the same thing as 0
        do {
            cout << "\t" << x.getAttribute(name, i, ' ') << "\n";
            if (i < 0) i = 0;    // to handle our -1 condition
        } while (++i < count);
    }
    cout << " isEmpty: " << x.isEmpty() << "\n";
    cout << " isEndTag: " << x.isEndTag() << "\n";
    cout << "\n";


    if (argc < 2) {  // only run if we're defaulted
        const char *testParts="ABC D EF GHIJ";
        cout << "Setting attribute 'multiPart' to: '" << testParts << "'\n";
        x.setAttribute("multiPart", testParts);
        cout << x << "\n";
        cout << "Setting part 2 to 'MMM'\n";
        x.setAttribute("multiPart", "MMM", 2, ' ');
        cout << x << "\n";
        cout << "Removing part 1\n";
        x.setAttribute("multiPart", 0, 1, ' ');
        cout << x << "\n";
        cout << "Removing part 2\n";
        x.setAttribute("multiPart", 0, 2, ' ');
        cout << x << "\n";
    }

}
Ejemplo n.º 8
0
void ListBox::Update()
{
	StringList::iterator it = m_messages.begin();
	for (uint16 i = 0; i < m_curLineIndex; i++)
	{
		if (it != m_messages.end())
			++it;
	}
	for(uint16 i = 0; i < m_lineNbr; ++i)
	{
		if (it == m_messages.end())
			m_lines[i]->SetMsg("");
		else {
			m_lines[i]->SetMsg(it->data());
			++it;
		}
	}
}
Ejemplo n.º 9
0
  String File::find(const String& filename, StringList directories)
  {
    String filename_new = filename;

    // empty string cannot be found, so throw Exception. 
    // The code below would return success on empty string, since a path is prepended and thus the location exists
    if (filename_new.trim().empty()) throw Exception::FileNotFound(__FILE__, __LINE__, __PRETTY_FUNCTION__, filename);

    //add data dir in OpenMS data path
    directories.push_back(getOpenMSDataPath());

    //add path suffix to all specified directories
    String path = File::path(filename);
    if (path != "")
    {
      for (StringList::iterator it = directories.begin(); it != directories.end(); ++it)
      {
        it->ensureLastChar('/');
        *it += path;
      }
      filename_new = File::basename(filename);
    }

    //look up file
    for (StringList::const_iterator it = directories.begin(); it != directories.end(); ++it)
    {
      String loc = *it;
      loc.ensureLastChar('/');
      loc = loc + filename_new;

      if (exists(loc))
      {
        return String(QDir::cleanPath(loc.toQString()));
      }
    }

    //if the file was not found, throw an exception
    throw Exception::FileNotFound(__FILE__, __LINE__, __PRETTY_FUNCTION__, filename);

    //this is never reached, but needs to be there to avoid compiler warnings
    return "";
  }
Ejemplo n.º 10
0
void TextManager::ShowMessages()
{
    STRINGLIST::iterator it;

    World.getTextManager().ClearDisplayLines();

    SetDisplayLine(0, "Previous Messages");
    SetDisplayLine(1, "=================");
    SetDisplayLine(2, "");

    int i = 3;

    for (it = messageList.begin(); it != messageList.end(); it++, i++)
    {
        SetDisplayLine(i, (char *)it->c_str());
    }

    SetDisplayLine(39, "[+/-] scroll - [x] to exit");

}
Ejemplo n.º 11
0
void DiskDir::load()
{
    _files.clear();
    _subdirs.clear();
    // TODO: cache existing files and keep them unless they do no longer exist

    StringList li;
    GetFileList(fullname(), li);
    for(StringList::iterator it = li.begin(); it != li.end(); ++it)
    {
        DiskFile *f = new DiskFile(joinPath(fullname(), it->c_str()).c_str());
        _files[f->name()] = f;
    }

    li.clear();
    GetDirList(fullname(), li, 0);
    for(StringList::iterator it = li.begin(); it != li.end(); ++it)
    {
        // GetDirList() returns relative paths, so need to join
        Dir *d = createNew(joinPath(fullname(), it->c_str()).c_str());
        _subdirs[d->name()] = d;
    }
}
Ejemplo n.º 12
0
StringList FileFormat::FileExtensions() const
{
   size_type count = 0;
   size_type maxLen = 0;
   (*API->FileFormat->GetFileFormatFileExtensions)( m_data->handle, 0, &count, &maxLen );

   StringList extensions( count );
   if ( count > 0 )
   {
      Array<char16_type*> ptrs;
      for ( size_type i = 0; i < count; ++i )
      {
         extensions[i].Reserve( maxLen );
         ptrs.Add( extensions[i].c_str() );
      }

      if ( (*API->FileFormat->GetFileFormatFileExtensions)( m_data->handle, ptrs.Begin(), &count, &maxLen ) == api_false )
         throw APIFunctionError( "GetFileFormatFileExtensions" );

      for ( StringList::iterator i = extensions.Begin(); i != extensions.End(); ++i )
         i->ResizeToNullTerminated();
   }
   return extensions;
}
Ejemplo n.º 13
0
char ThMLFootnotes::processText(SWBuf &text, const SWKey *key, const SWModule *module) {
	SWBuf token;
	bool intoken    = false;
	bool hide       = false;
	SWBuf tagText;
	XMLTag startTag;
	SWBuf refs = "";
	int footnoteNum = 1;
	char buf[254];
	SWKey *p = (module) ? module->createKey() : (key) ? key->clone() : new VerseKey();
        VerseKey *parser = SWDYNAMIC_CAST(VerseKey, p);
        if (!parser) {
        	delete p;
                parser = new VerseKey();
        }
        *parser = key->getText();

	SWBuf orig = text;
	const char *from = orig.c_str();

	for (text = ""; *from; from++) {
		if (*from == '<') {
			intoken = true;
			token = "";
			continue;
		}
		if (*from == '>') {	// process tokens
			intoken = false;

			XMLTag tag(token);
			if (!strcmp(tag.getName(), "note")) {
				if (!tag.isEndTag()) {
					if (!tag.isEmpty()) {
						refs = "";
						startTag = tag;
						hide = true;
						tagText = "";
						continue;
					}
				}
				if (hide && tag.isEndTag()) {
					if (module->isProcessEntryAttributes()) {
						SWBuf fc = module->getEntryAttributes()["Footnote"]["count"]["value"];
						footnoteNum = (fc.length()) ? atoi(fc.c_str()) : 0;
						sprintf(buf, "%i", ++footnoteNum);
						module->getEntryAttributes()["Footnote"]["count"]["value"] = buf;
						StringList attributes = startTag.getAttributeNames();
						for (StringList::iterator it = attributes.begin(); it != attributes.end(); it++) {
							module->getEntryAttributes()["Footnote"][buf][it->c_str()] = startTag.getAttribute(it->c_str());
						}
						module->getEntryAttributes()["Footnote"][buf]["body"] = tagText;
						startTag.setAttribute("swordFootnote", buf);
						if ((startTag.getAttribute("type")) && (!strcmp(startTag.getAttribute("type"), "crossReference"))) {
							if (!refs.length())
								refs = parser->parseVerseList(tagText.c_str(), *parser, true).getRangeText();
							module->getEntryAttributes()["Footnote"][buf]["refList"] = refs.c_str();
						}
					}
					hide = false;
					if ((option) || ((startTag.getAttribute("type") && (!strcmp(startTag.getAttribute("type"), "crossReference"))))) {	// we want the tag in the text; crossReferences are handled by another filter
						text += startTag;
						text.append(tagText);
					}
					else	continue;
				}
			}

			// if not a note token, keep token in text
			if ((!strcmp(tag.getName(), "scripRef")) && (!tag.isEndTag())) {
				SWBuf osisRef = tag.getAttribute("passage");
				if (refs.length())
					refs += "; ";
				refs += osisRef;
			}
			if (!hide) {
				text += '<';
				text.append(token);
				text += '>';
			}
			else {
				tagText += '<';
				tagText.append(token);
				tagText += '>';
			}
			continue;
		}
		if (intoken) { //copy token
			token += *from;
		}
		else if (!hide) { //copy text which is not inside a token
			text += *from;
		}
		else tagText += *from;
	}
        delete parser;
	return 0;
}
Ejemplo n.º 14
0
BibleStudyMainFrame::BibleStudyMainFrame(SwordTools *newSwordTools,
    const wxString & title,
    const wxPoint & pos,
    const wxSize & size):
    wxFrame((wxFrame *) NULL, -1, title, pos, size, wxDEFAULT_FRAME_STYLE,
            wxT("BibleStudyWindow")),
    m_SwordTools(newSwordTools)
{

  LoadConfig();

  m_PlanToolBar = NULL;
  m_WindowSplit = NULL;
  // Open and read an existing ReadingPlan.

  if(m_Config.m_PalmIntegration)
  {
    m_pdbFile = new RPpdb(m_Config.m_PalmUserBackupPath.mb_str());
  }
  else
  {
    wxString localPath = ::wxGetHomeDir();
    localPath += wxT("/.biblestudy");
    if(!wxFileName::DirExists(localPath))
      wxFileName::Mkdir(localPath);
    localPath += wxT("/readingplans");
    if(!wxFileName::DirExists(localPath))
      wxFileName::Mkdir(localPath);
    m_pdbFile = new RPpdb(localPath.mb_str());
  }
  // Set first plan name found as current plan.

  PDBNode* firstPlan = NULL;
  if(m_pdbFile->PDBGetNextDatabase(true, &firstPlan) == errNone)
    m_pdbFile->PDBOpenDatabase(firstPlan);


  m_PlanDate = wxDateTime::Today();

  wxWindowDisabler disableAll;

  wxMenu *menuFile = new wxMenu();
  wxMenu *menuEdit = new wxMenu();
  wxMenu *menuHelp = new wxMenu();
  wxMenu *menuBibleStudies = new wxMenu();
  wxMenu *menuWindow = new wxMenu();
  wxMenu *menuOptions = new wxMenu();

  SetIcon(wxIcon(biblestudy_xpm));

  menuFile->Append(ID_MenuNewWindow, _("&New Window"));
  menuFile->Append(ID_MenuCloseWindow, _("&Close Window"));
  menuFile->AppendSeparator();
  menuFile->Append(ID_MenuReadingPlannerWiz, _("&ReadingPlanner Wizard..."));
  menuFile->AppendSeparator();
  menuFile->Append(ID_MenuExit, _("E&xit"));

  menuEdit->Append(ID_MenuCopy, _("&Copy"));
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_MenuSelectAll, _("Select &All"));
  
  menuHelp->Append(ID_MenuAbout, _("&About BibleStudy"));

  menuWindow->Append(ID_MenuShowStartPage, _("Show Start Page"));
  menuWindow->Append(ID_MenuShowHideBookTree, _("Show/Hide Book List"));
  menuWindow->Append(ID_MenuShowHideRPToolBar, _("Show/Hide ReadingPlanner Toolbar"));
  menuWindow->AppendSeparator();

  menuWindow->Append(ID_MenuSplitVertically, _("Split View &Left/Right"));

  menuWindow->Append(ID_MenuSplitHorizontally, _("Split View &Top/Bottom"));
  menuWindow->Append(ID_MenuRemoveSplit, _("&Remove Active View"));
  menuWindow->AppendSeparator();
  menuWindow->Append(ID_MenuNewTab, _("&New Tab"));
  menuWindow->Append(ID_MenuCloseTab, _("Close Tab"));
  menuWindow->Append(ID_MenuCloseOtherTabs, _("Close Other Tabs"));
  menuWindow->Append(ID_MenuDetachTab, _("Detach Tab"));
  menuWindow->Append(ID_MenuDuplicateTab, _("Duplicate Tab"));

  StringList optlist;

  optlist = m_SwordTools->GetSwordManager()->getGlobalOptions();

  // unsigned char mychars[13];
  // mychars[0] = 68;
  // mychars[1] = 69;
  // mychars[2] = 226;
  // mychars[3] = 128;
  // mychars[4] = 156;
  // mychars[5] = 67;
  // mychars[6] = 46;
  // mychars[7] = 46;
  // mychars[8] = 46;
  // mychars[9] = 226;
  // mychars[10] = 128;
  // mychars[11] = 157;
  // mychars[12] = 0;
  //
  // wxString leftquote = wxString((const char *)mychars, wxConvUTF8);
  //
  // wxMessageBox(leftquote, wxT("Quote Test"), wxOK |
  // wxICON_INFORMATION, this);

  /*
   * Add global options reported by SwordManager 
   */
  StringList::iterator it;
  int id = ID_MenuTopBookOption;

  menuOptions->Append(ID_MenuSearch, _("Search"));
  menuOptions->AppendSeparator();
  menuOptions->Append(ID_MenuPrefs, _("Preferences"));
  menuOptions->AppendSeparator();

  for (it = optlist.begin(); it != optlist.end(); it++)
  {
    menuOptions->AppendCheckItem(id, wxString(it->c_str(), wxConvUTF8),
                                 wxString(m_SwordTools->GetSwordManager()->
                                          getGlobalOptionTip(it->c_str()),
                                          wxConvUTF8));
    /*
     * If global option is on, check the menu item 
     */
    if (!strcmp
        (m_SwordTools->GetSwordManager()->getGlobalOption(it->c_str()), "On"))
    {
      menuOptions->Check(id, true);
    }
    else
    {
      menuOptions->Check(id, false);
    }

    id++;
  }

  // menuBibleStudies->Append(ID_MenuBibleStudyWhy, wxT("Why Should I
  // Become a Christian?"));
  menuBibleStudies->Append(ID_MenuBibleStudyHow,
                           _("How Can I Become a Christian?"));
  menuBibleStudies->Append(ID_MenuBibleStudyGrow,
                           _("How Can I Grow as a Christian?"));

  wxMenuBar *menuBar = new wxMenuBar();

  menuBar->Append(menuFile, _("&File"));
  menuBar->Append(menuEdit, _("&Edit"));
  menuBar->Append(menuBibleStudies, _("&Bible Studies"));
  menuBar->Append(menuOptions, _("&Options"));
  menuBar->Append(menuWindow, _("&Window"));
  menuBar->Append(menuHelp, _("&Help"));

  SetMenuBar(menuBar);

  CreateStatusBar();
  SetStatusText(_("Welcome to BibleStudy!"));

  m_ToolBar =
    new BookViewToolBar(this, ID_BookViewToolBar, wxTB_HORIZONTAL |
                        wxTB_FLAT | wxTB_TEXT | wxFULL_REPAINT_ON_RESIZE);
  SetToolBar(m_ToolBar);

  // Add the ReadingPlanner toolbar here.

  m_PlanToolBar =
    new ReadingPlannerToolBar(this, ID_ReadingPlannerToolBar, wxTB_HORIZONTAL |
                              wxTB_FLAT );
  UpdatePlanToolBar();


  ShowHidePlanBar(false);
  SetupSplitterWindows();
  LayoutChildren();
}
Ejemplo n.º 15
0
void SearchContext::searchProc()
{
    int id = searchID_;
    HANDLE findHandle = INVALID_HANDLE_VALUE;
    StringList paths;
    paths = params_.paths;
    RegexList filespecRegexes;
    pcre *matchRegex = NULL;

    directoriesSearched_ = 0;
    directoriesSkipped_ = 0;
    filesSearched_ = 0;
    filesSkipped_ = 0;
    filesWithHits_ = 0;
    linesWithHits_ = 0;
    hits_ = 0;

    unsigned int startTick = GetTickCount();

    bool filespecUsesRegexes = ((params_.flags & SF_FILESPEC_REGEXES) != 0);
    bool matchUsesRegexes    = ((params_.flags & SF_MATCH_REGEXES) != 0);

	delete pokeData_;
	pokeData_ = new PokeData;

    if(matchUsesRegexes)
    {
        const char *error;
        int erroffset;
        int flags = 0;
        if(!(params_.flags & SF_MATCH_CASE_SENSITIVE))
            flags |= PCRE_CASELESS;
        matchRegex = pcre_compile(params_.match.c_str(), flags, &error, &erroffset, NULL);
        if(!matchRegex)
        {
            MessageBox(window_, error, "Match Regex Error", MB_OK);
            goto cleanup;
        }
    }

    for(StringList::iterator it = params_.filespecs.begin(); it != params_.filespecs.end(); ++it)
    {
        std::string regexString = it->c_str();
        if(!filespecUsesRegexes)
            convertWildcard(regexString);

        int flags = 0;
        if(!(params_.flags & SF_FILESPEC_CASE_SENSITIVE))
            flags |= PCRE_CASELESS;

        const char *error;
        int erroffset;
        pcre *regex = pcre_compile(regexString.c_str(), flags, &error, &erroffset, NULL);
        if(regex)
            filespecRegexes.push_back(regex);
        else
        {
            MessageBox(window_, error, "Filespec Regex Error", MB_OK);
            goto cleanup;
        }
    }

    PostMessage(window_, WM_SEARCHCONTEXT_STATE, 1, 0);

    while(!paths.empty())
    {
        directoriesSearched_++;
        stopCheck();

        std::string currentSearchPath = paths.back();
        std::string currentSearchWildcard = currentSearchPath + "\\*";

        paths.pop_back();

        WIN32_FIND_DATA wfd;
        findHandle = FindFirstFile(currentSearchWildcard.c_str(), &wfd);
        if(findHandle == INVALID_HANDLE_VALUE)
            continue;

        while(FindNextFile(findHandle, &wfd))
        {
            stopCheck();
            bool isDirectory = ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);

            if((wfd.cFileName[0] == '.') || (wfd.cFileName[0] == 0))
            {
                if(isDirectory)
                    directoriesSkipped_++;
                else
                    filesSkipped_++;
                continue;
            }

            std::string filename = currentSearchPath;
            filename += "\\";
            filename += wfd.cFileName;

            if(isDirectory)
            {
                if(params_.flags & SF_RECURSIVE)
                    paths.push_back(filename);
            }
            else
            {
                if(searchFile(id, filename, filespecRegexes, matchRegex))
                {
                    filesSearched_++;
                }
                else
                {
                    filesSkipped_++;
                }
                poke(id, "", HighlightList(), 0, false);
            }
        }

        if(findHandle != INVALID_HANDLE_VALUE)
        {
            FindClose(findHandle);
        }
    }

cleanup:
    for(RegexList::iterator it = filespecRegexes.begin(); it != filespecRegexes.end(); ++it)
    {
        pcre_free(*it);
    }
    if(matchRegex)
        pcre_free(matchRegex);
    filespecRegexes.clear();
    if(!stop_)
    {
        unsigned int endTick = GetTickCount();
        char buffer[512];
        float sec = (endTick - startTick) / 1000.0f;
        const char *verb = "searched";
        if(params_.flags & SF_REPLACE)
            verb = "updated";
        sprintf(buffer, "\n%d hits in %d lines across %d files.\n%d directories scanned, %d files %s, %d files skipped (%3.3f sec)", 
            hits_,
            linesWithHits_,
            filesWithHits_,
            directoriesSearched_,
            filesSearched_,
            verb,
            filesSkipped_,
            sec);
        poke(id, buffer, HighlightList(), 0, true);
    }
    delete pokeData_;
	pokeData_ = NULL;
    PostMessage(window_, WM_SEARCHCONTEXT_STATE, 0, 0);
}
Ejemplo n.º 16
0
// creates a page based on user input -- either displays data from
//   form or presents a form for users to submit data.
ResponseCode FormTester::HandleRequest ( HttpRequest * ipoHttpRequest,
        HttpResponse * ipoHttpResponse )
{
    char psHtml[ 5000 ];


    // if we got data from the user, show it
    if ( ipoHttpRequest->oFormValueMap [ "user" ].sBody.length ( ) ||
            ipoHttpRequest->oFormValueMap [ "existinguser" ].sBody.length ( ) ) {

        std::string sName;

        sName = ipoHttpRequest->oFormValueMap [ "existinguser" ].sBody;
        if ( ipoHttpRequest->oFormValueMap [ "user" ].sBody.length() ) {
            sName = ipoHttpRequest->oFormValueMap [ "user" ].sBody;
        }

        fprintf ( stderr, "Got name of %s\n", sName.c_str ( ) );

        char * psHtml = new char [ 5000 ];
        sprintf ( psHtml, "<html><head><title>StringList</title></head>\n<body>Hi %s</body></html>", sName.c_str ( ) );
        oNameList.push_back ( sName );

        ipoHttpResponse->SetBody( psHtml, strlen( psHtml ) );
        return HTTPRESPONSECODE_200_OK;

    } else {

        // otherwise, present the form to the user to fill in
        fprintf ( stderr, "Got no form data\n" );

        // create the options for the dropdown box
        char * psOptions;
        if ( oNameList.size ( ) > 0 )
            psOptions = new char [ oNameList.size ( ) * 200 ];
        else
            psOptions = new char [1];

        psOptions [ 0 ] = '\0';

        for ( StringList::iterator oCurrentName = oNameList.begin();
                oCurrentName != oNameList.end ( );
                oCurrentName++ ) {

            char psOption [ 200 ];
            sprintf ( psOption, "<option>%s\n",
                      oCurrentName->substr ( 0, 150 ).c_str ( ) );
            strcat ( psOptions, psOption );

        }

        sprintf ( psHtml, "<html><head><title>StringList</title></head> <body>Please log in<P> <form action = \"/\" method=GET> User name: <input type = text  name = user><BR> <select name = existinguser width = 20> %s </select> <input type = submit> </form>\n",
                  psOptions );

        delete[] psOptions;

        ipoHttpResponse->SetBody( psHtml, strlen( psHtml ) );
        return HTTPRESPONSECODE_200_OK;

    }

}
Ejemplo n.º 17
0
string ListBox::GetLine( int index )
{
	StringList::iterator it = m_messages.begin();
	return it->data();
}
  void DigestSimulation::digest(SimTypes::FeatureMapSim& feature_map)
  {
    LOG_INFO << "Digest Simulation ... started" << std::endl;

    if ((String)param_.getValue("enzyme") == String("none"))
    {
      //peptides = proteins;
      // convert all proteins into peptides

      // for each protein_hit in the FeatureMap
      for (std::vector<ProteinHit>::iterator protein_hit = feature_map.getProteinIdentifications()[0].getHits().begin();
           protein_hit != feature_map.getProteinIdentifications()[0].getHits().end();
           ++protein_hit)
      {
        // generate a PeptideHit hit with the correct link to the protein
        PeptideHit pep_hit(1.0, 1, 0, AASequence::fromString(protein_hit->getSequence()));
        PeptideEvidence pe;
        pe.setProteinAccession(protein_hit->getAccession());
        pep_hit.addPeptideEvidence(pe);

        // add the PeptideHit to the PeptideIdentification
        PeptideIdentification pep_id;
        pep_id.insertHit(pep_hit);

        // generate Feature with correct Intensity and corresponding PeptideIdentification
        Feature f;
        f.getPeptideIdentifications().push_back(pep_id);
        f.setIntensity(protein_hit->getMetaValue("intensity"));

        // copy intensity meta-values and additional annotations from Protein to Feature
        StringList keys;
        protein_hit->getKeys(keys);
        for (StringList::const_iterator it_key = keys.begin(); it_key != keys.end(); ++it_key)
        {
          f.setMetaValue(*it_key, protein_hit->getMetaValue(*it_key));
        }

        // add Feature to SimTypes::FeatureMapSim
        feature_map.push_back(f);
      }

      return;
    }


    UInt min_peptide_length = param_.getValue("min_peptide_length");
    bool use_log_model = param_.getValue("model") == "trained" ? true : false;
    UInt missed_cleavages = param_.getValue("model_naive:missed_cleavages");
    double cleave_threshold = param_.getValue("model_trained:threshold");

    EnzymaticDigestion digestion;
    digestion.setEnzyme(digestion.getEnzymeByName((String)param_.getValue("enzyme")));
    digestion.setLogModelEnabled(use_log_model);
    digestion.setLogThreshold(cleave_threshold);

    std::vector<AASequence> digestion_products;

    // keep track of generated features
    std::map<AASequence, Feature> generated_features;

    // Iterate through ProteinHits in the FeatureMap and digest them
    for (std::vector<ProteinHit>::iterator protein_hit = feature_map.getProteinIdentifications()[0].getHits().begin();
         protein_hit != feature_map.getProteinIdentifications()[0].getHits().end();
         ++protein_hit)
    {
      // determine abundance of each digestion product (this is quite long now...)
      // we assume that each digestion product will have the same abundance
      // note: missed cleavages reduce overall abundance as they combine two (or more) single peptides

      // how many "atomic"(i.e. non-cleavable) peptides are created?
      digestion.setMissedCleavages(0);
      Size complete_digest_count = digestion.peptideCount(AASequence::fromString(protein_hit->getSequence()));
      // compute average number of "atomic" peptides summed from all digestion products
      Size number_atomic_whole = 0;
      Size number_of_digestion_products = 0;
      for (Size i = 0; (i <= missed_cleavages) && (i < complete_digest_count); ++i)
      {
        number_atomic_whole += (complete_digest_count - i) * (i + 1);
        number_of_digestion_products += (complete_digest_count - i);
      }

      // mean number of "atomic" peptides per digestion product is now: number_atomic_whole / number_of_digestion_products
      // -> thus abundance of a digestion product is: #proteins / avg#of"atomic"peptides
      // i.e.: protein->second / (number_atomic_whole / number_of_digestion_products)

      Map<String, SimTypes::SimIntensityType> intensities;
      StringList keys;
      protein_hit->getKeys(keys);
      for (StringList::const_iterator it_key = keys.begin(); it_key != keys.end(); ++it_key)
      {
        if (!it_key->hasPrefix("intensity"))
          continue;
        intensities[*it_key] = std::max(SimTypes::SimIntensityType(1), SimTypes::SimIntensityType(protein_hit->getMetaValue(*it_key))
                                        * SimTypes::SimIntensityType(number_of_digestion_products)
                                        / SimTypes::SimIntensityType(number_atomic_whole)); // order changed for numeric stability
      }

      // do real digest
      digestion.setMissedCleavages(missed_cleavages);
      digestion.digest(AASequence::fromString(protein_hit->getSequence()), digestion_products);

      for (std::vector<AASequence>::const_iterator dp_it = digestion_products.begin();
           dp_it != digestion_products.end();
           ++dp_it)
      {
        if (dp_it->size() < min_peptide_length)
          continue;

        // sum equal peptide's intensities
        // *dp_it -> peptide
        // If we see this Peptide the first time -> generate corresponding feature
        if (generated_features.count(*dp_it) == 0)
        {
          PeptideHit pep_hit(1.0, 1, 0, *dp_it);

          PeptideIdentification pep_id;
          pep_id.insertHit(pep_hit);

          // create feature
          Feature f;
          f.getPeptideIdentifications().push_back(pep_id);
          // set intensity to 0 to avoid problems when summing up
          f.setIntensity(0.0);

          // copy all non-intensity meta values
          StringList lkeys;
          protein_hit->getKeys(lkeys);
          for (StringList::iterator key = lkeys.begin(); key != lkeys.end(); ++key)
          {
            if (!key->hasPrefix("intensity"))
            {
              f.setMetaValue(*key, protein_hit->getMetaValue(*key));
            }
          }

          // insert into map
          generated_features.insert(std::make_pair(*dp_it, f));
        }

        // sum up intensity values
        generated_features[*dp_it].setIntensity(generated_features[*dp_it].getIntensity() + intensities["intensity"]);
        // ... same for other intensities (iTRAQ...)
        for (Map<String, SimTypes::SimIntensityType>::const_iterator it_other = intensities.begin(); it_other != intensities.end(); ++it_other)
        {
          if (!generated_features[*dp_it].metaValueExists(it_other->first))
          {
            generated_features[*dp_it].setMetaValue(it_other->first, it_other->second);
          }
          else
          {
            generated_features[*dp_it].setMetaValue(it_other->first, SimTypes::SimIntensityType(generated_features[*dp_it].getMetaValue(it_other->first)) + it_other->second);
          }
        }

        // add current protein accession
        // existing proteins accessions ...
        std::set<String> protein_accessions = generated_features[*dp_it].getPeptideIdentifications()[0].getHits()[0].extractProteinAccessions();

        // ... add accession of current protein
        protein_accessions.insert(protein_hit->getAccession());

        std::vector<PeptideIdentification> pep_idents = generated_features[*dp_it].getPeptideIdentifications();
        std::vector<PeptideHit> pep_hits = pep_idents[0].getHits();

        for (std::set<String>::const_iterator s_it = protein_accessions.begin(); s_it != protein_accessions.end(); ++s_it)
        {
          PeptideEvidence pe;
          pe.setProteinAccession(*s_it);
          pep_hits[0].addPeptideEvidence(pe);
        }
        pep_idents[0].setHits(pep_hits);
        generated_features[*dp_it].setPeptideIdentifications(pep_idents);
      }
    }

    // add generated_features to FeatureMap
    for (std::map<AASequence, Feature>::iterator it_gf = generated_features.begin();
         it_gf != generated_features.end();
         ++it_gf)
    {
      // round up intensity
      (it_gf->second).setIntensity(ceil((it_gf->second).getIntensity()));
      feature_map.push_back(it_gf->second);
    }

  }
bool ObjectTemplateCustomizationDataWriter::writeToFile(const std::string &pathName, bool allowOverwrite)
{
	//-- Don't write anything if there's no data to write.
	bool hasData = false;

	if (!m_paletteColorData->empty())
		hasData = true;

	if (!m_rangedIntData->empty())
		hasData = true;

	if (!hasData)
	{
		DEBUG_REPORT_LOG(true, ("writeToFile(): no data: skipped writing [%s].\n", pathName.c_str()));
		return true;
	}

	//-- Handle no-overwrite case.
	if (!allowOverwrite)
	{
		FILE *const testFile = fopen(pathName.c_str(), "r");
		if (testFile != NULL)
		{
			fclose(testFile);
			DEBUG_REPORT_LOG(true, ("writeToFile(): overwrite attempt: skipped writing [%s] because it already exists and allowOverwrite == false.\n", pathName.c_str()));
			return false;
		}
	}

	//-- open file
	FILE *const file = fopen(pathName.c_str(), "w");
	if (!file)
	{
		WARNING(true, ("failed to create file [%s].", pathName.c_str()));
		return false;
	}

	//-- sort the output data
	m_paletteColorData->sort();
	m_rangedIntData->sort();

	//-- write palette color variables
	fprintf(file, "paletteColorCustomizationVariables = [");
	{
		int i = 0;
		int const count = static_cast<int>(m_paletteColorData->size());

		const StringList::iterator endIt = m_paletteColorData->end();
		for (StringList::iterator it = m_paletteColorData->begin(); it != endIt; ++it, ++i)
		{
			if (i == (count - 1))
			{
				// -- Fixup last entry to use ] in place of final comma.
				std::string::size_type position = it->rfind(',');
				DEBUG_FATAL(static_cast<int>(position) == static_cast<int>(std::string::npos), ("bad data, where's the final comma?"));

				(*it)[position] = ']';
			}

			fprintf(file, "\n  %s", it->c_str());
		}
	}
	if (m_paletteColorData->empty())
		fprintf(file, "]");
	fprintf(file, "\n\n");

	//-- write ranged int variables
	fprintf(file, "rangedIntCustomizationVariables = [");
	{
		int i = 0;
		int const count = static_cast<int>(m_rangedIntData->size());

		const StringList::iterator endIt = m_rangedIntData->end();
		for (StringList::iterator it = m_rangedIntData->begin(); it != endIt; ++it, ++i)
		{
			if (i == (count - 1))
			{
				// -- Fixup last entry to use ] in place of final comma.
				std::string::size_type position = it->rfind(',');
				DEBUG_FATAL(static_cast<int>(position) == static_cast<int>(std::string::npos), ("bad data, where's the final comma?"));

				(*it)[position] = ']';
			}

			fprintf(file, "\n  %s", it->c_str());
		}
	}
	if (m_rangedIntData->empty())
		fprintf(file, "]");
	fprintf(file, "\n\n");

	fclose(file);

	//-- return success
	return true;
}