// a function to return a compressed version of a string. string compress(string str) { string output; int len = str.length(); char tmp = str[0]; int tmpcount = 1; bool written = false; for (int i = 1; i < len; i++) { if (str[i] == tmp) { tmpcount++; written = false; } else { output += tmp; output += to_string(tmpcount); tmp = str[i]; tmpcount = 1; written = true; } } if (!written) { output += tmp; output += to_string(tmpcount); } // check to see if compressed or original string is longer, return shortest one. if ((output.length() >= len)) return str; else return output; }
void cCodeGen::Visit(cFuncDeclNode *node) { // Don't do anything if stmts and decls are null (aka, this was a function prototype) if(node->GetDecls() || node->GetStmts()) { m_func_rtn_label = GenerateLabel(); StartFunctionOutput(node->GetTypeName()); // Increment Stack if(node->GetDecls()) EmitString("Stack_Pointer += " + to_string(node->GetDecls()->GetSize()) + ";\n"); // Only print decls/stmts when they exist if(node->GetDecls()) node->GetDecls()->Visit(this); if(node->GetStmts()) node->GetStmts()->Visit(this); EmitString(m_func_rtn_label + ":\n"); // Decrement stack if(node->GetDecls()) EmitString("Stack_Pointer -= " + to_string(node->GetDecls()->GetSize()) + ";\n"); EndFunctionOutput(); } }
string compressString(string &str) { string compressedStr; char compareChar = NULL; char prevChar = str[0]; int counter = 0; for (auto i = 0; i < str.length(); ++i) { compareChar = str[i]; if (compareChar != prevChar) { compressedStr = compressedStr + prevChar + to_string(counter); counter = 0; } ++counter; prevChar = compareChar; } //could not find a way to accomplish this gracefully inside the loop. //Adds the compression for the last grouping of letters. compressedStr = compressedStr + prevChar + to_string(counter); if (compressedStr.length() < str.length()) return compressedStr; else return str; }
//draws the target at given point void drawTarget(Point target, Mat &cameraFeed) { int x = target.x; int y = target.y; line(cameraFeed, Point(x, y + 25), Point(x, y - 25), Scalar(0, 0, 0), 2); line(cameraFeed, Point(x + 25, y), Point(x - 25, y), Scalar(0, 0, 0), 2); putText(cameraFeed, "Tracking object at (" + to_string(x) + "," + to_string(y) + ")", Point(x - 100, y - 30), 1, 1, Scalar(0, 0, 255), 2); }
string generate_container_name() { static unsigned seq = 0; static string prefix = "_test_" + to_string(std::chrono::steady_clock::now().time_since_epoch().count()); return prefix + "_" + to_string(++seq); }
unit_t __jemalloc_context::jemallocStart(unit_t) { #ifdef K3_JEMALLOC bool enable = true; mallctl("prof.active", NULL, 0, &enable, sizeof(enable)); #ifdef K3_HEAP_SERIES auto init = []() { const char* hp_prefix; size_t hp_sz = sizeof(hp_prefix); mallctl("opt.prof_prefix", &hp_prefix, &hp_sz, NULL, 0); auto start = time_milli(); auto start_str = to_string( ( start - (start % 250) ) % 100000 ); return std::string(hp_prefix) + "." + start_str + ".0.t"; }; auto body = [](std::string& name, int i) { std::string heapName = name + to_string(i) + ".heap"; const char* hnPtr = heapName.c_str(); mallctl("prof.dump", NULL, 0, &hnPtr, sizeof(hnPtr)); }; heap_series_start(init, body); #endif #else std::cout << "jemallocStart: JEMALLOC is not defined. not starting." << std::endl; #endif return unit_t {}; }
void lookAndSay(string& num, int times){ if(times > 10){ return; } string newNum; int count = 1; char digit; if(num.size() == 1){ digit = num[0]; newNum.append(to_string(count)); newNum.push_back(digit); cout << newNum << endl; lookAndSay(newNum, ++times); return; } for(int i = 1; i < num.size(); ++i){ digit = num[i - 1]; if(num[i - 1] == num[i]){ count++ ; }else{ //digit = num[i - 1]; newNum.append(to_string(count)); newNum.push_back(digit); count = 1; } } digit = num.back(); newNum.append(to_string(count)); newNum.push_back(digit); cout << newNum << endl; lookAndSay(newNum, ++times); }
void cCodeGen::Visit(cFuncExprNode *node) { EmitString("*(int *)&Memory[Stack_Pointer] = Frame_Pointer;\n"); EmitString("Stack_Pointer += 4;\n"); // Push parameters onto stack if(node->GetParams() != nullptr) { for(int i = 0; i < node->GetParams()->NumChildren(); ++i) PushExpression(node->GetParams()->GetExpr(i)); EmitString("Frame_Pointer = Stack_Pointer;\n"); EmitString("Frame_Pointer -= " + to_string(node->GetFuncDecl()->GetParams()->GetSize()) + ";\n"); } else EmitString("Frame_Pointer = Stack_Pointer;\n"); EmitString(node->GetName() + "();\n"); if(node->GetParams() != nullptr) EmitString("Stack_Pointer -= " + to_string(node->GetFuncDecl()->GetParams()->GetSize()) + ";\n"); EmitString("Stack_Pointer -= 4;\n"); EmitString("Frame_Pointer = *(int *)&Memory[Stack_Pointer];\n"); }
void Pseudo3DCourse::Spec::saveProperties(const string& filename, const string& segmentsFilename) { Properties prop; prop.put("name", name); prop.put("author", author); prop.put("credits", credits); prop.put("comments", comments); prop.put("segment_file", segmentsFilename); prop.put("segment_length", to_string(roadSegmentLength)); prop.put("road_width", to_string(roadWidth)); prop.put("course_length", to_string(lines.size())); if(not landscapeFilename.empty()) prop.put("landscape_image", landscapeFilename); prop.put("landscape_color", colorLandscape.toRgbString()); prop.put("horizon_color", colorHorizon.toRgbString()); prop.put("road_color_primary", colorRoadPrimary.toRgbString()); prop.put("road_color_secondary", colorRoadSecondary.toRgbString()); prop.put("offroad_color_primary", colorOffRoadPrimary.toRgbString()); prop.put("offroad_color_secondary", colorOffRoadSecondary.toRgbString()); prop.put("humble_color_primary", colorHumblePrimary.toRgbString()); prop.put("humble_color_secondary", colorHumbleSecondary.toRgbString()); if(not musicFilename.empty()) prop.put("music", musicFilename); if(spritesFilenames.size() > DEFAULT_SPRITE_COUNT) prop.put("sprite_max_id", to_string(spritesFilenames.size()-1)); for(unsigned i = 0; i < spritesFilenames.size(); i++) prop.put("sprite"+to_string(i), spritesFilenames[i]); prop.store(filename); }
void cCodeGen::Visit(cVarExprNode *node) { if(node->GetType()->isFloat()) EmitString("*(double *)&Memory[Frame_Pointer + " + to_string(node->GetOffset()) + "]"); else if(node->GetSize() == 1) EmitString("Memory[Frame_Pointer + " + to_string(node->GetOffset()) + "]"); else EmitString("*(int *)&Memory[Frame_Pointer + " + to_string(node->GetOffset()) + "]"); }
/** * @brief This function will be called by the Bison parser to indicate an error. * * @param location This value specifies the location of the erroneous input. * @param message This value stores the error message emitted by the Bison * parser. * @param input This value stores the current input of the lexer/parser as text */ void Driver::error (const location_type & location, const string & message, string const & input) { numberOfErrors++; auto position = filename + ":" + to_string (location.begin.line) + ":" + to_string (location.begin.column) + ": "; auto indent = string (position.length (), ' '); errorMessage += "\n" + position + message + "\n"; errorMessage += visualizeError (location, input, indent); }
void Parser::ReportSyntaxError(string error) { if (current_token_ != nullptr) { cout << "ERRO de sintaxe na linha " + to_string(scanner.GetCurrentLine()) + " coluna " + to_string(scanner.GetCurrentColumn()) + ", ultimo token lido '" + current_token_->ToString() + "': " + error + "\n"; } else { cout << "ERRO de sintaxe na linha " + to_string(scanner.GetCurrentLine()) + " coluna " + to_string(scanner.GetCurrentColumn()) + ", ultimo token lido '" + tokens_.back()->ToString() + "': " + error + "\n"; } }
void send_data(int number, string data) { std::shared_ptr<string> message = std::make_shared<string>("DATA " + to_string(number) + " " + to_string(expected_datagram) + " " + to_string(get_free_space_size()) + "\n" + data); udp_socket.async_send_to(ba::buffer(*message), udp_endpoint, boost::bind(packet_sent, _1, _2, this, message)); }
OStream& operator<<(OStream&& os, tree<Nd> const& t) { using namespace hm3; using std::to_string; os << "digraph graphname {\n"; os << "concentrate=true\n"; const auto sibling_group_label = [](const siblings_idx sg) { return "g" + to_string(*sg); }; const auto sibling_label = [](const node_idx s) { return "s" + to_string(*s); }; const auto node_label = [=](const siblings_idx sg, const node_idx nIdx) { return sibling_group_label(sg) + ":" + sibling_label(nIdx); }; // write sibling groups: const auto last = t.no_children(); RANGES_FOR (auto s, t.sibling_groups()) { os << sibling_group_label(s); os << "[label=\""; os << "<gg" << *s << "> " << to_string(*s) << "* |"; auto c = 1; RANGES_FOR (auto&& n, t.nodes(s)) { os << "<" << sibling_label(n) << "> " << to_string(*n); if (n != 0_n and c != last) { os << "|"; } c++; }; os << "\", shape=record];\n"; }; // write links from parent->children RANGES_FOR (auto&& s, t.sibling_groups()) { RANGES_FOR (auto&& n, t.nodes(s)) { for (auto&& c : t.children(n)) { if (c) { os << node_label(s, n) << " -> " << node_label(t.sibling_group(c), c) << ";\n"; } } } } /// write links from sibling group - >parent for (auto&& s : t.sibling_groups()) { if (s == 0_sg) { continue; } const auto p = t.parent(s); const auto p_sg = t.sibling_group(p); os << sibling_group_label(s) << ":g" << sibling_group_label(s) << " -> " << node_label(p_sg, p) << ";\n"; } os << "}\n"; return os; }
string make_report() { string report = address + ":" + to_string(port) + " FIFO: " + to_string(queue.size()) + "/" + to_string(fifo_size) + " (min. " + to_string(min_fifo_size) + ", max. " + to_string(max_fifo_size) + ")\n"; min_fifo_size = max_fifo_size = queue.size(); return report; }
//Нарисовать вершину графа (кружок с текстом в нем) static void DrawVertex(float x, float y, int i, string s) { glColor3f(0.7, 0.7, 0.7); glBegin(GL_POLYGON); for (int i = 0; i < 16; ++i) { glVertex2f(vertexR * cosX[i] + x, vertexR * sinX[i] + y); } glEnd(); DrawString(x - fontWidth * s.length(), y + fontHeight * 2, s); DrawString(x - fontWidth * to_string(i).length(), y, to_string(i)); }
//Move moves the item with searchID to destIndex, // shifting the others along the way. //It determines the source index from the database. void QueueModel::move(const QString searchID, const int destIndex) { QSqlQuery query; query.exec("BEGIN TRANSACTION;"); //Get the source index. query.prepare("SELECT QTsortedIndex FROM QueueTable WHERE QTsearchID = ?;"); query.bindValue(0, searchID); query.exec(); query.next(); const int sourceIndex = query.value(0).toInt(); if (sourceIndex < destIndex) //Move one to the right, shift the rest leftward { std::string queryString = "UPDATE QueueTable SET QTsortedIndex = QTsortedIndex - 1 "; queryString.append("WHERE QTsortedIndex >= "); queryString.append(to_string(sourceIndex)); queryString.append(" AND QTsortedIndex <= "); queryString.append(to_string(destIndex)); queryString.append(";"); query.exec(QString::fromStdString(queryString)); query.prepare("UPDATE QueueTable " "SET QTsortedIndex = ? " "WHERE QTsearchID = ?;"); query.bindValue(0, destIndex); query.bindValue(1, searchID); query.exec(); } else if (sourceIndex > destIndex) //move one to the left, shift the rest rightward { std::string queryString = "UPDATE QueueTable SET QTsortedIndex = QTsortedIndex + 1 "; queryString.append("WHERE QTsortedIndex >= "); queryString.append(to_string(destIndex)); queryString.append(" AND QTsortedIndex <= "); queryString.append(to_string(sourceIndex)); queryString.append(";"); query.exec(QString::fromStdString(queryString)); query.prepare("UPDATE QueueTable " "SET QTsortedIndex = ? " "WHERE QTsearchID = ?;"); query.bindValue(0, destIndex); query.bindValue(1, searchID); query.exec(); } else { //Do nothing } query.exec("END TRANSACTION"); //Now tell the view to update all of the indices. //We update everything just for thoroughness's sake. emit dataChanged(createIndex(0,0),createIndex(rowCount(),columnCount())); }
int euler_solver<3>(string& solution) { constexpr long long test_val = 600851475143LL; long long curr_val = test_val; Prime my_prime; Cap<long long> capi([] (const long long &x) -> bool { return x <= sqrt(test_val); }); auto term = capi.wrap(my_prime); for (const auto &i : term) { if (divisible(curr_val, i)) { curr_val /= i; if (curr_val == 1LL) { curr_val = i; break; } } } solution = to_string(curr_val); return EulerStatus::SUCCESS; }
TsdbQueryConverter::TsdbQueryConverter(const std::string& prefix, InfoReader &info_reader, TimestampCalculator& timestamp_calculator) : info_reader(info_reader), timestamp_calculator(timestamp_calculator) { this->prefix = prefix; current_index = 0; for (std::string& s : info_reader.channel_labels) { string current_metric_label = boost::algorithm::to_lower_copy(s); unsigned int suffix = 0; if (contains(metrics, current_metric_label)) { while (contains(metrics, current_metric_label + to_string(suffix))) suffix++; metrics.push_back(current_metric_label + to_string(suffix)); } else { metrics.push_back(current_metric_label); } } }
BENCHMARK(BenchmarkTest, assign_istring) { for (istring s: SMALL_STRINGS) { for (std::size_t i = 0; i < NUM_ASSIGNS; ++i) { auto benchmark_name = "assign_istring," + to_string(s.size()) + "," + to_string(i+1); benchmark(benchmark_name, [&s,i]() { benchmark_string_copy(s, i+1); }); } } }
string fractionToDecimal(int numerator, int denominator) { if (numerator == 0) return "0"; if (denominator == 0) return string(); string result; if (numerator < 0 ^ denominator < 0) result.push_back('-'); long long num = numerator, den = denominator; num = num < 0 ? -num : num; den = den < 0 ? -den : den; result += to_string(num / den); num %= den; if (num) { result.push_back('.'); unordered_map<int, int> map; while (num) { if (map.find(num) != map.end()) { result.insert(result.begin() + map[num], '('); result.push_back(')'); break; } else { map[num] = result.size(); } num *= 10; result.push_back(num / den + '0'); num %= den; } } return result; }
void receive_upload(int number, string data) { active = true; if (number == expected_datagram) { load_data(data); expected_datagram++; } std::shared_ptr<string> message = std::make_shared<string>("ACK " + to_string(expected_datagram) + " " + to_string(get_free_space_size()) + "\n"); udp_socket.async_send_to(ba::buffer(*message), udp_endpoint, boost::bind(packet_sent, _1, _2, this, message)); }
Priority priority_from_string(const Glib::ustring& s) { if (s.compare(to_string(Priority::INVALID)) == 0) return Priority::INVALID; else if (s.empty()) return Priority::INVALID; else if (s.compare(to_string(Priority::LOW)) == 0) return Priority::LOW; else if (s.compare(to_string(Priority::MEDIUM)) == 0) return Priority::MEDIUM; else if (s.compare(to_string(Priority::HIGH)) == 0) return Priority::HIGH; else { std::cerr << "Error: Unknown Priority (" << s << ")" << std::endl; return Priority::INVALID; } }
std::string j_value::cast_to()const{ switch(M_type){ case j_value::Value_Types::LL_INTEGER: return to_string(M_val.llint_val); case j_value::Value_Types::DOUBLE: return to_string(M_val.dbl_val); case j_value::Value_Types::BOOL: return M_val.bool_val ? "true" : "false"; case j_value::Value_Types::STRING: return *M_val.str_val; case j_value::Value_Types::UNDEFINIED: throw J_Value_Error("Undefined Value type"); default: throw J_Value_Error("Could not convert type to string"); } }
vector<CategoryStats> DatabaseHelper::getYearStats(SortOrder sortOrder) { QSqlQuery query; query.exec("SELECT DISTINCT year FROM pl_paper"); vector<int> years; while (query.next()) { int year = query.value(0).toInt(); years.push_back(year); } vector<CategoryStats> stats(years.size()); for (vector<CategoryStats>::size_type i = 0; i < stats.size(); ++i) { query.prepare("SELECT COUNT(*) FROM pl_paper WHERE year = :year"); query.bindValue(":year", years[i]); query.exec(); query.last(); stats[i].setName(to_string(static_cast<long long>(years[i]))); stats[i].setCount(query.value(0).toInt()); } sortStats(stats, sortOrder); return stats; }
static void count_states_pos(const bool INCLUDE_CPGS, const string &chrom, const MappedRead &r, vector<size_t> &unconv, vector<size_t> &conv, vector<size_t> &err, size_t &hanging) { const size_t width = r.r.get_width(); const size_t offset = r.r.get_start(); size_t position = offset; if (chrom.length() < offset) // at least one bp of read on chr throw runtime_error("read mapped off chrom:\n" + r.tostring() + "\n" + to_string(chrom.length())); for (size_t i = 0; i < width; ++i, ++position) { if (position >= chrom.length()) // some overhang ++hanging; if (is_cytosine(chrom[position]) && (!is_guanine(chrom[position+1]) || position == chrom.length() || INCLUDE_CPGS)) { if (is_cytosine(r.seq[i])) ++unconv[i]; else if (is_thymine(r.seq[i])) ++conv[i]; else if (toupper(r.seq[i]) != 'N') ++err[i]; } } }
void fun_llvm_2_nts::create_basicblock_mapping() { unsigned int bb_id = 0; const auto & l = fun.getBasicBlockList(); for ( const auto & b : l ) { auto name = string ( "st_" ) + to_string ( bb_id ) + "_0"; auto st = new State ( std::move ( name ) ); st->insert_to ( bni.bn ); // I am not the owner of st anymore auto i = unique_ptr<StateInfo> ( new StateInfo ( *st, b ) ); i->bb_id = bb_id; i->inst_id = 0; funmap.ins_bb_start ( b, std::move ( i ) ); bb_id++; } // First basic block has initial state if ( l.size() != 0 ) { const BasicBlock * first = l.begin(); StateInfo & si = * funmap.bbinfo().find ( first )->getSecond(); si.st->is_initial() = true; } }
void FileSystem::filestat(arguments arg, outputStream out) { checkArgumentsCount(arg, 1); uint64_t descriptorId = std::stoll(arg.at(0)); FSDescriptor descriptor; try { descriptor = _descriptors.getDescriptor(descriptorId); } catch(const std::invalid_argument &) { out << "Bad descriptor\n"; return; } if(descriptor.type == DescriptorVariant::None) { out << "Descriptor does not exist\n"; return; } using std::to_string; out << "File statistic: \n\tid: " << descriptorId; if(descriptor.type == DescriptorVariant::File) { out << descriptor.fileSize; } out << "\n\tType: " << to_string(descriptor.type) << "\n\tReferences: " << descriptor.referencesCount << "\n\tHas extended blocks: " << (descriptor.nextDataSegment == Constants::HEADER_ADDRESS() ? "false" : "true") << "\n"; }
namespace detail { template<typename T> auto is_iterable_impl(int) -> decltype( begin(std::declval<T&>()) == end(std::declval<T&>()), *begin(std::declval<T&>()), ++begin(std::declval<T&>()), std::true_type{} ); template<typename T> std::false_type is_iterable_impl(...); /**Consider an object iterable, if the following are valid: * * - iterator = begin(T()) * - iterator = end(T()) * - iterator == iterator * - *iterator * - ++iterator * * The decltype will only be valid, resolving to std::true_type if the listed operations * are valid. */ template <typename T> struct is_iterable : public decltype(is_iterable_impl<T>(0)) {}; using std::to_string; template<typename T> auto has_to_string_impl(int) -> decltype(to_string(std::declval<T>())); template<typename T> std::false_type has_to_string_impl(...); /**to_string(T()) exists.*/ template<typename T> struct has_to_string : public decltype(has_to_string_impl<T>(0)) {}; }
void cCodeGen::Visit(cProgramNode *node) { EmitString("Stack_Pointer += " + to_string(node->GetBlock()->GetSize())); EmitSemicolon(); VisitAllChildren(node); }