bool RpcStringBinding::operator== (const RpcStringBinding& sb) const { const char* s1 = formatted (); const char* s2 = sb.formatted (); if (s1 && s2 && (strcmp (s1, s2) == 0)) return true; if ((s1 == 0) && (s2 == 0)) return true; return false; }
RawStr4::RawStr4(const char *ipath, int fileMode, bool caseSensitive) : caseSensitive(caseSensitive) { lastoff = -1; path = 0; stdstr(&path, ipath); if (fileMode == -1) { // try read/write if possible fileMode = FileMgr::RDWR; } idxfd = FileMgr::getSystemFileMgr()->open(formatted("%s.idx", path).c_str(), fileMode, true); datfd = FileMgr::getSystemFileMgr()->open(formatted("%s.dat", path).c_str(), fileMode, true); if (!datfd) { SWLog::getSystemLog()->logError("%d", errno); } instance++; }
std::string format_exception(exception_info const & ex_info) { bp::str formatted( bp::make_tuple( ex_info.type, ex_info.value, ex_info.traceback)); return bp::extract<std::string>(formatted); }
bool ErrorLogger::Verbose(const char* formatStr, ...) { QString formatted(""); va_list args; va_start(args, formatStr); formatted = formatted.vsprintf(formatStr, args); va_end(args); return Log(VERBOSE_DEBUG, formatted); }
bool ErrorLogger::Message(const char* formatStr, ...) { QString formatted(""); va_list args; va_start(args, formatStr); formatted = formatted.vsprintf(formatStr, args); va_end(args); return Log(MESSAGE, formatted); }
bool ErrorLogger::Warning(const char* formatStr, ...) { QString formatted(""); va_list args; va_start(args, formatStr); formatted = formatted.vsprintf(formatStr, args); va_end(args); return Log(WARNING, formatted); }
bool ErrorLogger::Log(ErrorLogger::Severity severity, const char* formatStr, ...) { QString formatted(""); va_list args; va_start(args, formatStr); formatted = formatted.vsprintf(formatStr, args); va_end(args); return Log(severity, formatted); }
bool ErrorLogger::NonFatal(const char* formatStr, ...) { QString formatted(""); va_list args; va_start(args, formatStr); formatted = formatted.vsprintf(formatStr, args); va_end(args); return Log(NONFATAL_ERROR, formatted); }
bool RpcStringBinding::operator< (const RpcStringBinding& sb) const { const char* s1 = formatted (); const char* s2 = sb.formatted (); if (s1 && s2) return (strcmp (s1, s2) < 0); if (s1 == 0) return false; return true; }
std::string WbFabricInterfaceImpl::execute(int connection_id, const std::string& query) { int error = 0; std::string output; if (_connections.find(connection_id) != _connections.end()) { error = mysql_query(&_connections[connection_id], query.c_str()); if (!error) { MYSQL_RES *result = mysql_store_result(&_connections[connection_id]); // Since output is created in JSON format, a single string record // contains all the needed data if (result) { MYSQL_ROW row = mysql_fetch_row(result); output = row[0]; mysql_free_result(result); } // If there are no results we need to check that it is correct to not // have any, else it means an error occurred else error = mysql_field_count(&_connections[connection_id]); } if (error != 0) { // Escape strings to create valid JSON structure std::string formatted(query); size_t index = 0; do { index = formatted.find("\"", index); if (index != std::string::npos) { formatted.insert(index, "\\"); index += 2; } } while (index != std::string::npos); output = base::strfmt("[[{\"message\":\"SQL Error executing %s: %d - %s\"}]]", formatted.c_str(), mysql_errno(&_connections[connection_id]), mysql_error(&_connections[connection_id])); } } else output = "[[{\"message\":\"Invalid Connection Id\"}]]"; return output; }
QString PaymentItem::getData(qint32 column) { switch (column) { case 0: return reference(); case 1: return QString::number(member()); case 2: return name(); case 3: return section(); case 4: return tr("%1 sFr.").arg(amountPaid(), 0, 'f', 2); case 5: return valuta().toString("yyyy-MM-dd"); case 6: return tr("%1 sFr.").arg(amount(), 0, 'f', 2); case 7: return payable().toString("yyyy-MM-dd"); case 8: return paidDue().toString("yyyy-MM-dd"); case 9: return tr("%1 sFr.").arg(amountPaidTotal(), 0, 'f', 2); default: return formatted(); } }
/** * Extract the exception error string from the python interpreter. * * This function assumes the gil is acquired. See \ref python_thread_guard. * * Code adapted from http://stackoverflow.com/questions/1418015/how-to-get-python-exception-text */ std::string parse_python_error() { PyObject *exc,*val,*tb; PyErr_Fetch(&exc,&val,&tb); PyErr_NormalizeException(&exc,&val,&tb); python::handle<> hexc(exc),hval(python::allow_null(val)),htb(python::allow_null(tb)); if(!hval) { return python::extract<std::string>(python::str(hexc)); } else { python::object traceback(python::import("traceback")); python::object format_exception(traceback.attr("format_exception")); python::object formatted_list(format_exception(hexc,hval,htb)); python::object formatted(python::str("").join(formatted_list)); return python::extract<std::string>(formatted); } }
int RpcStringBinding::format ( BSTR* bstr, bool includePortNumber ) const { USES_CONVERSION; const char* f = formatted (includePortNumber); if (f != 0) { OLECHAR * wStr = new OLECHAR [strlen (f) + 1]; comAsciiToWide (wStr, f, strlen (f) + 1); *bstr = ::SysAllocString (wStr); delete []wStr; } else *bstr = 0; return *bstr != 0 ? 0 : -1; }
TextDocument::TextDocument(IrcBuffer* buffer) : QTextDocument(buffer) { qRegisterMetaType<TextDocument*>(); d.uc = 0; d.dirty = -1; d.rebuild = -1; d.lowlight = -1; d.clone = false; d.batch = false; d.buffer = buffer; d.visible = false; d.formatter = new MessageFormatter(this); connect(d.formatter, SIGNAL(formatted(MessageData)), this, SLOT(append(MessageData))); d.formatter->setBuffer(buffer); setUndoRedoEnabled(false); setMaximumBlockCount(1000); connect(buffer->connection(), SIGNAL(disconnected()), this, SLOT(lowlight())); connect(buffer, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(receiveMessage(IrcMessage*))); }
bool TEIHTMLHREF::handleToken(std::string &buf, const char *token, BasicFilterUserData *userData) { // manually process if it wasn't a simple substitution if (!substituteToken(buf, token)) { MyUserData *u = (MyUserData *)userData; XMLTag tag(token); if (!strcmp(tag.getName(), "p")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { // non-empty start tag buf += "<!P><br />"; } else if (tag.isEndTag()) { // end tag buf += "<!/P><br />"; //userData->supressAdjacentWhitespace = true; } else { // empty paragraph break marker buf += "<!P><br />"; //userData->supressAdjacentWhitespace = true; } } // <hi> else if (!strcmp(tag.getName(), "hi")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { std::string rend = tag.getAttribute("rend"); u->lastHi = rend; if (rend == "italic" || rend == "ital") buf += "<i>"; else if (rend == "bold") buf += "<b>"; else if (rend == "super" || rend == "sup") buf += "<sup>"; else if (rend == "sub") buf += "<sub>"; else if (rend == "overline") buf += "<span style=\"text-decoration:overline\">"; } else if (tag.isEndTag()) { std::string rend = u->lastHi; if (rend == "italic" || rend == "ital") buf += "</i>"; else if (rend == "bold") buf += "</b>"; else if (rend == "super" || rend == "sup") buf += "</sup>"; else if (rend == "sub") buf += "</sub>"; else if (rend == "overline") buf += "</span>"; } } // <entryFree> else if (!strcmp(tag.getName(), "entryFree")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { std::string n = tag.getAttribute("n"); if (n != "") { buf += "<b>"; buf += n; buf += "</b>"; } } } // <sense> else if (!strcmp(tag.getName(), "sense")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { std::string n = tag.getAttribute("n"); if (n != "") { buf += "<br /><b>"; buf += n; buf += "</b>"; } } } // <div> else if (!strcmp(tag.getName(), "div")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { buf += "<!P>"; } else if (tag.isEndTag()) { } } // <lb.../> else if (!strcmp(tag.getName(), "lb")) { buf += "<br />"; } // <pos>, <gen>, <case>, <gram>, <number>, <mood>, <pron>, <def> else if (!strcmp(tag.getName(), "pos") || !strcmp(tag.getName(), "gen") || !strcmp(tag.getName(), "case") || !strcmp(tag.getName(), "gram") || !strcmp(tag.getName(), "number") || !strcmp(tag.getName(), "pron") /*|| !strcmp(tag.getName(), "def")*/) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { buf += "<i>"; } else if (tag.isEndTag()) { buf += "</i>"; } } // <tr> else if (!strcmp(tag.getName(), "tr")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { buf += "<i>"; } else if (tag.isEndTag()) { buf += "</i>"; } } // orth else if (!strcmp(tag.getName(), "orth")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { buf += "<b>"; } else if (tag.isEndTag()) { buf += "</b>"; } } // <etym>, <usg> else if (!strcmp(tag.getName(), "etym") || !strcmp(tag.getName(), "usg")) { // do nothing here } else if (!strcmp(tag.getName(), "ref")) { if (!tag.isEndTag()) { u->suspendTextPassThru = true; std::string target; std::string work; std::string ref; int was_osisref = false; if(!tag.getAttribute("osisRef").empty()) { target += tag.getAttribute("osisRef"); was_osisref=true; } else if(!tag.getAttribute("target").empty()) target += tag.getAttribute("target"); if(target.size()) { const char* the_ref = std::strchr(target.c_str(), ':'); if(!the_ref) { // No work ref = target; } else { // Compensate for starting : ref = the_ref + 1; int size = target.size() - ref.size() - 1; work.resize(size, '\0'); std::strncpy(&work[0u], target.c_str(), size); } if(was_osisref) { buf += formatted("<a href=\"passagestudy.jsp?action=showRef&type=scripRef&value=%s&module=%s\">", (!ref.empty()) ? URL::encode(ref.c_str()).c_str() : "", (!work.empty()) ? URL::encode(work.c_str()).c_str() : ""); } else { // Dictionary link, or something buf += formatted("<a href=\"sword://%s/%s\">", (!work.empty()) ? URL::encode(work.c_str()).c_str() : u->version.c_str(), (!ref.empty()) ? URL::encode(ref.c_str()).c_str() : "" ); } } else { //std::cout << "TARGET WASN'T\n"; } } else { buf += u->lastTextNode.c_str(); buf += "</a>"; u->suspendTextPassThru = false; } } // <note> tag else if (!strcmp(tag.getName(), "note")) { if (!tag.isEndTag()) { if (!tag.isEmpty()) { u->suspendTextPassThru = true; } } if (tag.isEndTag()) { std::string footnoteNumber = tag.getAttribute("swordFootnote"); std::string noteName = tag.getAttribute("n"); buf += formatted("<a href=\"passagestudy.jsp?action=showNote&type=n&value=%s&module=%s&passage=%s\"><small><sup class=\"n\">*n%s</sup></small></a>", URL::encode(footnoteNumber.c_str()).c_str(), URL::encode(u->version.c_str()).c_str(), URL::encode(u->key->getText()).c_str(), (renderNoteNumbers ? URL::encode(noteName.c_str()).c_str() : "")); u->suspendTextPassThru = false; } } // <graphic> image tag else if (!strcmp(tag.getName(), "graphic")) { auto url(tag.getAttribute("url")); if (!url.empty()) { // assert we have a url attribute std::string filepath; if (userData->module) { filepath = userData->module->getConfigEntry("AbsoluteDataPath"); if ((filepath.size()) && (filepath[filepath.size()-1] != '/') && (url[0] != '/')) filepath += '/'; } filepath += url; // images become clickable, if the UI supports showImage. buf += formatted("<a href=\"passagestudy.jsp?action=showImage&value=%s&module=%s\"><img src=\"file:%s\" border=\"0\" /></a>", URL::encode(filepath.c_str()).c_str(), URL::encode(u->version.c_str()).c_str(), filepath.c_str()); u->suspendTextPassThru = true; } } // <table> <row> <cell> else if (!strcmp(tag.getName(), "table")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { buf += "<table><tbody>\n"; } else if (tag.isEndTag()) { buf += "</tbody></table>\n"; u->supressAdjacentWhitespace = true; } } else if (!strcmp(tag.getName(), "row")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { buf += "\t<tr>"; } else if (tag.isEndTag()) { buf += "</tr>\n"; } } else if (!strcmp(tag.getName(), "cell")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { buf += "<td>"; } else if (tag.isEndTag()) { buf += "</td>"; } } else { return false; // we still didn't handle token } } return true; }
inline TCPConnection* TCPConnection_connect (CString host, uint16 port) { const int fd = socket(AF_INET, SOCK_STREAM, 0); report_zero_if(ERROR_MESSAGE("socket"), fd == -1); // Make it so that we can early-return from this scope using one-liners. struct Cleanup { explicit Cleanup (int fd) : ok(false), fd(fd) {} ~Cleanup () { return_if(ok); close(fd); } bool ok; int fd; } cleanup(fd); // FIXME: Use the IPv6-compliant getaddrinfo. struct hostent* ip = ::gethostbyname(host); report_zero_if(ERROR_MESSAGE("gethostbyname"), ip == NULL); sockaddr_in address; address.sin_family = AF_INET; memcpy(&address.sin_addr, ip->h_addr_list[0], ip->h_length); address.sin_port = htons(port); { // Put the socket into non-blocking mode. int flags = fcntl(fd, F_GETFL, 0); int status = fcntl(fd, F_SETFL, flags | O_NONBLOCK); report_zero_if(ERROR_MESSAGE("fcntl"), status < 0); } { // Perform the non-blocking connection dance. int status = 0; do { status = ::connect(fd, (sockaddr*) &address, sizeof(address)); } while (-1 == status && EINTR == errno); // In the extreme case where connect got interrupted by a signal. if (0 != status) // TCPConnection did not immediately succeed. { switch (errno) // Investigate the error, and take action. { case EINPROGRESS: // The connection is in progress. { static const int connectionTimeoutInMilliseconds = 500; // Poll the socket for writing, with a timeout. const int ret = select_single_write(fd, connectionTimeoutInMilliseconds); // Select might actually have returned EINPROGRESS, here. // Currently, we behave as if the connection failed when it times out. // FIXME: Introduce an asynchronous callback connection mechanism in parallel to this blocking one. // Abort if select failed. report_zero_unless(ERROR_MESSAGE("select"), 0 < ret); // Also abort if select returned with a descriptor not ready for writing. report_zero_if("Connection timed out.", 0 == ret); // Make sure that the connection is error-free. int err = 0; socklen_t len = sizeof(int); report_zero_unless(ERROR_MESSAGE("getsockopt"), 0 == getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len)); report_zero_unless(formatted("connect: %s", strerror(err)).get(), 0 == err); break; // The connection is now established. } default: // The connection failed for other reasons. { uplink_log_error(ERROR_MESSAGE("connect")); return 0; } } } } { // Put the socket back into blocking mode. int flags = fcntl(fd, F_GETFL, 0); int status = fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); report_zero_if(ERROR_MESSAGE("fcntl"), status < 0); } cleanup.ok = true; return TCPConnection_create(fd); }
bool OSISWEBIF::handleToken(std::string &buf, const char *token, BasicFilterUserData *userData) { MyUserData *u = (MyUserData *)userData; std::string scratch; bool sub = (u->suspendTextPassThru) ? substituteToken(scratch, token) : substituteToken(buf, token); if (!sub) { // manually process if it wasn't a simple substitution XMLTag tag(token); // <w> tag if (!strcmp(tag.getName(), "w")) { // start <w> tag if ((!tag.isEmpty()) && (!tag.isEndTag())) { u->w = token; } // end or empty <w> tag else { bool endTag = tag.isEndTag(); std::string lastText; bool show = true; // to handle unplaced article in kjv2003-- temporary till combined if (endTag) { tag = u->w.c_str(); lastText = u->lastTextNode.c_str(); } else lastText = "stuff"; std::string attrib; const char *val; if (!(attrib = tag.getAttribute("xlit")).empty()) { val = strchr(attrib.c_str(), ':'); val = (val) ? (val + 1) : attrib.c_str(); // buf += formatted(" %s", val); } if (!(attrib = tag.getAttribute("gloss")).empty()) { val = strchr(attrib.c_str(), ':'); val = (val) ? (val + 1) : attrib.c_str(); // buf += formatted(" %s", val); } if (!(attrib = tag.getAttribute("lemma")).empty()) { int count = tag.getAttributePartCount("lemma", ' '); int i = (count > 1) ? 0 : -1; // -1 for whole value cuz it's faster, but does the same thing as 0 do { attrib = tag.getAttribute("lemma", i, ' '); if (i < 0) i = 0; // to handle our -1 condition val = strchr(attrib.c_str(), ':'); val = (val) ? (val + 1) : attrib.c_str(); const char *val2 = val; if ((strchr("GH", *val)) && (isdigit(val[1]))) val2++; if ((!strcmp(val2, "3588")) && (lastText.length() < 1)) show = false; else buf += formatted(" <small><em><<a href=\"%s?showStrong=%s#cv\">%s</a>></em></small> ", passageStudyURL.c_str(), URL::encode(val2).c_str(), val2); } while (++i < count); } if (!(attrib = tag.getAttribute("morph")).empty() && (show)) { std::string savelemma = tag.getAttribute("savlm"); if ((strstr(savelemma.c_str(), "3588")) && (lastText.length() < 1)) show = false; if (show) { int count = tag.getAttributePartCount("morph", ' '); int i = (count > 1) ? 0 : -1; // -1 for whole value cuz it's faster, but does the same thing as 0 do { attrib = tag.getAttribute("morph", i, ' '); if (i < 0) i = 0; // to handle our -1 condition val = strchr(attrib.c_str(), ':'); val = (val) ? (val + 1) : attrib.c_str(); const char *val2 = val; if ((*val == 'T') && (strchr("GH", val[1])) && (isdigit(val[2]))) val2+=2; buf += formatted(" <small><em>(<a href=\"%s?showMorph=%s#cv\">%s</a>)</em></small> ", passageStudyURL.c_str(), URL::encode(val2).c_str(), val2); } while (++i < count); } } if (!(attrib = tag.getAttribute("POS")).empty()) { val = strchr(attrib.c_str(), ':'); val = (val) ? (val + 1) : attrib.c_str(); buf += formatted(" %s", val); } /*if (endTag) buf += "}";*/ } } // <note> tag else if (!strcmp(tag.getName(), "note")) { if (!tag.isEndTag()) { std::string type = tag.getAttribute("type"); bool strongsMarkup = (type == "x-strongsMarkup" || type == "strongsMarkup"); // the latter is deprecated if (strongsMarkup) { tag.setEmpty(false); // handle bug in KJV2003 module where some note open tags were <note ... /> } if (!tag.isEmpty()) { if (!strongsMarkup) { // leave strong's markup notes out, in the future we'll probably have different option filters to turn different note types on or off std::string footnoteNumber = tag.getAttribute("swordFootnote"); std::string modName = (u->module) ? u->module->getName() : ""; if (dynamic_cast<VerseKey const *>(u->key)) { char ch = ((!tag.getAttribute("type").empty() && ((!strcmp(tag.getAttribute("type").c_str(), "crossReference")) || (!strcmp(tag.getAttribute("type").c_str(), "x-cross-ref")))) ? 'x':'n'); // buf += formatted("<a href=\"noteID=%s.%c.%s\"><small><sup>*%c</sup></small></a> ", vkey->getText(), ch, footnoteNumber.c_str(), ch); buf += formatted("<span class=\"fn\" onclick=\"f(\'%s\',\'%s\',\'%s\');\" >%c</span>", modName.c_str(), u->key->getText(), footnoteNumber.c_str(), ch); } } u->suspendTextPassThru = (++u->suspendLevel); } } if (tag.isEndTag()) { u->suspendTextPassThru = (--u->suspendLevel); } } // handled appropriately in base class else { return OSISXHTML::handleToken(buf, token, userData); } } return true; }
void Value::saveToFile(const std::string& filename) const { std::ofstream out(filename); out << formatted(); }
// Builds the option list from the data source. void ElementFormControlDataSelect::BuildOptions() { widget->ClearOptions(); if (data_source == NULL) return; // Store the old selection value and index. These will be used to restore the selection to the // most appropriate option after the options have been rebuilt. Rocket::Core::String old_value = GetValue(); int old_selection = GetSelection(); Rocket::Core::String fields_attribute = GetAttribute<Rocket::Core::String>("fields", ""); Rocket::Core::String valuefield_attribute = GetAttribute<Rocket::Core::String>("valuefield", ""); Rocket::Core::String data_formatter_attribute = GetAttribute<Rocket::Core::String>("formatter", ""); DataFormatter* data_formatter = NULL; // Process the attributes. if (fields_attribute.Empty()) { Core::Log::Message(Rocket::Core::Log::LT_ERROR, "DataQuery failed, no fields specified for %s.", GetTagName().CString()); return; } if (valuefield_attribute.Empty()) { valuefield_attribute = fields_attribute.Substring(0, fields_attribute.Find(",")); } if (!data_formatter_attribute.Empty()) { data_formatter = DataFormatter::GetDataFormatter(data_formatter_attribute); if (!data_formatter) Core::Log::Message(Rocket::Core::Log::LT_WARNING, "Unable to find data formatter named '%s', formatting skipped.", data_formatter_attribute.CString()); } // Build a list of attributes Rocket::Core::String fields(valuefield_attribute); fields += ","; fields += fields_attribute; DataQuery query(data_source, data_table, fields); while (query.NextRow()) { Rocket::Core::StringList fields; Rocket::Core::String value = query.Get<Rocket::Core::String>(0, ""); for (size_t i = 1; i < query.GetNumFields(); ++i) fields.push_back(query.Get< Rocket::Core::String>(i, "")); Rocket::Core::String formatted(""); if (fields.size() > 0) formatted = fields[0]; if (data_formatter) data_formatter->FormatData(formatted, fields); // Add the data as an option. widget->AddOption(formatted, value, -1, false); } // If an option was selected before, attempt to restore the selection to it. if (old_selection > -1) { // Try to find a selection with the same value as the previous one. for (int i = 0; i < GetNumOptions(); ++i) { SelectOption* option = GetOption(i); if (option->GetValue() == old_value) { widget->SetSelection(i, true); return; } } // Failed to find an option with the same value. Attempt to at least set the same index. int new_selection = Rocket::Core::Math::Clamp(old_selection, 0, GetNumOptions() - 1); if (GetNumOptions() == 0) new_selection = -1; widget->SetSelection(new_selection, true); } }
bool TEILaTeX::handleToken(std::string &buf, const char *token, BasicFilterUserData *userData) { // manually process if it wasn't a simple substitution if (!substituteToken(buf, token)) { MyUserData *u = (MyUserData *)userData; XMLTag tag(token); if (!strcmp(tag.getName(), "p")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { // non-empty start tag buf += ""; } else if (tag.isEndTag()) { // end tag buf += "//\n"; //userData->supressAdjacentWhitespace = true; } else { // empty paragraph break marker buf += "//\n"; //userData->supressAdjacentWhitespace = true; } } // <hi> else if (!strcmp(tag.getName(), "hi")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { std::string rend = tag.getAttribute("rend"); u->lastHi = rend; if (rend == "italic" || rend == "ital") buf += "\\it{"; else if (rend == "bold") buf += "\\bd{"; else if (rend == "super" || rend == "sup") buf += "^{"; else if (rend == "sub") buf += "_{"; else if (rend == "overline") buf += "\\overline{"; } else if (tag.isEndTag()) { buf += "}"; } } // <entryFree> else if (!strcmp(tag.getName(), "entryFree")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { std::string n = tag.getAttribute("n"); if (n != "") { buf += "\\teiEntryFree{"; buf += n; buf += "}"; } } } // <sense> else if (!strcmp(tag.getName(), "sense")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { std::string n = tag.getAttribute("n"); if (n != "") { buf += "\n\\teiSense{"; buf += n; buf += "}"; } } } // <div> else if (!strcmp(tag.getName(), "div")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { buf += ""; } else if (tag.isEndTag()) { } } // <lb.../> else if (!strcmp(tag.getName(), "lb")) { buf += "//\n"; } // <pos>, <gen>, <case>, <gram>, <number>, <mood>, <pron>, <def> else if (!strcmp(tag.getName(), "pos") || !strcmp(tag.getName(), "gen") || !strcmp(tag.getName(), "case") || !strcmp(tag.getName(), "gram") || !strcmp(tag.getName(), "number") || !strcmp(tag.getName(), "pron") || !strcmp(tag.getName(), "tr") || !strcmp(tag.getName(), "orth") || !strcmp(tag.getName(), "etym") || !strcmp(tag.getName(), "usg") || !strcmp(tag.getName(), "def")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { buf += "\\tei"; buf += tag.getName(); buf += "{"; } else if (tag.isEndTag()) { buf += "}"; } } else if (!strcmp(tag.getName(), "ref")) { if (!tag.isEndTag()) { u->suspendTextPassThru = true; std::string target; std::string work; std::string ref; int was_osisref = false; if(!tag.getAttribute("osisRef").empty()) { target += tag.getAttribute("osisRef"); was_osisref=true; } else if(!tag.getAttribute("target").empty()) target += tag.getAttribute("target"); if(target.size()) { const char* the_ref = std::strchr(target.c_str(), ':'); if(!the_ref) { // No work ref = target; } else { // Compensate for starting : ref = the_ref + 1; int size = target.size() - ref.size() - 1; work.resize(size, '\0'); strncpy(&work[0u], target.c_str(), size); } if(was_osisref) { buf += formatted("\\swordref{%s}{%s}{", ref.c_str(), work.c_str()); } else { // Dictionary link, or something buf += formatted("\\sworddictref{%s}{%s}{", (!work.empty()) ? work.c_str() : u->version.c_str(), ref.c_str() ); } } else { //std::cout << "TARGET WASN'T\n"; } } else { buf += u->lastTextNode.c_str(); buf += "}"; u->suspendTextPassThru = false; } } // <note> tag else if (!strcmp(tag.getName(), "note")) { if (!tag.isEndTag()) { if (!tag.isEmpty()) { u->suspendTextPassThru = true; } } if (tag.isEndTag()) { std::string footnoteNumber = tag.getAttribute("swordFootnote"); std::string noteName = tag.getAttribute("n"); std::string footnoteBody = ""; if (u->module){ footnoteBody += u->module->getEntryAttributes()["Footnote"][footnoteNumber]["body"]; } buf += formatted("\\swordfootnote{%s}{%s}{%s}{%s}{", footnoteNumber.c_str(), u->version.c_str(), u->key->getText(), renderNoteNumbers ? noteName.c_str() : ""); if (u->module) { buf += u->module->renderText(footnoteBody.c_str()).c_str(); } u->suspendTextPassThru = false; } } // <graphic> image tag else if (!strcmp(tag.getName(), "graphic")) { auto url(tag.getAttribute("url")); if (!url.empty()) { // assert we have a url attribute std::string filepath; if (userData->module) { filepath = userData->module->getConfigEntry("AbsoluteDataPath"); if ((filepath.size()) && (filepath[filepath.size()-1] != '/') && (url[0] != '/')) filepath += '/'; } filepath += url; buf += formatted("\\figure{\\includegraphics{%s}}", filepath.c_str()); u->suspendTextPassThru = false; } } // <table> <row> <cell> else if (!strcmp(tag.getName(), "table")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { buf += "\n\\begin{tabular}"; } else if (tag.isEndTag()) { buf += "\n\\end{tabular}"; ++u->consecutiveNewlines; u->supressAdjacentWhitespace = true; } } else if (!strcmp(tag.getName(), "row")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { buf += "\n"; u->firstCell = true; } else if (tag.isEndTag()) { buf += "//"; u->firstCell = false; } } else if (!strcmp(tag.getName(), "cell")) { if ((!tag.isEndTag()) && (!tag.isEmpty())) { if (u->firstCell == false) { buf += " & "; } else { u->firstCell = false; } } else if (tag.isEndTag()) { buf += ""; } } else { return false; // we still didn't handle token } } return true; }
char OSISWordJS::processText(std::string &text, const SWKey *key, const SWModule *module) { if (option) { char token[2112]; // cheese. Fix. int tokpos = 0; bool intoken = false; int wordNum = 1; char wordstr[5]; std::string modName = (module)?module->getName():""; // add TR to w src in KJV then remove this next line std::string wordSrcPrefix = (modName == "KJV")?std::string("TR"):modName; VerseKey const * vkey = 0; if (key) { vkey = dynamic_cast<VerseKey const *>(key); } const std::string orig = text; const char * from = orig.c_str(); for (text = ""; *from; ++from) { if (*from == '<') { intoken = true; tokpos = 0; token[0] = 0; token[1] = 0; token[2] = 0; continue; } if (*from == '>') { // process tokens intoken = false; if ((*token == 'w') && (token[1] == ' ')) { // Word XMLTag wtag(token); sprintf(wordstr, "%03d", wordNum); std::string lemmaClass; std::string lemma; std::string morph; std::string page; std::string src; char gh = 0; page = module->getEntryAttributes()["Word"][wordstr]["Page"].c_str(); if (page.length()) page = (std::string)"p:" + page; int count = atoi(module->getEntryAttributes()["Word"][wordstr]["PartCount"].c_str()); for (int i = 0; i < count; i++) { // for now, lemma class can just be equal to last lemma class in multi part word std::string tmp = "LemmaClass"; if (count > 1) tmp += formatted(".%d", i+1); lemmaClass = module->getEntryAttributes()["Word"][wordstr][tmp]; tmp = "Lemma"; if (count > 1) tmp += formatted(".%d", i+1); tmp = (module->getEntryAttributes()["Word"][wordstr][tmp].c_str()); // if we're strongs, if (lemmaClass == "strong") { gh = tmp[0]; tmp.erase(0u, 1u); } if (lemma.size()) lemma += "|"; lemma += tmp; tmp = "Morph"; if (count > 1) tmp += formatted(".%d", i+1); tmp = (module->getEntryAttributes()["Word"][wordstr][tmp].c_str()); if (morph.size()) morph += "|"; morph += tmp; tmp = "Src"; if (count > 1) tmp += formatted(".%d", i+1); tmp = (module->getEntryAttributes()["Word"][wordstr][tmp].c_str()); if (!tmp.length()) tmp += formatted("%d", wordNum); tmp.insert(0, wordSrcPrefix); if (src.size()) src += "|"; src += tmp; } std::string lexName = ""; // we can pass the real lex name in, but we have some // aliases in the javascript to optimize bandwidth if ((gh == 'G') && (defaultGreekLex)) { lexName = (!strcmp(defaultGreekLex->getName(), "StrongsGreek"))?"G":defaultGreekLex->getName(); } else if ((gh == 'H') && (defaultHebLex)) { lexName = (!strcmp(defaultHebLex->getName(), "StrongsHebrew"))?"H":defaultHebLex->getName(); } std::string xlit = wtag.getAttribute("xlit"); if ((lemmaClass != "strong") && (hasPrefix(xlit, "betacode:"))) { lexName = "betacode"; // const char *m = strchr(xlit.c_str(), ':'); // strong = ++m; } std::string wordID; if (vkey) { // optimize for bandwidth and use only the verse as the unique entry id wordID += formatted("%d", vkey->getVerse()); } else { wordID = key->getText(); } wordID += formatted("_%s", src.c_str()); // clean up our word ID for XHTML for (unsigned int i = 0; i < wordID.size(); i++) { if ((!isdigit(wordID[i])) && (!isalpha(wordID[i]))) { wordID[i] = '_'; } } // 'p' = 'fillpop' to save bandwidth text += formatted("<span class=\"clk\" onclick=\"p('%s','%s','%s','%s','%s','%s');\" >", lexName.c_str(), lemma.c_str(), wordID.c_str(), morph.c_str(), page.c_str(), modName.c_str()); wordNum++; if (wtag.isEmpty()) { text += "</w></span>"; } } if ((*token == '/') && (token[1] == 'w') && option) { // Word text += "</w></span>"; continue; } // if not a strongs token, keep token in text text.push_back('<'); text.append(token); text.push_back('>'); continue; } if (intoken) { if (tokpos < 2045) { token[tokpos++] = *from; token[tokpos+2] = 0; } } else { text.push_back(*from); } } } return 0; }
void GVSearchListBox::DrawVia(LPDRAWITEMSTRUCT lpdis) { if (m_findMessages.size() > 0 && m_findMessages.size() >= lpdis->itemID) { RECT rect(lpdis->rcItem); HDC hdc = lpdis->hDC; LOGFONT lFont; std::memset(&lFont, 0, sizeof(LOGFONT)); lFont.lfHeight = 14; lFont.lfWeight = FW_NORMAL; lstrcpy(lFont.lfFaceName, L"Sans Droid"); HFONT font = CreateFontIndirect(&lFont); SelectObject(hdc, font); if (lpdis->itemState & ODS_SELECTED) { SetTextColor(hdc, RGB(128, 128, 128)); } else { SetTextColor(hdc, RGB(128, 128, 128)); } SetBkMode(hdc, TRANSPARENT); auto u = m_findMessages[lpdis->itemID].pairs[L"u"]; if (u.size() > 0) { auto profile = GVProfileCache::SharedInstance().Find(u); auto f = profile[L"f"]; auto __t = atol(Utility::ws2s(m_findMessages[lpdis->itemID].pairs[L"__t"]).c_str()); auto time = std::time(0) - __t; BOOL isSecs = FALSE, isMins = FALSE, isHours = FALSE, isExpired = FALSE; if (time > 60 * 60 * 72) { isExpired = TRUE; } else if (time > 60 * 60) { isHours = TRUE; time = time / 60 / 60; } else if (time > 60) { isMins = TRUE; time = time / 60; } else { isSecs = TRUE; } time = max(1, time); std::wstring timeFormat; if (isSecs) { timeFormat = L"seconds"; } else if (isMins) { timeFormat = L"minutes"; } else if (isHours) { timeFormat = L"hours"; } std::wstring formatted( std::to_wstring(time) + + L" " + timeFormat + L" ago via " + (f.size() > 0 ? f : u) ); enum { text_padding_right = 12 }; RECT dest(rect); dest.left += 56; dest.top = rect.bottom - 28; dest.right -= text_padding_right; DrawText(hdc, formatted.c_str(), formatted.size(), &dest, DT_WORDBREAK); } DeleteObject(font); } }
// Format the current Python exception as a string. // Let Python do the work for us; call traceback.format_exception() std::string formatPythonException() { if (!PyErr_Occurred()) { return "<no error?>"; } // Retrieve Python exception and "normalize" (the docs are unclear but // they say you should do it :) ) PyObject* exceptionObj; PyObject* valueObj; PyObject* tracebackObj; PyErr_Fetch(&exceptionObj, &valueObj, &tracebackObj); DCHECK(exceptionObj); PyErr_NormalizeException(&exceptionObj, &valueObj, &tracebackObj); PyObjectHandle exception(exceptionObj); PyObjectHandle value(valueObj); PyObjectHandle traceback(tracebackObj); // value and traceback may be null if (!value) { value.reset(PyObjectHandle::INCREF, Py_None); } if (!traceback) { traceback.reset(PyObjectHandle::INCREF, Py_None); } PyObjectHandle tbModule(PyImport_ImportModule("traceback")); if (!tbModule) { return "<import traceback failed>"; } PyObject* tbDict = PyModule_GetDict(tbModule.get()); // borrowed if (!tbDict) { return "<no dict in traceback module>"; } // borrowed PyObject* formatFunc = PyDict_GetItemString(tbDict, "format_exception"); if (!formatFunc) { return "<no format_exception in traceback module>"; } PyObjectHandle formatted(PyObject_CallFunction( formatFunc, const_cast<char*>("OOO"), exception.get(), value.get(), traceback.get())); if (!formatted) { return "<traceback.format_exception error>"; } // format_exception returns a list of strings that should be concatenated. // Well then, let's do that. if (!PyList_Check(formatted.get())) { return "<traceback.format_exception didn't return a list>"; } std::string out; for (Py_ssize_t i = 0; i < PyList_GET_SIZE(formatted.get()); ++i) { PyObject* obj = PyList_GET_ITEM(formatted.get(), i); // borrowed char* data; Py_ssize_t len; if (PyString_AsStringAndSize(obj, &data, &len) == -1) { return "<traceback.format_exception member not a string>"; } out.append(data, len); } return out; }
void Notification::setValues(const QString &application, const QString &summary, const QString &body, const QString &icon, int timeout, const QStringList& actions, const QVariantMap& hints) { // Basic properties ********************* // Notifications spec set real order here: // An implementation which only displays one image or icon must // choose which one to display using the following order: // - "image-data" // - "image-path" // - app_icon parameter // - for compatibility reason, "icon_data" if (!hints[QL1S("image_data")].isNull()) { m_pixmap = getPixmapFromHint(hints[QL1S("image_data")]); } else if (!hints[QL1S("image_path")].isNull()) { m_pixmap = getPixmapFromString(hints[QL1S("image_path")].toString()); } else if (!icon.isEmpty()) { m_pixmap = getPixmapFromString(icon); } else if (!hints[QL1S("icon_data")].isNull()) { m_pixmap = getPixmapFromHint(hints[QL1S("icon_data")]); } // issue #325: Do not display icon if it's not found... if (m_pixmap.isNull()) { iconLabel->hide(); } else { if (m_pixmap.size().width() > ICONSIZE.width() || m_pixmap.size().height() > ICONSIZE.height()) { m_pixmap = m_pixmap.scaled(ICONSIZE, Qt::KeepAspectRatio, Qt::SmoothTransformation); } iconLabel->setPixmap(m_pixmap); iconLabel->show(); } //XXX: workaround to properly set text labels widths (for correct sizeHints after setText) adjustSize(); // application appLabel->setVisible(!application.isEmpty()); appLabel->setFixedWidth(appLabel->width()); appLabel->setText(application); // summary summaryLabel->setVisible(!summary.isEmpty() && application != summary); summaryLabel->setFixedWidth(summaryLabel->width()); summaryLabel->setText(summary); // body bodyLabel->setVisible(!body.isEmpty()); bodyLabel->setFixedWidth(bodyLabel->width()); //https://developer.gnome.org/notification-spec //Body - This is a multi-line body of text. Each line is a paragraph, server implementations are free to word wrap them as they see fit. //XXX: remove all unsupported tags?!? (supported <b>, <i>, <u>, <a>, <img>) QString formatted(body); bodyLabel->setText(formatted.replace(QL1C('\n'), QStringLiteral("<br/>"))); // Timeout // Special values: // < 0: server decides timeout // 0: infifite if (m_timer) { m_timer->stop(); m_timer->deleteLater(); } // -1 for server decides is handled in notifyd to save QSettings instance if (timeout > 0) { m_timer = new NotificationTimer(this); connect(m_timer, &NotificationTimer::timeout, this, &Notification::timeout); m_timer->start(timeout); } // Categories ********************* if (!hints[QL1S("category")].isNull()) { // TODO/FIXME: Categories - how to handle it? } // Urgency Levels ********************* // Type Description // 0 Low // 1 Normal // 2 Critical if (!hints[QL1S("urgency")].isNull()) { // TODO/FIXME: Urgencies - how to handle it? } // Actions if (actions.count() && m_actionWidget == 0) { if (actions.count()/2 < 4) m_actionWidget = new NotificationActionsButtonsWidget(actions, this); else m_actionWidget = new NotificationActionsComboWidget(actions, this); connect(m_actionWidget, &NotificationActionsWidget::actionTriggered, this, &Notification::actionTriggered); actionsLayout->addWidget(m_actionWidget); m_actionWidget->show(); } adjustSize(); // ensure layout expansion setMinimumHeight(qMax(rect().height(), childrenRect().height())); }