//=========================================================================== int main () { { //------------------------------------------------------ // SETUP FIXTURE // TEST String str(X); // VERIFY assert(str == YYY); } { //------------------------------------------------------ // SETUP FIXTURE // TEST String str(X); // VERIFY assert(str == YYY); } { //------------------------------------------------------ // SETUP FIXTURE // TEST String str(X); // VERIFY assert(str == YYY); } { //------------------------------------------------------ // SETUP FIXTURE // TEST String str(X); // VERIFY assert(str == YYY); } { //------------------------------------------------------ // SETUP FIXTURE // TEST String str(X); // VERIFY assert(str == YYY); } // ADD ADDITIONAL TESTS AS NECESSARY std::cout << "Done testing XXX." << std::endl; }
void Command::smg(std::string cmd, GameEngine *game) { (void) game; std::string str(cmd.begin() + 4, cmd.end()); }
ctConfigItem* ctFindReplaceDialog::FindNextItem(ctConfigToolDoc* doc, ctConfigItem* item, const wxString& text, bool matchCase, bool matchWordOnly, bool wrap, bool skipFirst) { ctConfigItem* firstInDoc = NULL; wxString text2(text); if (!matchCase) text2.MakeLower(); ctConfigItem* found = NULL; ctConfigItem* next = item; int i = 0; do { // If starting the search from beginning, we can now // set the value of 'item' in the 2nd iteration without immediately // dropping out of the while loop because card == next if (!item && (i > 0)) item = firstInDoc; // We might want to start from this item if skipFirst is false. if ((i == 0) && !skipFirst && next) { } else next = doc->FindNextItem(next, wrap); // Save to be used in iteration 2 if ((i == 0) && !item) firstInDoc = next; if (next) { wxString str(next->GetName()); wxString description(next->GetPropertyString(wxT("description"))); wxString notes(next->GetPropertyString(wxT("notes"))); if (!matchCase) { str.MakeLower(); description.MakeLower(); notes.MakeLower(); } if (ctMatchString(str, text2, matchWordOnly) || ctMatchString(description, text2, matchWordOnly) || ctMatchString(notes, text2, matchWordOnly)) { found = next; } } else break; // Didn't find an item at all i ++; } while (!found && item != next); if (item == found && !firstInDoc) return NULL; else return found; }
int main(int argc, char* argv[]) { if(argc < 2) { usage(); return -1; } { int result; while((result=getopt(argc,argv,"shi:o:n:d:f:g:"))!=-1){ std::istringstream is; if(optarg) { std::string str(optarg); is.str(str); } switch(result){ case 'i': is >> input_img; break; case 'o': is >> output_img; break; case 'n': is >> iteration; CV_Assert((iteration > 0) && (iteration <= 8)); break; case 'd': is >> decay_factor; CV_Assert(decay_factor >= 1.0); break; case 'f': is >> decay_offset; CV_Assert(decay_offset >= 0.); break; case 'g': is >> gamma; CV_Assert(gamma > 0.); break; case 's': std::cout << "opt:s" << std::endl; show_result = true; break; case 'h': default: usage(); return -1; } } } { std::cout << "Settings..." << std::endl; std::cout << "Input image=" << input_img << std::endl; std::cout << "Output image=" << output_img << std::endl; std::cout << "Iteration=" << iteration << std::endl; std::cout << "Decay factor=" << decay_factor << std::endl; std::cout << "Decay offset=" << decay_offset << std::endl; std::cout << "Gamma=" << gamma << std::endl; std::cout << "Show result=" << show_result << std::endl << std::endl; } cv::Mat src_img = cv::imread(input_img); //argv[1]); if(src_img.empty()) { std::cout << input_img << " does not exist." << std::endl; return -1; } cv::Mat dst_img; soft_filter(src_img,dst_img,iteration,decay_factor,decay_offset,gamma); cv::imwrite(output_img, dst_img); if(show_result) { cv::namedWindow("original", cv::WINDOW_NORMAL); cv::imshow("original", src_img); cv::namedWindow("result", cv::WINDOW_NORMAL); cv::imshow("result", dst_img); cv::waitKey(0); } return 0; }
int main() { std::string str( `\`` ) ; }
const pstring param_model_t::type() { return state().setup().models().type(str()); }
nl_double param_model_t::value(const pstring &entity) { return state().setup().models().value(str(), entity); }
int main (int argc, char ** argv){ //------------------------------------------------ //Defines some constants bool specificKeyword = false; bool allowSpikes = false; bool findVolumeError = false; bool integrationTest = false; bool regressionTest = true; bool allowDifferentAmountOfKeywords = true; bool printKeywords = false; bool printSpecificKeyword = false; bool findVectorWithGreatestErrorRatio = false; bool oneOfTheMainVariables = false; bool throwExceptionForTooGreatErrorRatio = true; bool isRestartFile = false; bool throwOnError = true; bool analysis = false; const char* keyword = nullptr; const char* mainVariable = nullptr; int c = 0; int limit = -1; //------------------------------------------------ //------------------------------------------------ //For setting the options selected while ((c = getopt(argc, argv, "dghik:Km:napP:rRs:vV:")) != -1) { switch (c) { case 'a': analysis = true; break; case 'd': throwExceptionForTooGreatErrorRatio = false; break; case 'g': findVectorWithGreatestErrorRatio = true; throwExceptionForTooGreatErrorRatio = false; break; case 'h': printHelp(); return 0; case 'i': integrationTest = true; regressionTest = false; break; case 'k': specificKeyword = true; keyword = optarg; break; case 'K': allowDifferentAmountOfKeywords = false; break; case 'm': oneOfTheMainVariables = true; mainVariable = optarg; break; case 'n': throwOnError = false; break; case 'p': printKeywords = true; break; case 'P': specificKeyword = true; printSpecificKeyword = true; keyword = optarg; break; case 'r': integrationTest = false; regressionTest = true; break; case 'R': isRestartFile = true; break; case 's': allowSpikes = true; limit = atof(optarg); break; case 'v': findVolumeError = true; break; case 'V': findVolumeError = true; specificKeyword = true; keyword = optarg; break; case '?': if (optopt == 'k' || optopt == 'm' || optopt == 'P' || optopt == 's' || optopt == 'V') { std::cout << "Option -"<<optopt<<" requires an keyword." << std::endl; return EXIT_FAILURE; } else { std::cout << "Unknown option." << std::endl; return EXIT_FAILURE; } default: return EXIT_FAILURE; } } //------------------------------------------------ int argOffset = optind; if (argc != argOffset + 4) { printHelp(); return EXIT_FAILURE; } const char * basename1 = argv[argOffset]; const char * basename2 = argv[argOffset+1]; double absoluteTolerance = strtod(argv[argOffset+2], nullptr); double relativeTolerance = strtod(argv[argOffset+3], nullptr); std::cout << "Comparing '" << basename1 << "' to '" << basename2 << "'." << std::endl; try { if(regressionTest){ SummaryRegressionTest compare(basename1,basename2, absoluteTolerance, relativeTolerance); compare.throwOnErrors(throwOnError); compare.doAnalysis(analysis); if(printKeywords){compare.setPrintKeywords(true);} if(isRestartFile){compare.setIsRestartFile(true);} if(specificKeyword){ compare.getRegressionTest(keyword); } else{ if(printKeywords){compare.setPrintKeywords(true);} compare.getRegressionTest(); } } if(integrationTest){ SummaryIntegrationTest compare(basename1,basename2, absoluteTolerance, relativeTolerance); compare.throwOnErrors(throwOnError); if(findVectorWithGreatestErrorRatio){compare.setFindVectorWithGreatestErrorRatio(true);} if(allowSpikes){compare.setAllowSpikes(true);} if(oneOfTheMainVariables){ compare.setOneOfTheMainVariables(true); std::string str(mainVariable); std::transform(str.begin(), str.end(),str.begin(), ::toupper); if(str == "WOPR" ||str=="WWPR" ||str=="WGPR" || str == "WBHP"){ compare.setMainVariable(str); }else{ throw std::invalid_argument("The input is not a main variable. -m option requires a valid main variable."); } } if(findVolumeError){compare.setFindVolumeError(true);} if(limit != -1){compare.setSpikeLimit(limit);} if(!allowDifferentAmountOfKeywords){compare.setAllowDifferentAmountOfKeywords(false);} if(printKeywords){compare.setPrintKeywords(true);} if(!throwExceptionForTooGreatErrorRatio){compare.setThrowExceptionForTooGreatErrorRatio(false);} if(specificKeyword){ if(printSpecificKeyword){compare.setPrintSpecificKeyword(true);} compare.getIntegrationTest(keyword); return 0; } compare.getIntegrationTest(); } } catch(const std::exception& e) { std::cerr << "Program threw an exception: " << e.what() << std::endl; return EXIT_FAILURE; } return 0; }
Value Interpreter::exec(const InstructionList &instructions, Bindings &bindings) { Stack stack; ClosureValues closureValues; for(InstructionList::const_iterator it = instructions.begin() ; it != instructions.end() ; ++it) { Instruction::Type type = it->type(); const Value &value = it->value(); switch(type) { case Instruction::PUSH: if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " push " << value << '\n'; } stack.push_back(value); break; case Instruction::CALL: { if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " call " << value << '\n'; } Value result = handleFunction(it->sourceLocation(), value, stack, bindings); stack.push_back(result); if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " return value " << result << '\n'; } } break; case Instruction::JUMP: { int instructionsToSkip = getInstructionsToSkip(type, value); int remaining = instructions.end() - it; if(remaining < instructionsToSkip) { throw CompilerBug("insufficient instructions available to skip! (remaining: " + str(remaining) + " < instructionsToSkip: " + str(instructionsToSkip) + ")"); } if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " jumping back " << instructionsToSkip << '\n'; } it += instructionsToSkip; } break; case Instruction::LOOP: { int instructionsToSkip = getInstructionsToSkip(type, value); int instructionsAvailable = instructions.size(); // Note: signed type is important! if(instructionsAvailable < instructionsToSkip) { throw CompilerBug("insufficient instructions available to loop! (instructionsToSkip: " + str(instructionsToSkip) + " > instructions.size(): " + str(instructions.size()) + ")"); } if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " looping back " << instructionsToSkip << " instructions\n"; } it -= instructionsToSkip; } break; case Instruction::CLOSE: { if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " close " << value << '\n'; } Value result = handleClose(value, stack, closureValues, bindings); stack.push_back(result); } break; case Instruction::COND_JUMP: { if(stack.empty()) { throw CompilerBug("empty stack when testing conditional jump"); } int instructionsToSkip = getInstructionsToSkip(type, value); int remaining = instructions.end() - it; if(remaining < instructionsToSkip) { throw CompilerBug("insufficient instructions available to skip! (remaining: " + str(remaining) + " < instructionsToSkip: " + str(instructionsToSkip) + ")"); } Value top = pop(stack); if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " jumping back " << instructionsToSkip << " if " << top << '\n'; } if(top.isFalsey()) { it += instructionsToSkip; } } break; case Instruction::REF_LOCAL: handleRef(Bindings::Local, value, stack, bindings); if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " local ref '" << value.string() << "' is " << stack.back() << '\n'; } break; case Instruction::INIT_LOCAL: { const Value &intialisedValue = handleInit(Bindings::Local, value, stack, bindings); if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " local init '" << value.string() << "' to " << intialisedValue << '\n'; } } break; case Instruction::ASSIGN_LOCAL: { const Value &assignedValue = handleAssign(Bindings::Local, value, stack, bindings); if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " local assign '" << value.string() << "' to " << assignedValue << '\n'; } } break; case Instruction::REF_GLOBAL: handleRef(Bindings::Global, value, stack, bindings); if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " global ref '" << value.string() << "' is " << stack.back() << '\n'; } break; case Instruction::INIT_GLOBAL: { const Value &intialisedValue = handleInit(Bindings::Global, value, stack, bindings); if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " global init '" << value.string() << "' to " << intialisedValue << '\n'; } } break; case Instruction::ASSIGN_GLOBAL: { const Value &assignedValue = handleAssign(Bindings::Global, value, stack, bindings); if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " global assign '" << value.string() << "' to " << assignedValue << '\n'; } } break; case Instruction::REF_CLOSURE: handleRef(Bindings::Closure, value, stack, bindings); if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " closure ref '" << value.string() << "' is " << stack.back() << '\n'; } break; case Instruction::INIT_CLOSURE: { Identifier identifier = Identifier(value.string()); Bindings::ValuePtr &binding = bindings.getPointer(identifier); closureValues.push_back(ClosedNameAndValue(identifier, binding)); if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " closure init '" << value.string() << "' is " << *binding << '\n'; } } break; case Instruction::ASSIGN_CLOSURE: { const Value &assignedValue = handleAssign(Bindings::Closure, value, stack, bindings); if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " closure assign '" << value.string() << "' to " << assignedValue << '\n'; } } break; case Instruction::MEMBER_ACCESS: { if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " member access " << value << '\n'; } assert(value.isString()); const std::string &memberName = value.string(); Value top = pop(stack); if(!top.isObject()) { throw ExecutionError(it->sourceLocation(), "Member access instruction requires an object but got " + str(top)); } const Value::Object &object = top.object(); Value::Object::const_iterator memberIterator = object.find(memberName); if (memberIterator == object.end()) { throw ExecutionError(it->sourceLocation(), "Unknown member name " + memberName + " for " + str(top)); } if(settings_.trace) { std::cout << "DEBUG: " << it->sourceLocation() << " member access " << value.string() << "." << memberName << " was " << memberIterator->second << '\n'; } stack.push_back(memberIterator->second); } break; default: throw CompilerBug("unhandled instruction type: " + str(type)); } if (settings_.trace) { if (stack.empty()) { std::cout << "Stack is empty\n"; } else { std::cout << "Stack contains " << stack.size() << " entries:\n"; int index = 0; for(Stack::const_iterator it = stack.begin() ; it != stack.end() ; ++it) { ++index; std::cout << index << ": " << *it << '\n'; } } if (closureValues.empty()) { std::cout << "closureValues is empty\n"; } else { std::cout << "closureValues contains " << closureValues.size() << " entries:\n"; int index = 0; for(const ClosedNameAndValue &closedValue: closureValues) { ++index; std::cout << index << ": " << closedValue.first << " -> " << *closedValue.second << " @ " << closedValue.second << '\n'; } } } } return stack.empty() ? Value::nil() : pop(stack); }
void ResolveOperator::Reply(DNSServiceRef aSdRef, DNSServiceFlags aFlags, uint32_t aInterfaceIndex, DNSServiceErrorType aErrorCode, const nsACString& aFullName, const nsACString& aHostTarget, uint16_t aPort, uint16_t aTxtLen, const unsigned char* aTxtRecord) { MOZ_ASSERT(GetThread() == NS_GetCurrentThread()); auto guard = MakeScopeExit([this] { NS_WARN_IF(NS_FAILED(Stop())); }); if (NS_WARN_IF(kDNSServiceErr_NoError != aErrorCode)) { LOG_E("ResolveOperator::Reply (%d)", aErrorCode); return; } // Resolve TXT record int count = TXTRecordGetCount(aTxtLen, aTxtRecord); LOG_I("resolve: txt count = %d, len = %d", count, aTxtLen); nsCOMPtr<nsIWritablePropertyBag2> attributes = nullptr; if (count) { attributes = new nsHashPropertyBag(); if (NS_WARN_IF(!attributes)) { return; } for (int i = 0; i < count; ++i) { char key[TXT_BUFFER_SIZE] = { '\0' }; uint8_t vSize = 0; const void* value = nullptr; if (kDNSServiceErr_NoError != TXTRecordGetItemAtIndex(aTxtLen, aTxtRecord, i, TXT_BUFFER_SIZE, key, &vSize, &value)) { break; } nsAutoCString str(reinterpret_cast<const char*>(value), vSize); LOG_I("resolve TXT: (%d) %s=%s", vSize, key, str.get()); if (NS_WARN_IF(NS_FAILED(attributes->SetPropertyAsACString( /* it's safe to convert because key name is ASCII only. */ NS_ConvertASCIItoUTF16(key), str)))) { break; } } } if (!mListener) { return; } nsCOMPtr<nsIDNSServiceInfo> info = new nsDNSServiceInfo(mServiceInfo); if (NS_WARN_IF(NS_FAILED(info->SetHost(aHostTarget)))) { return; } if (NS_WARN_IF(NS_FAILED(info->SetPort(aPort)))) { return; } if (NS_WARN_IF(NS_FAILED(info->SetAttributes(attributes)))) { return; } if (kDNSServiceErr_NoError == aErrorCode) { GetAddrInfor(info); } else { mListener->OnResolveFailed(info, aErrorCode); NS_WARN_IF(NS_FAILED(Stop())); } }
void ShortcutsWindow::MessageReceived(BMessage* msg) { switch(msg->what) { case OPEN_KEYSET: case APPEND_KEYSET: fLastOpenWasAppend = (msg->what == APPEND_KEYSET); if (fOpenPanel) fOpenPanel->Show(); else { BMessenger m(this); fOpenPanel = new BFilePanel(B_OPEN_PANEL, &m, NULL, 0, false); fOpenPanel->Show(); } fOpenPanel->SetButtonLabel(B_DEFAULT_BUTTON, fLastOpenWasAppend ? B_TRANSLATE("Append") : B_TRANSLATE("Open")); break; case REVERT_KEYSET: { // Send a message to myself, to get me to reload the settings file fLastOpenWasAppend = false; BMessage reload(B_REFS_RECEIVED); entry_ref eref; _GetSettingsFile(&eref); reload.AddRef("refs", &eref); reload.AddString("startupRef", "yeah"); PostMessage(&reload); break; } // Respond to drag-and-drop messages here case B_SIMPLE_DATA: { int i = 0; entry_ref ref; while (msg->FindRef("refs", i++, &ref) == B_OK) { BEntry entry(&ref); if (entry.InitCheck() == B_OK) { BPath path(&entry); if (path.InitCheck() == B_OK) { // Add a new item with the given path. BString str(path.Path()); DoStandardEscapes(str); _AddNewSpec(str.String()); } } } break; } // Respond to FileRequester's messages here case B_REFS_RECEIVED: { // Find file ref entry_ref ref; bool isStartMsg = msg->HasString("startupRef"); if (msg->FindRef("refs", &ref) == B_OK) { // load the file into (fileMsg) BMessage fileMsg; { BFile file(&ref, B_READ_ONLY); if ((file.InitCheck() != B_OK) || (fileMsg.Unflatten(&file) != B_OK)) { if (isStartMsg) { // use this to save to anyway fLastSaved = BEntry(&ref); break; } else { (new BAlert(ERROR, B_TRANSLATE("Shortcuts was couldn't open your " "KeySet file!"), B_TRANSLATE("OK")))->Go(NULL); break; } } } if (fLastOpenWasAppend == false) { // Clear the menu... while (ShortcutsSpec* item = ((ShortcutsSpec*)fColumnListView->RemoveItem(0L))) { delete item; } } if (_LoadKeySet(fileMsg)) { if (isStartMsg) fLastSaved = BEntry(&ref); fSaveButton->SetEnabled(isStartMsg == false); // If we just loaded in the Shortcuts settings file, then // no need to tell the user to save on exit. entry_ref eref; _GetSettingsFile(&eref); if (ref == eref) fKeySetModified = false; } else { (new BAlert(ERROR, B_TRANSLATE("Shortcuts was unable to parse your " "KeySet file!"), B_TRANSLATE("OK")))->Go(NULL); break; } } break; } // These messages come from the pop-up menu of the Applications column case SELECT_APPLICATION: { int csel = fColumnListView->CurrentSelection(); if (csel >= 0) { entry_ref aref; if (msg->FindRef("refs", &aref) == B_OK) { BEntry ent(&aref); if (ent.InitCheck() == B_OK) { BPath path; if ((ent.GetPath(&path) == B_OK) && (((ShortcutsSpec *) fColumnListView->ItemAt(csel))-> ProcessColumnTextString(ShortcutsSpec:: STRING_COLUMN_INDEX, path.Path()))) { fColumnListView->InvalidateItem(csel); _MarkKeySetModified(); } } } } break; } case SAVE_KEYSET: { bool showSaveError = false; const char * name; entry_ref entry; if ((msg->FindString("name", &name) == B_OK) && (msg->FindRef("directory", &entry) == B_OK)) { BDirectory dir(&entry); BEntry saveTo(&dir, name, true); showSaveError = ((saveTo.InitCheck() != B_OK) || (_SaveKeySet(saveTo) == false)); } else if (fLastSaved.InitCheck() == B_OK) { // We've saved this before, save over previous file. showSaveError = (_SaveKeySet(fLastSaved) == false); } else PostMessage(SAVE_KEYSET_AS); // open the save requester... if (showSaveError) { (new BAlert(ERROR, B_TRANSLATE("Shortcuts wasn't able to save your keyset."), B_TRANSLATE("OK")))->Go(NULL); } break; } case SAVE_KEYSET_AS: { if (fSavePanel) fSavePanel->Show(); else { BMessage msg(SAVE_KEYSET); BMessenger messenger(this); fSavePanel = new BFilePanel(B_SAVE_PANEL, &messenger, NULL, 0, false, &msg); fSavePanel->Show(); } break; } case ADD_HOTKEY_ITEM: _AddNewSpec(NULL); break; case REMOVE_HOTKEY_ITEM: { int index = fColumnListView->CurrentSelection(); if (index >= 0) { CLVListItem* item = (CLVListItem*) fColumnListView->ItemAt(index); fColumnListView->RemoveItem(index); delete item; _MarkKeySetModified(); // Rules for new selection: If there is an item at (index), // select it. Otherwise, if there is an item at (index-1), // select it. Otherwise, select nothing. int num = fColumnListView->CountItems(); if (num > 0) { if (index < num) fColumnListView->Select(index); else { if (index > 0) index--; if (index < num) fColumnListView->Select(index); } } } break; } // Received when the user clicks on the ColumnListView case HOTKEY_ITEM_SELECTED: { int32 index = -1; msg->FindInt32("index", &index); bool validItem = (index >= 0); fRemoveButton->SetEnabled(validItem); break; } // Received when an entry is to be modified in response to GUI activity case HOTKEY_ITEM_MODIFIED: { int32 row, column; if ((msg->FindInt32("row", &row) == B_OK) && (msg->FindInt32("column", &column) == B_OK)) { int32 key; const char* bytes; if (row >= 0) { ShortcutsSpec* item = (ShortcutsSpec*) fColumnListView->ItemAt(row); bool repaintNeeded = false; // default if (msg->HasInt32("mouseClick")) { repaintNeeded = item->ProcessColumnMouseClick(column); } else if ((msg->FindString("bytes", &bytes) == B_OK) && (msg->FindInt32("key", &key) == B_OK)) { repaintNeeded = item->ProcessColumnKeyStroke(column, bytes, key); } else if (msg->FindInt32("unmappedkey", &key) == B_OK) { repaintNeeded = ((column == item->KEY_COLUMN_INDEX) && ((key > 0xFF) || (GetKeyName(key) != NULL)) && (item->ProcessColumnKeyStroke(column, NULL, key))); } else if (msg->FindString("text", &bytes) == B_OK) { if ((bytes[0] == '(')&&(bytes[1] == 'C')) { if (fSelectPanel) fSelectPanel->Show(); else { BMessage msg(SELECT_APPLICATION); BMessenger m(this); fSelectPanel = new BFilePanel(B_OPEN_PANEL, &m, NULL, 0, false, &msg); fSelectPanel->Show(); } fSelectPanel->SetButtonLabel(B_DEFAULT_BUTTON, B_TRANSLATE("Select")); } else { repaintNeeded = item->ProcessColumnTextString( column, bytes); } } if (repaintNeeded) { fColumnListView->InvalidateItem(row); _MarkKeySetModified(); } } } break; } default: BWindow::MessageReceived(msg); break; } }
int main (int argc, char **argv) { #ifdef MOZ_WIDGET_GTK2 gtk_init(&argc, &argv); #endif #ifdef XP_MACOSX CocoaPoolInit(); #endif // Initialize XPCOM nsresult rv = NS_InitXPCOM2(nsnull, nsnull, nsnull); if (NS_FAILED(rv)) return -1; rv = gfxPlatform::Init(); if (NS_FAILED(rv)) return -1; // let's get all the xpcom goop out of the system fflush (stderr); fflush (stdout); gTextRuns = new FrameTextRunCache(); nsRefPtr<gfxContext> ctx = MakeContext(); { gfxFontStyle style (FONT_STYLE_NORMAL, 139, 10.0, nsDependentCString("x-western"), 0.0, PR_FALSE, PR_FALSE); nsRefPtr<gfxFontGroup> fontGroup = gfxPlatform::GetPlatform()->CreateFontGroup(NS_LITERAL_STRING("Geneva, MS Sans Serif, Helvetica,serif"), &style); gfxTextRunFactory::Parameters params = { ctx, nsnull, nsnull, nsnull, 0, 60 }; PRUint32 flags = gfxTextRunFactory::TEXT_IS_PERSISTENT; // First load an Arabic word into the cache const char cString[] = "\xd8\xaa\xd9\x85"; nsDependentCString cStr(cString); NS_ConvertUTF8toUTF16 str(cStr); gfxTextRun *tr = MakeTextRun(str.get(), str.Length(), fontGroup, ¶ms, flags); tr->GetAdvanceWidth(0, str.Length(), nsnull); // Now try to trigger an assertion with a word cache bug. The first // word is in the cache so it gets added to the new textrun directly. // The second word is not in the cache const char cString2[] = "\xd8\xaa\xd9\x85\n\xd8\xaa\xd8\x85 "; nsDependentCString cStr2(cString2); NS_ConvertUTF8toUTF16 str2(cStr2); gfxTextRun *tr2 = MakeTextRun(str2.get(), str2.Length(), fontGroup, ¶ms, flags); tr2->GetAdvanceWidth(0, str2.Length(), nsnull); } fflush (stderr); fflush (stdout); }
void KMCupsJobManager::parseListAnswer(IppRequest& req, KMPrinter *pr) { ipp_attribute_t *attr = req.first(); KMJob *job = new KMJob(); QString uri; while (attr) { QString name(attr->name); if (name == "job-id") job->setId(attr->values[0].integer); else if (name == "job-uri") job->setUri(QString::fromLocal8Bit(attr->values[0].string.text)); else if (name == "job-name") job->setName(QString::fromLocal8Bit(attr->values[0].string.text)); else if (name == "job-state") { switch (attr->values[0].integer) { case IPP_JOB_PENDING: job->setState(KMJob::Queued); break; case IPP_JOB_HELD: job->setState(KMJob::Held); break; case IPP_JOB_PROCESSING: job->setState(KMJob::Printing); break; case IPP_JOB_STOPPED: job->setState(KMJob::Error); break; case IPP_JOB_CANCELLED: job->setState(KMJob::Cancelled); break; case IPP_JOB_ABORTED: job->setState(KMJob::Aborted); break; case IPP_JOB_COMPLETED: job->setState(KMJob::Completed); break; default: job->setState(KMJob::Unknown); break; } } else if (name == "job-k-octets") job->setSize(attr->values[0].integer); else if (name == "job-originating-user-name") job->setOwner(QString::fromLocal8Bit(attr->values[0].string.text)); else if (name == "job-k-octets-completed") job->setProcessedSize(attr->values[0].integer); else if (name == "job-media-sheets") job->setPages(attr->values[0].integer); else if (name == "job-media-sheets-completed") job->setProcessedPages(attr->values[0].integer); else if (name == "job-printer-uri" && !pr->isRemote()) { QString str(attr->values[0].string.text); int p = str.findRev('/'); if (p != -1) job->setPrinter(str.mid(p+1)); } else if (name == "job-priority") { job->setAttribute(0, QString::fromLatin1("%1").arg(attr->values[0].integer, 3)); } else if (name == "job-billing") { job->setAttributeCount(2); job->setAttribute(1, QString::fromLocal8Bit(attr->values[0].string.text)); } if (name.isEmpty() || attr == req.last()) { if (job->printer().isEmpty()) job->setPrinter(pr->printerName()); job->setRemote(pr->isRemote()); addJob(job); // don't use job after this call !!! job = new KMJob(); } attr = attr->next; } delete job; }
bool RuleTableLoaderStandard::Load(FormatType format , const std::vector<FactorType> &input , const std::vector<FactorType> &output , const std::string &inFile , size_t /* tableLimit */ , RuleTableTrie &ruleTable) { PrintUserTime(string("Start loading text phrase table. ") + (format==MosesFormat?"Moses ":"Hiero ") + " format"); const StaticData &staticData = StaticData::Instance(); const std::string& factorDelimiter = staticData.GetFactorDelimiter(); string lineOrig; size_t count = 0; std::ostream *progress = NULL; IFVERBOSE(1) progress = &std::cerr; util::FilePiece in(inFile.c_str(), progress); // reused variables vector<float> scoreVector; StringPiece line; std::string hiero_before, hiero_after; double_conversion::StringToDoubleConverter converter(double_conversion::StringToDoubleConverter::NO_FLAGS, NAN, NAN, "inf", "nan"); while(true) { try { line = in.ReadLine(); } catch (const util::EndOfFileException &e) { break; } if (format == HieroFormat) { // inefficiently reformat line hiero_before.assign(line.data(), line.size()); ReformatHieroRule(hiero_before, hiero_after); line = hiero_after; } util::TokenIter<util::MultiCharacter> pipes(line, "|||"); StringPiece sourcePhraseString(*pipes); StringPiece targetPhraseString(*++pipes); StringPiece scoreString(*++pipes); StringPiece alignString; if (++pipes) { StringPiece temp(*pipes); alignString = temp; } if (++pipes) { StringPiece str(*pipes); //counts } bool isLHSEmpty = (sourcePhraseString.find_first_not_of(" \t", 0) == string::npos); if (isLHSEmpty && !staticData.IsWordDeletionEnabled()) { TRACE_ERR( ruleTable.GetFilePath() << ":" << count << ": pt entry contains empty target, skipping\n"); continue; } scoreVector.clear(); for (util::TokenIter<util::AnyCharacter, true> s(scoreString, " \t"); s; ++s) { int processed; float score = converter.StringToFloat(s->data(), s->length(), &processed); UTIL_THROW_IF2(isnan(score), "Bad score " << *s << " on line " << count); scoreVector.push_back(FloorScore(TransformScore(score))); } const size_t numScoreComponents = ruleTable.GetNumScoreComponents(); if (scoreVector.size() != numScoreComponents) { UTIL_THROW2("Size of scoreVector != number (" << scoreVector.size() << "!=" << numScoreComponents << ") of score components on line " << count); } // parse source & find pt node // constituent labels Word *sourceLHS = NULL; Word *targetLHS; // create target phrase obj TargetPhrase *targetPhrase = new TargetPhrase(); // targetPhrase->CreateFromString(Output, output, targetPhraseString, factorDelimiter, &targetLHS); targetPhrase->CreateFromString(Output, output, targetPhraseString, &targetLHS); // source Phrase sourcePhrase; // sourcePhrase.CreateFromString(Input, input, sourcePhraseString, factorDelimiter, &sourceLHS); sourcePhrase.CreateFromString(Input, input, sourcePhraseString, &sourceLHS); // rest of target phrase targetPhrase->SetAlignmentInfo(alignString); targetPhrase->SetTargetLHS(targetLHS); //targetPhrase->SetDebugOutput(string("New Format pt ") + line); if (++pipes) { StringPiece sparseString(*pipes); targetPhrase->SetSparseScore(&ruleTable, sparseString); } if (++pipes) { StringPiece propertiesString(*pipes); targetPhrase->SetProperties(propertiesString); } targetPhrase->GetScoreBreakdown().Assign(&ruleTable, scoreVector); targetPhrase->Evaluate(sourcePhrase, ruleTable.GetFeaturesToApply()); TargetPhraseCollection &phraseColl = GetOrCreateTargetPhraseCollection(ruleTable, sourcePhrase, *targetPhrase, sourceLHS); phraseColl.Add(targetPhrase); // not implemented correctly in memory pt. just delete it for now delete sourceLHS; count++; } // sort and prune each target phrase collection SortAndPrune(ruleTable); return true; }
void MatroskaWrapper::GetSubtitles(agi::fs::path const& filename, AssFile *target) { MkvStdIO input(filename); char err[2048]; agi::scoped_holder<MatroskaFile*, decltype(&mkv_Close)> file(mkv_Open(&input, err, sizeof(err)), mkv_Close); if (!file) throw MatroskaException(err); // Get info unsigned tracks = mkv_GetNumTracks(file); std::vector<unsigned> tracksFound; std::vector<std::string> tracksNames; // Find tracks for (auto track : boost::irange(0u, tracks)) { auto trackInfo = mkv_GetTrackInfo(file, track); if (trackInfo->Type != 0x11) continue; // Known subtitle format std::string CodecID(trackInfo->CodecID); if (CodecID == "S_TEXT/SSA" || CodecID == "S_TEXT/ASS" || CodecID == "S_TEXT/UTF8") { tracksFound.push_back(track); tracksNames.emplace_back(str(boost::format("%d (%s %s)") % track % CodecID % trackInfo->Language)); if (trackInfo->Name) { tracksNames.back() += ": "; tracksNames.back() += trackInfo->Name; } } } // No tracks found if (tracksFound.empty()) throw MatroskaException("File has no recognised subtitle tracks."); unsigned trackToRead; // Only one track found if (tracksFound.size() == 1) trackToRead = tracksFound[0]; // Pick a track else { int choice = wxGetSingleChoiceIndex(_("Choose which track to read:"), _("Multiple subtitle tracks found"), to_wx(tracksNames)); if (choice == -1) throw agi::UserCancelException("canceled"); trackToRead = tracksFound[choice]; } // Picked track mkv_SetTrackMask(file, ~(1 << trackToRead)); auto trackInfo = mkv_GetTrackInfo(file, trackToRead); std::string CodecID(trackInfo->CodecID); bool srt = CodecID == "S_TEXT/UTF8"; bool ssa = CodecID == "S_TEXT/SSA"; AssParser parser(target, !ssa); // Read private data if it's ASS/SSA if (!srt) { // Read raw data std::string priv((const char *)trackInfo->CodecPrivate, trackInfo->CodecPrivateSize); // Load into file boost::char_separator<char> sep("\r\n"); for (auto const& cur : boost::tokenizer<boost::char_separator<char>>(priv, sep)) parser.AddLine(cur); } // Load default if it's SRT else { target->LoadDefault(false); parser.AddLine("[Events]"); } // Read timecode scale auto segInfo = mkv_GetFileInfo(file); longlong timecodeScale = mkv_TruncFloat(trackInfo->TimecodeScale) * segInfo->TimecodeScale; // Progress bar auto totalTime = double(segInfo->Duration) / timecodeScale; DialogProgress progress(nullptr, _("Parsing Matroska"), _("Reading subtitles from Matroska file.")); progress.Run([&](agi::ProgressSink *ps) { read_subtitles(ps, file, &input, srt, totalTime, &parser); }); }
std::string StructuredScript::Nodes::EchoNode::str_(IAny::Ptr value, IStorage *storage, IExceptionManager *exception, INode *expr){ value = value->base(); if (value == nullptr || Query::Object::isUndefined(value) || Query::Object::isExpansion(value) || Query::Object::isExpanded(value)){ Query::ExceptionManager::set(exception, PrimitiveFactory::createString(Query::ExceptionManager::combine( "Cannot echo an invalid object!", expr))); return ""; } auto enumObject = dynamic_cast<IEnum *>(value.get()); if (enumObject != nullptr) return enumObject->name(); auto arrayObject = dynamic_cast<IArrayObject *>(value.get()); if (arrayObject != nullptr){ std::string str; for (auto entry : arrayObject->list()){ auto entryStr = str_(entry.value, storage, exception, expr); if (Query::ExceptionManager::has(exception)) return ""; if (str.empty()) str = entryStr; else str += ", " + entryStr; } return ("[" + str + "]"); } auto rangeObject = dynamic_cast<IRange *>(value.get()); if (rangeObject != nullptr) return rangeObject->str(); auto nodeObject = dynamic_cast<INodeObject *>(value.get()); if (nodeObject != nullptr){ auto nodeValue = nodeObject->value(); return (nodeValue == nullptr) ? value->str(storage, exception, expr) : ("`" + nodeValue->str() + "`"); } auto str = value->str(storage, exception, expr); if (Query::ExceptionManager::has(exception)) return ""; if (dynamic_cast<IString *>(value.get()) != nullptr) return ("\"" + str + "\""); if (dynamic_cast<Objects::Char *>(value.get()) != nullptr) return ("\'" + str + "\'"); if (dynamic_cast<Objects::UChar *>(value.get()) != nullptr) return ("\'" + str + "\'U"); if (dynamic_cast<Objects::Short *>(value.get()) != nullptr) return (str + "H"); if (dynamic_cast<Objects::UShort *>(value.get()) != nullptr) return (str + "UH"); if (dynamic_cast<Objects::UInt *>(value.get()) != nullptr) return (str + "U"); if (dynamic_cast<Objects::Long *>(value.get()) != nullptr || dynamic_cast<Objects::LDouble *>(value.get()) != nullptr) return (str + "L"); if (dynamic_cast<Objects::ULong *>(value.get()) != nullptr) return (str + "UL"); if (dynamic_cast<Objects::LLong *>(value.get()) != nullptr) return (str + "LL"); if (dynamic_cast<Objects::ULLong *>(value.get()) != nullptr) return (str + "ULL"); if (dynamic_cast<Objects::Float *>(value.get()) != nullptr) return (str + "F"); return str; }
QTSS_Error RTSPResponseStream::WriteV(iovec* inVec, UInt32 inNumVectors, UInt32 inTotalLength, UInt32* outLengthSent, UInt32 inSendType) { QTSS_Error theErr = QTSS_NoErr; UInt32 theLengthSent = 0; UInt32 amtInBuffer = this->GetCurrentOffset() - fBytesSentInBuffer; if (amtInBuffer > 0) { // There is some data in the output buffer. Make sure to send that // first, using the empty space in the ioVec. inVec[0].iov_base = this->GetBufPtr() + fBytesSentInBuffer; inVec[0].iov_len = amtInBuffer; theErr = fSocket->WriteV(inVec, inNumVectors, &theLengthSent); if (fPrintRTSP) { DateBuffer theDate; DateTranslator::UpdateDateBuffer(&theDate, 0); // get the current GMT date and time qtss_printf("\n#S->C:\n#time: ms=%" _U32BITARG_ " date=%s\n", (UInt32)OS::StartTimeMilli_Int(), theDate.GetDateBuffer()); for (UInt32 i = 0; i < inNumVectors; i++) { StrPtrLen str((char*)inVec[i].iov_base, (UInt32)inVec[i].iov_len); str.PrintStrEOL(); } } if (theLengthSent >= amtInBuffer) { // We were able to send all the data in the buffer. Great. Flush it. this->Reset(); fBytesSentInBuffer = 0; // Make theLengthSent reflect the amount of data sent in the ioVec theLengthSent -= amtInBuffer; } else { // Uh oh. Not all the data in the buffer was sent. Update the // fBytesSentInBuffer count, and set theLengthSent to 0. fBytesSentInBuffer += theLengthSent; Assert(fBytesSentInBuffer < this->GetCurrentOffset()); theLengthSent = 0; } // theLengthSent now represents how much data in the ioVec was sent } else if (inNumVectors > 1) { theErr = fSocket->WriteV(&inVec[1], inNumVectors - 1, &theLengthSent); } // We are supposed to refresh the timeout if there is a successful write. if (theErr == QTSS_NoErr) fTimeoutTask->RefreshTimeout(); // If there was an error, don't alter anything, just bail if ((theErr != QTSS_NoErr) && (theErr != EAGAIN)) return theErr; // theLengthSent at this point is the amount of data passed into // this function that was sent. if (outLengthSent != NULL) *outLengthSent = theLengthSent; // Update the StringFormatter fBytesWritten variable... this data // wasn't buffered in the output buffer at any time, so if we // don't do this, this amount would get lost fBytesWritten += theLengthSent; // All of the data was sent... whew! if (theLengthSent == inTotalLength) return QTSS_NoErr; // We need to determine now whether to copy the remaining unsent // iovec data into the buffer. This is determined based on // the inSendType parameter passed in. if (inSendType == kDontBuffer) return theErr; if ((inSendType == kAllOrNothing) && (theLengthSent == 0)) return EAGAIN; // Some or none of the iovec data was sent. Copy the remainder into the output // buffer. // The caller should consider this data sent. if (outLengthSent != NULL) *outLengthSent = inTotalLength; UInt32 curVec = 1; while (theLengthSent >= inVec[curVec].iov_len) { // Skip over the vectors that were in fact sent. Assert(curVec < inNumVectors); theLengthSent -= inVec[curVec].iov_len; curVec++; } while (curVec < inNumVectors) { // Copy the remaining vectors into the buffer this->Put(((char*)inVec[curVec].iov_base) + theLengthSent, inVec[curVec].iov_len - theLengthSent); theLengthSent = 0; curVec++; } return QTSS_NoErr; }
bool load(handle src, bool convert) { value.arg = "loading ArgInspector1 argument " + std::string(convert ? "WITH" : "WITHOUT") + " conversion allowed. " "Argument value = " + (std::string) str(src); return true; }
const pstring param_model_t::value_str(const pstring &entity) { return state().setup().models().value_str(str(), entity); }
static handle cast(const ArgInspector1 &src, return_value_policy, handle) { return str(src.arg).release(); }
plib::unique_ptr<plib::pistream> param_data_t::stream() { return device().setup().get_data_stream(str()); }
string char_to_string(char *input_p) { string str(input_p); return str; }
/// Create and register test SeqU(int n0) : SetTest("Sequence::SeqU"+str(n0),n0+1,ds_33,false), n(n0) {}
//------------------------------------------------------------------------------------------------- OutOfRange::OutOfRange(std::size_t index, std::size_t size) : Error("the index (" + str(index) + ") is out of the allowed range [0, " + str(size - 1) + "]") { }
void InvalidQID_r10b::RunCoreTest() { /** \verbatim * Assumptions: * None. * \endverbatim */ string work; bool enableLog; uint64_t maxIOQEntries = 2; if (gCtrlrConfig->SetState(ST_DISABLE_COMPLETELY) == false) throw FrmwkEx(HERE); LOG_NRM("Create admin queues ACQ and ASQ"); SharedACQPtr acq = SharedACQPtr(new ACQ(gDutFd)); acq->Init(5); SharedASQPtr asq = SharedASQPtr(new ASQ(gDutFd)); asq->Init(5); // All queues will use identical IRQ vector IRQ::SetAnySchemeSpecifyNum(1); gCtrlrConfig->SetCSS(CtrlrConfig::CSS_NVM_CMDSET); if (gCtrlrConfig->SetState(ST_ENABLE) == false) throw FrmwkEx(HERE); // Calc X, max no. of IOSQ's DUT supports. uint32_t X = gInformative->GetFeaturesNumOfIOSQs(); LOG_NRM("Maximum num of IOSQ's DUT will support = %d", X); LOG_NRM("Setup element sizes for the IOQ's"); gCtrlrConfig->SetIOCQES(gInformative->GetIdentifyCmdCtrlr()-> GetValue(IDCTRLRCAP_CQES) & 0xf); gCtrlrConfig->SetIOSQES(gInformative->GetIdentifyCmdCtrlr()-> GetValue(IDCTRLRCAP_SQES) & 0xf); LOG_NRM("Create IOCQ with QID = %d", IOQ_ID); SharedIOCQPtr iocq = Queues::CreateIOCQContigToHdw(mGrpName, mTestName, CALC_TIMEOUT_ms(1), asq, acq, IOQ_ID, maxIOQEntries, false, IOCQ_GROUP_ID, true, 0); LOG_NRM("Issue CreateIOSQ cmds with QID's ranging from %d to %d", (X + 1), MAX_IOQ_ID); list<uint32_t> illegalQIDs = GetIllegalQIDs(X + 1); for (list<uint32_t>::iterator qId = illegalQIDs.begin(); qId != illegalQIDs.end(); qId++) { LOG_NRM("Process CreateIOSQCmd with iosq id #%d and assoc iocq id #%d", *qId, IOQ_ID); SharedIOSQPtr iosq = SharedIOSQPtr(new IOSQ(gDutFd)); iosq->Init(*qId, maxIOQEntries, IOQ_ID, 0); SharedCreateIOSQPtr createIOSQCmd = SharedCreateIOSQPtr(new CreateIOSQ()); createIOSQCmd->Init(iosq); work = str(boost::format("iosqId.%d") % *qId); enableLog = false; if ((*qId <= (X + 8)) || (*qId >= (MAX_IOQ_ID - 8))) enableLog = true; LOG_NRM("Send and reap cmd with SQ ID #%d", *qId); IO::SendAndReapCmd(mGrpName, mTestName, CALC_TIMEOUT_ms(1), asq, acq, createIOSQCmd, work, enableLog, CESTAT_INVALID_QID); } }
int sync() { print(str().c_str()); str(std::string()); // Clear the string buffer return 0; }
void Command::edi(std::string cmd, GameEngine *game) { std::string str(cmd.begin() + 5, cmd.end()); int val = stoi(str); game->deleteEgg(val, 0); }
void SeeDif::updateBrowser() { sdfmakelockfiles=NIL; if (openDatabase()) return; seadifBrowser->Clear(); sdfNameIterator seadifName; int out; outSelBS->GetValue(out); switch (out) { case 1: seadifName.initialize(libNamEditor->Text()); break; case 2: seadifName.initialize(libNamEditor->Text(),funNamEditor->Text()); break; case 3: seadifName.initialize(libNamEditor->Text(),funNamEditor->Text(), cirNamEditor->Text()); break; case 4: seadifName.initialize(libNamEditor->Text(),funNamEditor->Text(), cirNamEditor->Text(),layNamEditor->Text()); break; } int mode; outModeBS->GetValue(mode); while (seadifName()) { if (mode == 1) { seadifBrowser->Append(seadifName.sdfName()); } else { char buf[200]; int width=20; ostrstream str(buf,200); str.setf(ios::left,ios::adjustfield); str.width(width); str << seadifName.bname(); if (out > 1) { str.width(width); str << seadifName.fname(); } if (out> 2) { str.width(width); str << seadifName.cname(); } if (out > 3) { str.width(width); str << seadifName.lname() ; } str << ends; seadifBrowser->Append(buf); } } closeDatabase(); }
// Return string with repeated characters removed Foam::string Foam::string::removeRepeated(const char character) const { string str(*this); str.removeRepeated(character); return str; }
int RedisLink::convert_req(){ if(!inited){ inited = true; RedisCommand_raw *def = &cmds_raw[0]; while(def->redis_cmd != NULL){ RedisRequestDesc desc; desc.strategy = def->strategy; desc.redis_cmd = def->redis_cmd; desc.ssdb_cmd = def->ssdb_cmd; desc.reply_type = def->reply_type; cmd_table[desc.redis_cmd] = desc; def += 1; } } this->req_desc = NULL; std::map<std::string, RedisRequestDesc>::iterator it; it = cmd_table.find(cmd); if(it == cmd_table.end()){ recv_string.push_back(cmd); for(int i=1; i<recv_bytes.size(); i++){ recv_string.push_back(recv_bytes[i].String()); } return 0; } this->req_desc = &(it->second); if(this->req_desc->strategy == STRATEGY_HKEYS || this->req_desc->strategy == STRATEGY_HVALS ){ recv_string.push_back(req_desc->ssdb_cmd); if(recv_bytes.size() == 2){ recv_string.push_back(recv_bytes[1].String()); recv_string.push_back(""); recv_string.push_back(""); recv_string.push_back("2000000000"); } return 0; } if(this->req_desc->strategy == STRATEGY_SETEX){ recv_string.push_back(req_desc->ssdb_cmd); if(recv_bytes.size() == 4){ recv_string.push_back(recv_bytes[1].String()); recv_string.push_back(recv_bytes[3].String()); recv_string.push_back(recv_bytes[2].String()); } return 0; } if(this->req_desc->strategy == STRATEGY_ZADD){ recv_string.push_back(req_desc->ssdb_cmd); if(recv_bytes.size() >= 2){ recv_string.push_back(recv_bytes[1].String()); for(int i=2; i<=recv_bytes.size()-2; i+=2){ recv_string.push_back(recv_bytes[i+1].String()); recv_string.push_back(recv_bytes[i].String()); } } return 0; } if(this->req_desc->strategy == STRATEGY_ZINCRBY){ recv_string.push_back(req_desc->ssdb_cmd); if(recv_bytes.size() == 4){ recv_string.push_back(recv_bytes[1].String()); recv_string.push_back(recv_bytes[3].String()); recv_string.push_back(recv_bytes[2].String()); } return 0; } if(this->req_desc->strategy == STRATEGY_REMRANGEBYRANK || this->req_desc->strategy == STRATEGY_REMRANGEBYSCORE) { recv_string.push_back(req_desc->ssdb_cmd); if(recv_bytes.size() >= 4){ recv_string.push_back(recv_bytes[1].String()); recv_string.push_back(recv_bytes[2].String()); recv_string.push_back(recv_bytes[3].String()); } return 0; } if(this->req_desc->strategy == STRATEGY_ZRANGE || this->req_desc->strategy == STRATEGY_ZREVRANGE) { recv_string.push_back(req_desc->ssdb_cmd); if(recv_bytes.size() >= 4){ int64_t start = recv_bytes[2].Int64(); int64_t end = recv_bytes[3].Int64(); if((start >= 0 && end >= 0) || end == -1){ int64_t size; if(end == -1){ size = -1; }else{ if(this->req_desc->strategy == STRATEGY_REMRANGEBYSCORE){ size = end; }else{ size = end - start + 1; } } recv_string.push_back(recv_bytes[1].String()); recv_string.push_back(recv_bytes[2].String()); recv_string.push_back(str(size)); } } if(recv_bytes.size() > 4){ std::string s = recv_bytes[4].String(); strtolower(&s); recv_string.push_back(s); } return 0; } if(this->req_desc->strategy == STRATEGY_ZRANGEBYSCORE || this->req_desc->strategy == STRATEGY_ZREVRANGEBYSCORE){ recv_string.push_back(req_desc->ssdb_cmd); std::string name, smin, smax, withscores, offset, count; if(recv_bytes.size() >= 4){ name = recv_bytes[1].String(); smin = recv_bytes[2].String(); smax = recv_bytes[3].String(); bool after_limit = false; for(int i=4; i<recv_bytes.size(); i++){ std::string s = recv_bytes[i].String(); if(after_limit){ if(offset.empty()){ offset = s; }else{ count = s; after_limit = false; } } strtolower(&s); if(s == "withscores"){ withscores = s; }else if(s == "limit"){ after_limit = true; } } } if(smin.empty() || smax.empty()){ return 0; } recv_string.push_back(name); recv_string.push_back(""); if(smin == "-inf" || smin == "+inf"){ recv_string.push_back(""); }else{ if(smin[0] == '('){ std::string tmp(smin.data() + 1, smin.size() - 1); char buf[32]; if(this->req_desc->strategy == STRATEGY_ZRANGEBYSCORE){ snprintf(buf, sizeof(buf), "%d", str_to_int(tmp) + 1); }else{ snprintf(buf, sizeof(buf), "%d", str_to_int(tmp) - 1); } smin = buf; } recv_string.push_back(smin); } if(smax == "-inf" || smax == "+inf"){ recv_string.push_back(""); }else{ if(smax[0] == '('){ std::string tmp(smax.data() + 1, smax.size() - 1); char buf[32]; if(this->req_desc->strategy == STRATEGY_ZRANGEBYSCORE){ snprintf(buf, sizeof(buf), "%d", str_to_int(tmp) - 1); }else{ snprintf(buf, sizeof(buf), "%d", str_to_int(tmp) + 1); } smax = buf; } recv_string.push_back(smax); } if(offset.empty()){ recv_string.push_back("0"); }else{ recv_string.push_back(offset); } if(count.empty()){ recv_string.push_back("2000000000"); }else{ recv_string.push_back(count); } recv_string.push_back(withscores); return 0; } recv_string.push_back(req_desc->ssdb_cmd); for(int i=1; i<recv_bytes.size(); i++){ recv_string.push_back(recv_bytes[i].String()); } return 0; }