/** For each mask check if done, then update CurrentVars, then increment. */ ControlBlock::DoneType ControlBlock_For::CheckDone(Varray& CurrentVars) { static const char* prefix[] = {"@", ":", "^", ":", ":"}; for (Marray::iterator MH = Vars_.begin(); MH != Vars_.end(); ++MH) { // Exit as soon as one is done TODO check all? if (MH->varType_ == INTEGER) { if (MH->endOp_ == LESS_THAN) { if (MH->currentVal_ >= MH->end_) return DONE; } else if (MH->endOp_ == GREATER_THAN) { if (MH->currentVal_ <= MH->end_) return DONE; } // Get variable value and update CurrentVars CurrentVars.UpdateVariable( MH->varname_, integerToString( MH->currentVal_ )); // Increment MH->currentVal_ += MH->inc_; } else if (MH->varType_ == LIST) { if (MH->sdx_ == MH->List_.end()) return DONE; // Get variable value CurrentVars.UpdateVariable( MH->varname_, *(MH->sdx_) ); // Increment ++(MH->sdx_); } else { if (MH->idx_ == MH->Idxs_.end()) return DONE; // Get variable value std::string maskStr = prefix[MH->varType_] + integerToString(*(MH->idx_) + 1); //mprintf("DEBUG: ControlBlock_For: %s\n", maskStr.c_str()); // Update CurrentVars CurrentVars.UpdateVariable( MH->varname_, maskStr ); // Increment ++(MH->idx_); } } return NOT_DONE; }
string ViewType::getTimeTaskString(int time) { string timeString; if(time >= 0) { if(time >= TIME_MIDDAY) { if(time >= TIME_MIDDAY + 100) { time = time - TIME_MIDDAY; } timeString = integerToString(time); timeString = timeString + MESSAGE_PM; } else { if(time < 100) { time = time + TIME_MIDDAY; } timeString = integerToString(time); timeString = timeString + MESSAGE_AM; } timeString.insert(timeString.size() - TIME_STRING_INT, MESSAGE_TIME_SEPERATOR); return timeString; } else { return MESSAGE_VOID_STRING; } }
void addBiggerThanByte(map<int, int> freqTable, obitstream& output){ output.put('{'); for(map<int, int>::iterator it = freqTable.begin(); it != freqTable.end(); ++it){ int first = it->first; int second = it->second; string firstString = integerToString(first); while(firstString.size() > 0){ char tempFirst = firstString.front(); output.put(tempFirst); firstString.erase(firstString.begin()); } output.put(':'); string secondString = integerToString(second); while(secondString.size() > 0){ char tempSecond = secondString.front(); output.put(tempSecond); secondString.erase(secondString.begin()); } //Iterationen innan slutet för utskrift av kommatecken if(it != --freqTable.end()){ output.put(','); output.put(' '); } } output.put('}'); }
/** * Standard input for a Fuzzy SOM * Parameter: _is The input stream */ void FuzzyMap::readSelf(std::istream& _is, const unsigned _size) { clear(); int dim; std::string layout, str; _is >> dim; _is >> layout; if (layout == "HEXA") { HEXALayout *tmpLayout = new HEXALayout(); somLayout = tmpLayout; } else { RECTLayout *tmpLayout = new RECTLayout(); somLayout = tmpLayout; } _is >> somWidth; _is >> somHeight; str = integerToString(dim); str += " "; str += integerToString(somWidth * somHeight); str += " "; for (int i = str.size() - 1; i >= 0; i--) if (_is) _is.putback((char) str[i]); FuzzyCodeBook::readSelf(_is, _size); }
// 18 void endIteration(FILE* file, DynamicTable* symbols, Token token) { printf("semantic: EOI\n");fflush(stdout); // allows end of conditional or iteration blocks label with NOP (instruction with no effect) if(!strncmp(label, "_else", 5)) { fprintf(file, "%s\tJP\t_then%d\n", label, top(ifs)); strcpy(label, "_then"); strcat(label, integerToString(auxiliar, pop(&ifs), 10)); strcpy(auxiliar, ""); } fflush(file); // cannot end block with opened label if(strcmp(label, "") && strncmp(label, "_then", 5) && strncmp(label, "_do", 3) && strncmp(label, "_finally", 8)) { printf("ERROR: label \"%s\" at the end of compound statement.\n", label); fprintf(file, "ERROR: label \"%s\" at the end of compound statement.\n", label); fflush(stdout); fflush(file); system("PAUSE"); exit(5); } fprintf(file, "%s\tJP\t_while%d\n", label, top(whiles)); fflush(file); strcpy(label, "_finally"); strcat(label, integerToString(auxiliar, pop(&whiles), 10)); strcpy(auxiliar, ""); }
void GBufferedImage::load(const std::string& filename) { // for efficiency, let's at least check whether the file exists // and throw error immediately rather than contacting the back-end if (!fileExists(filename)) { error("GBufferedImage::load: file not found: " + filename); } std::string result = pp->gbufferedimage_load(this, filename); result = Base64::decode(result); std::istringstream input(result); std::string line; if (!getline(input, line)) { error("GBufferedImage::load: image data does not contain valid width"); } m_width = stringToInteger(line); if (!getline(input, line)) { error("GBufferedImage::load: image data does not contain valid height"); } m_height = stringToInteger(line); for (int y = 0; y < m_height; y++) { for (int x = 0; x < m_width; x++) { if (!getline(input, line)) { error("GBufferedImage::load: image data does not contain valid pixel (x=" + integerToString(x) + ", y=" + integerToString(y) + ")"); } int px = convertColorToRGB(line); m_pixels[y][x] = px; } } }
// TODO benchmark - will using a big buffer and C string routines be better? void TextFormat::SetFormatString() { std::string width_arg, prec_arg, left_arg, long_arg; // Set width and/or precision if applicable. if (width_ > 0) width_arg.assign( integerToString( width_ ) ); if (precision_ > -1 && (int)type_ < (int)INTEGER) prec_arg.assign( "." + integerToString( precision_ ) ); if (align_ == LEFT) left_arg.assign("-"); if (isLong_) long_arg.assign("l"); // Set format string. if (align_ == LEADING_SPACE) { fmt_.assign(" "); colwidth_ = 1; } else { fmt_.clear(); colwidth_ = 0; } for (int i = 0; i != nelements_; i++) { if (i != 0) { fmt_.append(" "); // TODO: Option to not have spaces in-between? colwidth_++; } fmt_.append( "%" + left_arg + long_arg + width_arg + prec_arg + TypeChar_[type_] ); colwidth_ += width_; } }
static void eraseOldScore(Player playerNum, int value) { gwp->setFont(SCORE_FONT + "-" + integerToString(SCORE_FONT_SIZE)); string str = integerToString(value); fillBox(gState.scoreBox[playerNum].x + gState.scoreBox[playerNum].w - gwp->getStringWidth(str), gState.scoreBox[playerNum].y + LABEL_DY - SCORE_FONT_SIZE, gwp->getStringWidth(str), SCORE_FONT_SIZE, "White"); }
/** Create a name based on the given defaultName and # of DataSets, * i.e. defaultName_XXXXX */ std::string DataSetList::GenerateDefaultName(std::string const& defaultName) const { // Determine # chars needed to hold text version of set number (min 5). size_t extsize = (size_t) DigitWidth( size() ); if (extsize < 5) extsize = 5; if (defaultName.empty()) return ( "D" + integerToString(size(), extsize) ); else return ( defaultName + "_" + integerToString(size(), extsize) ); }
static void drawOneScore(Player playerNum, int value) { gwp->setFont(SCORE_FONT + "-" + integerToString(SCORE_FONT_SIZE)); gwp->setColor(LABEL_COLOR); string str = integerToString(value); gwp->drawString(str, gState.scoreBox[playerNum].x + gState.scoreBox[playerNum].w - gwp->getStringWidth(str), gState.scoreBox[playerNum].y + LABEL_DY); }
void GBufferedImage::checkIndex(std::string member, double x, double y) const { if (!inBounds(x, y)) { error("GBufferedImage::" + member + ": (x=" + integerToString((int) x) + ", y=" + integerToString((int) y) + ") is out of valid range of (0, 0) through (" + integerToString((int) m_width) + ", " + integerToString((int) m_height) + ")"); } }
vector<string> Settings::settingsGetVector() { vector<string> updatedData; updatedData.push_back(_textFileName); updatedData.push_back(_saveDirectory); updatedData.push_back(integerToString(_viewType)); updatedData.push_back(integerToString(_width)); updatedData.push_back(integerToString(_length)); return updatedData; }
string LinkedIntList::toString() const { string result = "{"; if (!isEmpty()) { result += integerToString(front->data); ListNode* curr = front->next; while (curr != NULL) { result += ", " + integerToString(curr->data); curr = curr->next; } } return result + "}"; }
void Grid<ValueType>::resize(int nRows, int nCols) { if (nRows < 0 || nCols < 0) { error("Attempt to resize grid to invalid size (" + integerToString(nRows) + ", " + integerToString(nCols) + ")"); } if (elements != NULL) delete[] elements; this->nRows = nRows; this->nCols = nCols; elements = new ValueType[nRows * nCols]; ValueType value = ValueType(); for (int i = 0; i < nRows * nCols; i++) { elements[i] = value; } }
void TestSuite::suiteAssertEquals(Test& test, int expected, int actual, int lineNumber) { bool areEqual = (expected == actual); if (!areEqual && test.successful) { test.successful = false; addFailure(); char expectedBuffer[MAX_INTEGER_LENGTH]; integerToString(expected, expectedBuffer); char actualBuffer[MAX_INTEGER_LENGTH]; integerToString(actual, actualBuffer); reporter->reportEqualityFailure(test, adjustLineNumber(lineNumber), expectedBuffer, actualBuffer); } }
/** \return Replica file name for given offset from lowest replica number. */ FileName File::RepName::RepFilename(int offset) const { FileName trajFilename; trajFilename.SetFileName_NoExpansion( Prefix_ + extChar_ + integerToString(lowestRepnum_ + offset, ExtWidth_) + CompressExt_ ); return trajFilename; }
/* Member function obitstream::writeBit * ---------------------------------- * If bits remain to be written in curByte, add bit into byte and increment pos * Else if end of curByte (or some other write happened), then start a fresh * byte at position 0. * We write the byte out for each bit (backing up to overwrite as needed), rather * than waiting for 8 bits. This is because the client might make * 3 writeBit calls and then start using << so we can't wait til full-byte * boundary to flush any partial-byte bits. */ void obitstream::writeBit(int bit) { if (bit != 0 && bit != 1) { error(string("writeBit must be passed an integer argument of 0 or 1. You passed the integer ") + toPrintable(bit) + " (" + integerToString(bit) + ")."); } if (!is_open()) { error("Cannot writeBit to stream which is not open."); } // if just filled curByte or if data written to stream after last writeBit() if (lastTell != tellp() || pos == NUM_BITS_IN_BYTE) { curByte = 0; // zero out byte for next writes pos = 0; // start writing to first bit of new byte } if (bit) { // only need to change if bit needs to be 1 (byte starts already zeroed) SetNthBit(pos, curByte); } if (pos == 0 || bit) { // only write if first bit in byte or changing 0 to 1 if (pos != 0) { seekp(-1, ios::cur); // back up to overwite if pos > 0 } put(curByte); } pos++; // advance to next bit position for next write lastTell = tellp(); }
// 21 void setParam(FILE* file, DynamicTable* symbols, Token token) { int i; char nick[128]; printf("semantic: param\n");fflush(stdout); i = lookUpForCell(*symbols, identifier, "variable"); if(i == -1) { strcpy(nick, "_param"); strcat(nick, integerToString(auxiliar, params++, 10)); strcat(nick, "_"); strcat(nick, procedure); i = addToTable(symbols, identifier, nick, "variable"); defineRow(symbols, i); strcpy(identifier, ""); strcpy(auxiliar, ""); strcpy(type, ""); fprintf(file, "%s\t K\t/0000\n", nick); fflush(file); } else { printf("ERROR: redeclaration of \"%s\".\n", identifier); fprintf(file, "ERROR: redeclaration of \"%s\".\n", identifier); fflush(stdout); fflush(file); system("PAUSE"); exit(5); } }
long int Assembly::addMolecule(Molecule &toadd) { std::string ori_toadd_name = simplify(toadd.name); // Check whether the name of this molecule is unique // If not add a suffix to it bool is_uniq = false; int suffix = 0; while (!is_uniq) { suffix++; is_uniq = true; for (int imol = 0; imol < molecules.size(); imol++) { if (molecules[imol].name == toadd.name) { is_uniq = false; break; } } if (!is_uniq) { toadd.name = ori_toadd_name + integerToString(suffix); } } long int result = molecules.size(); molecules.push_back(toadd); return result; }
// Analysis_CrossCorr::Analyze() Analysis::RetType Analysis_CrossCorr::Analyze() { DataSet_MatrixFlt& tmatrix = static_cast<DataSet_MatrixFlt&>( *matrix_ ); if (tmatrix.AllocateTriangle(input_dsets_.size())) return Analysis::ERR; mprintf("\tDataSet Legend:\n"); std::string Ylabels("\""); for (Array1D::const_iterator ds = input_dsets_.begin(); ds != input_dsets_.end(); ++ds) { int idx = (int)(ds - input_dsets_.begin() + 1); mprintf("\t\t%8i: %s\n", idx, (*ds)->legend()); //Xlabels_ += (dsets_[i]->Legend() + ","); Ylabels += (integerToString(idx) + ":" + (*ds)->Meta().Legend() + ","); } Ylabels += "\""; for (Array1D::const_iterator ds0 = input_dsets_.begin(); ds0 != input_dsets_.end(); ++ds0) { DataSet_1D const& set0 = static_cast<DataSet_1D const&>( *(*ds0) ); for (Array1D::const_iterator ds1 = ds0 + 1; ds1 != input_dsets_.end(); ++ds1) { float corr = (float)set0.CorrCoeff( *(*ds1) ); //mprinterr("DBG:\tCross corr between %i (%s) and %i (%s)\n", // i, dsets_[i]->legend(), j, dsets_[j]->legend()); tmatrix.AddElement( corr ); } } if (outfile_ != 0) outfile_->ProcessArgs("ylabels " + Ylabels); return Analysis::OK; }
/** Generate a temporary file name of format: * TempPrefix_<#> * where <#> is based on the current number of temporary file names * that have been requested. */ FileName GenTempName() { // Could also set this to 0, but setting it to size is a better guarantee // that the name will be free. unsigned int tmpidx = TempFileNames_.size(); FileName temp( TempPrefix_ + integerToString(tmpidx) ); while (tmpidx < maxtmpidx_ && Exists(temp)) { tmpidx++; temp = FileName( TempPrefix_ + integerToString(tmpidx) ); } if (tmpidx >= maxtmpidx_) { mprinterr("Internal Error: Too many temporary files. Remove files named '%s*'\n", TempPrefix_.c_str()); return FileName(); } return temp; }
/* * Creates all cubes in position, including a blank letter centered in * the middle of each cube. Initially the cubes are not highlighted. */ static void setupLetterCubes() { double lineWidth = 2; double cubeSize = gState.cubeSize - lineWidth; double cubeY = gState.board.y + BOARD_BORDER/2; for (int row = 0; row < gState.rowCount; row++) { double cubeX = gState.board.x + BOARD_BORDER/2; for (int col = 0; col < gState.columnCount; col++) { // display the letter cubes as rounded rectangles double cubeRoundRadius = gState.cubeSize/5; GRoundRect* rect = new GRoundRect(cubeX, cubeY, cubeSize, cubeSize, cubeRoundRadius * 2); rect->setLineWidth(lineWidth); rect->setColor("Black"); rect->setFilled(true); rect->setFillColor(DIE_COLOR); gwp->add(rect); letterCubes[row][col].rect = rect; // draw the letter on the cube GLabel* label = new GLabel("M"); // start as "M" for getWidth label->setFont(CUBE_FONT + "-" + integerToString(int(gState.fontSize))); label->setColor(LETTER_COLOR); label->setLocation(cubeX + gState.cubeSize/2 - label->getWidth()/2, cubeY + gState.cubeSize/2 + 0.4 * gState.fontSize); label->setLabel(" "); gwp->add(label); letterCubes[row][col].label = label; cubeX += (int) cubeSize + lineWidth; } cubeY += (int) cubeSize + lineWidth; } }
/** * It is called each time a new chunk of data is received. * @param conn The Connection that ran the operation. * @param result The number of bytes read on success, * or a \link #CONNERR_GENERIC CONNERR \endlink code \< 0 on failure. */ void MediaWiki::connRecvFinished(MAUtil::Connection * conn, int result) { if(result >= 0) { // Notify the UI that a new chunk was received mHomeScreen->engineChunkReceived(); // Parse each chunk. // mBuffer now contains the result,we can now parse it. processSearchResults(); // Read next chunk of data. mHttp.recv(mBuffer, CONNECTION_BUFFER_SIZE); return; } else if(result == CONNERR_CLOSED) { // The result is parsed, now display it( if there is any). if ( mWiki->titleResults.size() > 0 ){ mHomeScreen->engineFinished(); } else{ // No results available,display some message. mHomeScreen->engineError(ERROR_NO_RESULTS); } } else { // Notify the UI of the error. mHomeScreen->engineError(ERROR_INVALID_DATA+integerToString(result, 10)); } mHttp.close(); mIsConnected = false; }
/** For each point p, calculate function Kdist(p) which is the distance of * the Kth nearest point to p. */ void Cluster_DBSCAN::ComputeKdist( int Kval, std::vector<int> const& FramesToCluster ) const { std::vector<double> dists; std::vector<double> Kdist; dists.reserve( FramesToCluster.size() ); Kdist.reserve( FramesToCluster.size() ); std::string outfilename = k_prefix_ + "Kdist." + integerToString(Kval) + ".dat"; mprintf("\tDBSCAN: Calculating Kdist(%i), output to %s\n", Kval, outfilename.c_str()); for (std::vector<int>::const_iterator point = FramesToCluster.begin(); point != FramesToCluster.end(); ++point) { // Store distances from this point dists.clear(); for (std::vector<int>::const_iterator otherpoint = FramesToCluster.begin(); otherpoint != FramesToCluster.end(); ++otherpoint) dists.push_back( FrameDistances_.GetFdist(*point, *otherpoint) ); // Sort distances - first dist should always be 0 std::sort(dists.begin(), dists.end()); Kdist.push_back( dists[Kval] ); } std::sort( Kdist.begin(), Kdist.end() ); CpptrajFile Outfile; Outfile.OpenWrite(outfilename); Outfile.Printf("%-8s %1i%-11s\n", "#Point", Kval,"-dist"); // Write out largest to smallest unsigned int ik = 0; for (std::vector<double>::reverse_iterator k = Kdist.rbegin(); k != Kdist.rend(); ++k, ++ik) Outfile.Printf("%8u %12.4f\n", ik, *k); Outfile.CloseFile(); }
// Action_Diffusion::CalcDiffForSet() void Action_Diffusion::CalcDiffForSet(unsigned int& set, Dlist const& Sets, int Ndim, std::string const& label) const { for (Dlist::const_iterator ds = Sets.begin(); ds != Sets.end(); ds++) if (*ds != 0) CalcDiffusionConst(set, *ds, Ndim, label + "_" + integerToString( (*ds)->Meta().Idx() )); }
/* * Labels player word list with specified name and draws a line underneath. * Also sets up the score label for the specified player. */ static void setupPlayerLabels(Player player, string name) { gwp->setColor(LABEL_COLOR); gwp->drawLine(gState.scoreBox[player].x, gState.scoreBox[player].y, gState.scoreBox[player].x + gState.scoreBox[player].w, gState.scoreBox[player].y); GLabel* lab = new GLabel(name); lab->setFont(SCORE_FONT + "-" + integerToString(SCORE_FONT_SIZE)); gwp->add(lab, gState.scoreBox[player].x, gState.scoreBox[player].y + LABEL_DY); GLabel** scoreLabel = player == COMPUTER ? &computerScoreLabel : &humanScoreLabel; *scoreLabel = new GLabel("0"); (*scoreLabel)->setFont(SCORE_FONT + "-" + integerToString(SCORE_FONT_SIZE)); (*scoreLabel)->setColor(LABEL_COLOR); int offset = 32; gwp->add(*scoreLabel, gState.scoreBox[player].x + gState.scoreBox[player].w - offset, gState.scoreBox[player].y + LABEL_DY); }
int myregister(){ string file; cout<< "Registering server...\n"; int sock=tcpConnect("nwprog1.netlab.hut.fi","3000"); if (sock==-1){ printf("Registration Failed\n"); return -1; } int totalWriteByte=0; /*start of sending PUT requst to server*/ string str("PUT /servers-behzad.txt"); str.append(" HTTP/1.1\r\nHost: http://nwprog1.netlab.hut.fi:3000"); str.append("\r\nIam: BEHZAD\r\nContent-Type: text/plain\r\nContent-Length: "); file.append(runningHost); file.append(":"); file.append(integerToString(SERV_PORT)); str.append(integerToString((int)file.length())); str.append("\r\n\r\n"); str.append(file); if ((totalWriteByte=writeString(sock,str))==-1){ cout<<"Error in sending Registration request"; return -1; } /*end of sending PUT requst to server*/ /*read response*/ string headers; headers=readResponse(sock); if (strcmp((const char *)headers.c_str(),"-1")==0) { cout<<"Error in reading response from server\n"; close(sock); return -1; } close(sock); return 0; }
// TODO: Accept const ArgList so arguments are not reset? CpptrajFile* DataFileList::AddCpptrajFile(FileName const& nameIn, std::string const& descrip, CFtype typeIn, bool allowStdout) { // If no filename and stdout not allowed, no output desired. if (nameIn.empty() && !allowStdout) return 0; FileName name; CpptrajFile* Current = 0; int currentIdx = -1; if (!nameIn.empty()) { name = nameIn; // Append ensemble number if set. if (ensembleNum_ != -1) name.Append( "." + integerToString(ensembleNum_) ); // Check if filename in use by DataFile. DataFile* df = GetDataFile(name); if (df != 0) { mprinterr("Error: Text output file name '%s' already in use by data file '%s'.\n", nameIn.full(), df->DataFilename().full()); return 0; } // Check if this filename already in use currentIdx = GetCpptrajFileIdx( name ); if (currentIdx != -1) Current = cfList_[currentIdx]; } // If no CpptrajFile associated with name, create new CpptrajFile if (Current==0) { switch (typeIn) { case TEXT: Current = new CpptrajFile(); break; case PDB: Current = (CpptrajFile*)(new PDBfile()); break; } Current->SetDebug(debug_); // Set up file for writing. //if (Current->SetupWrite( name, debug_ )) if (Current->OpenWrite( name )) { mprinterr("Error: Setting up text output file %s\n", name.full()); delete Current; return 0; } cfList_.push_back( Current ); cfData_.push_back( CFstruct(descrip, typeIn) ); } else { // If Current type does not match typeIn do not allow. if (typeIn != cfData_[currentIdx].Type()) { mprinterr("Error: Cannot change type of text output for '%s'.\n", Current->Filename().full()); return 0; } Current->SetDebug(debug_); // Update description if (!descrip.empty()) cfData_[currentIdx].UpdateDescrip( descrip ); } return Current; }
static void drawPlayerLabel(Player player, string name) { gwp->setColor(LABEL_COLOR); gwp->drawLine(gState.scoreBox[player].x, gState.scoreBox[player].y, gState.scoreBox[player].x + gState.scoreBox[player].w, gState.scoreBox[player].y); gwp->setFont(SCORE_FONT + "-" + integerToString(SCORE_FONT_SIZE)); gwp->drawString(name, gState.scoreBox[player].x, gState.scoreBox[player].y + LABEL_DY); gState.scores[player] = gState.numWords[player] = 0; }
void labelCube(int row, int col, char letter, bool highlighted) { ensureInitialized(); if (row < 0 || row >= gState.rowCount || col < 0 || col >= gState.columnCount) { error(string("labelCube called with invalid row, col arguments. Must be between (0, 0) and (") + integerToString(gState.rowCount) + ", " + integerToString(gState.columnCount) + ")"); } if (!isalpha(letter) && letter != ' ') { error(string("labelCube called with non-alphabetic character: '") + letter); } setHighlighted(row, col, highlighted); GLabel* label = letterCubes[row][col].label; label->setLabel(string(1, letter)); if (isalpha(letter)) { label->setLocation( letterCubes[row][col].rect->getX() + gState.cubeSize/2 - 0.45 * label->getWidth(), letterCubes[row][col].rect->getY() + gState.cubeSize/2 + 0.36 * gState.fontSize); } }