bool ICACHE_FLASH_ATTR passesFilter(char *appTokens[]) { int filterID; bool anyMatched = false; int activeFilters = 0; for (filterID = 0; filterID < FILTER_COUNT; filterID++) { if (strlen(sysCfg.filters[filterID]) > 0) activeFilters++; } if (activeFilters == 0) { INFOP("No filters\n"); return true; } for (filterID = 0; filterID < FILTER_COUNT && !anyMatched; filterID++) { if (strlen(sysCfg.filters[filterID]) > 0) { bool match = true; char *filterTokens[10]; char bfr[100]; // splitString overwrites filter template! strcpy(bfr, sysCfg.filters[filterID]); int tokenCount = splitString((char *) bfr, '/', filterTokens); int tkn; for (tkn = 0; tkn < tokenCount && match; tkn++) { if (strcmp("+", filterTokens[tkn]) == 0) continue; if (strcmp("#", filterTokens[tkn]) == 0) break; if (strcmp(filterTokens[tkn], appTokens[tkn]) != 0) match = false; } if (match) anyMatched = true; } } INFOP("Filter matched %d - (%s)\n", anyMatched, sysCfg.filters[filterID]); return anyMatched; }
void Artists::addSome() { auto searchKeywords = splitString(_search->text().toUTF8(), " "); auto clusterIds = _filters->getClusterIds(); Wt::Dbo::Transaction transaction(LmsApp->getDboSession()); bool moreResults; auto artists = Artist::getByFilter(LmsApp->getDboSession(), clusterIds, searchKeywords, _container->count(), 20, moreResults); for (auto artist : artists) { Wt::WTemplate* entry = _container->addNew<Wt::WTemplate>(Wt::WString::tr("Lms.Explore.Artists.template.entry")); entry->bindWidget("name", LmsApplication::createArtistAnchor(artist)); } _showMore->setHidden(!moreResults); }
static bool fromString(const CString& str, HeadingStyle& hs) { CStringArray parts; splitString(str, parts, _T('|')); if (parts.GetCount() != 9) return false; memset(&hs, 0, sizeof(hs)); _tcsncpy(hs.fontFamily, parts[0], LF_FACESIZE); hs.fontPointSize = _ttoi(parts[1]); hs.fontBold = parts[2] == _T("1"); hs.fontItalic = parts[3] == _T("1"); hs.fontUnderline = parts[4] == _T("1"); hs.fontColor = _ttoi(parts[5]); hs.breakPage = parts[6] == _T("1"); hs.numbered = parts[7] == _T("1"); hs.justify = HeadingStyle::_justify(_ttoi(parts[8])); if (hs.fontPointSize < 0 || hs.fontPointSize > 99 || hs.justify < 0 || hs.justify > 2 || hs.fontFamily[0] == 0) return false; return true; }
void Platform::createDirectorys(const char* path) { char szFileNameTmp[1024]; strncpy(szFileNameTmp, path, 1024); replaceBacklashPath(szFileNameTmp); std::string strPathName = szFileNameTmp; size_t pos = strPathName.find_last_of("\\"); std::string strPath = strPathName.substr(0,pos); std::string strName = strPathName.substr(pos+1,strPathName.length()); vector<string> list; splitString(list, strPath, "/"); string strPathTemp; for (size_t i=0; i<list.size(); i++) { strPathTemp += list[i]; strPathTemp += "/"; if (strPathTemp == "./") continue; if (!Platform::isDirExist(strPathTemp.c_str())) Platform::mkdir(strPathTemp.c_str()); } }
void CSVreader::readData( const string &filename, const string &csvdelimiter, vector< vector<double> > &sarr, int numY, int numX ) { numY++; numX; ifstream fin(filename.c_str()); string s; vector<string> selements; vector<double> delements; int x = 0; while ( !fin.eof() ) { getline(fin, s); if ( !s.empty() ) { splitString(s, selements, csvdelimiter); for ( int i=0; i<selements.size(); i++ ) { delements.push_back(stringToDouble(selements[i])); if (i>=numX) break; } sarr.push_back(delements); selements.clear(); delements.clear(); } x++; if (x>=numY) break; } fin.close(); }
void UltraRemapOpLimit::process(sgxString &resultPattern, const sgxString &source) const { std::vector<sgxString> result; int argCount = splitString(result, source, ' '); if (argCount >= 3) { int v = atoi(result[0].c_str()); int minimum = atoi(result[1].c_str()); int maximum = atoi(result[2].c_str()); if (v < minimum) { v = minimum; } else if (v > maximum) { v = maximum; } intToString(resultPattern, v); } else { log(LOG_WARNING, "op.limit didn't have 3 args"); } }
void NXClientLib::processParseStdout() { QString message = nxsshProcess.readAllStandardOutput().data(); // Message 211 is sent if ssh is asking to continue with an unknown host if (session.parseResponse(message) == 211) { emit sshRequestConfirmation(message); } cout << message.toStdString(); emit stdout(message); QStringList messages = splitString(message); QStringList::const_iterator i; // On some connections this is sent via stdout instead of stderr? if (proxyData.encrypted && isFinished && message.contains("NX> 999 Bye")) { QString returnMessage; returnMessage = "NX> 299 Switching connection to: "; returnMessage += proxyData.proxyIP + ":" + QString::number(proxyData.port) + " cookie: " + proxyData.cookie + "\n"; write(returnMessage); } else if (message.contains("NX> 287 Redirected I/O to channel descriptors")) emit callbackWrite(tr("The session has been started successfully")); for (i = messages.constBegin(); i != messages.constEnd(); ++i) { if ((*i).contains("Password")) { emit callbackWrite(tr("Authenticating with NX server")); password = true; } if (!isFinished) write(session.parseSSH(*i)); else write(parseSSH(*i)); } }
static char * findProgram (const char *name) { char *path = NULL; const char *string; if ((string = getenv("PATH"))) { int count; char **array; if ((array = splitString(string, ':', &count))) { int index; for (index=0; index<count; ++index) { const char *directory = array[index]; if (!*directory) directory = "."; if ((path = testProgram(directory, name))) break; } deallocateStrings(array); } } return path; }
PPaths FileReaderTXT::getDataPaths(int num) { vector<string> stringList = getDataStrings(num, ':'); PPaths result(new vector<IdentifiersType>()); for (vector<string>::iterator iset = stringList.begin(); iset != stringList.end(); ++iset) { vector<string> subsetStrings; IdentifiersType subset; splitString(*iset, &subsetStrings, ','); char *p; IdentifiersType path; for (vector<string>::const_iterator i = subsetStrings.begin(); i != subsetStrings.end(); ++i) { long li = strtol((*i).c_str(), &p, 10); if (*p == 0) { path.push_back(li); } } result->push_back(path); } return result; }
/** * This method creates a ConnectionConfig object based on the data in a string, the data in the string must contain the * port, the host and the url of a web service. The format of the string (rInformation) must be equal to as follows: * "port,host,url". If the information is incorrect this method return a null pointer. * Example if rInformation is equal to "80,localhost,http//localhost:80/WebAppCar/service/rest/embedded/addReport" * the method return a pointer to a ConnectionConfig which the port is 80, the host is localhost and the url is * http//localhost:80/WebAppCar/service/rest/embedded/addReport. <p> * * @param rInformation The information required to create a ConnectionConfig (A string with the port, the host and the url) * @return ConnectionConfig* A pointer to a ConnectionConfig which was created with the information on the string. */ ConnectionConfig* FileReader::createConnectionConfig(string rInformation){ //Vector that contains the data of the information vector<string> string_list; //Split the information based on the character separator "," splitString(rInformation, INFORMATION_SEPARATOR, string_list); //Check if the information has been divided in three parts if(string_list.size() == SIZE_CONNEC_CONFIG){ string string_port = string_list.at(POS_PORT_WEBCON); string host = string_list.at(POS_HOST_WEBCON); string url = string_list.at(POS_URL_WEBCON); //Check if the port is a number if(!isNumber(string_port)){ return NULL; } int port = atoi(string_port.c_str()); ConnectionConfig* p_connection_config = new ConnectionConfig(port,host,url); return p_connection_config; } return NULL; }
boolean TransducerProxy::read (char*& reply) { boolean ret; char buf[8] = {0}, *r; strcat (buf, "REA "); strcat (buf, name); strcat (buf, "\n"); if ((ret = srvpx -> sendcmd (buf, r))) { char *p[2]; if (splitString (r, p, 2) != 2) { DPRINT (F("AAA:")); DPRINTLN (r); ret = false; } else if (strcmp (p[0], name) != 0) { DPRINT (F("AAAAAA: ")); DPRINTLN (r); ret = false; } else { reply = p[1]; } } return ret; }
/// extern vector<string> splitString(string const &text, string const &split) { return splitString(text, split, 0); }
void ThemeComponent::readXML(std::string path) { if(mPath == path) return; setDefaults(); deleteComponents(); mPath = path; if(path.empty()) return; LOG(LogInfo) << "Loading theme \"" << path << "\"..."; pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(path.c_str()); if(!result) { LOG(LogError) << "Error parsing theme \"" << path << "\"!\n" << " " << result.description(); return; } pugi::xml_node root; if(!mDetailed) { //if we're using the basic view, check if there's a basic version of the theme root = doc.child("basicTheme"); } if(!root) { root = doc.child("theme"); } if(!root) { LOG(LogError) << "No theme tag found in theme \"" << path << "\"!"; return; } //load non-component theme stuff mColorMap["primary"] = resolveColor(root.child("listPrimaryColor").text().get(), mColorMap["primary"]); mColorMap["secondary"] = resolveColor(root.child("listSecondaryColor").text().get(), mColorMap["secondary"]); mColorMap["selector"] = resolveColor(root.child("listSelectorColor").text().get(), mColorMap["selector"]); mColorMap["selected"] = resolveColor(root.child("listSelectedColor").text().get(), mColorMap["selected"]); mColorMap["description"] = resolveColor(root.child("descColor").text().get(), mColorMap["description"]); mColorMap["fastSelect"] = resolveColor(root.child("fastSelectColor").text().get(), mColorMap["fastSelect"]); mBoolMap["hideHeader"] = root.child("hideHeader") != 0; mBoolMap["hideDividers"] = root.child("hideDividers") != 0; //GuiBox theming data mBoxData.backgroundPath = expandPath(root.child("boxBackground").text().get()); mBoxData.backgroundTiled = root.child("boxBackgroundTiled") != 0; mBoxData.horizontalPath = expandPath(root.child("boxHorizontal").text().get()); mBoxData.horizontalTiled = root.child("boxHorizontalTiled") != 0; mBoxData.verticalPath = expandPath(root.child("boxVertical").text().get()); mBoxData.verticalTiled = root.child("boxVerticalTiled") != 0; mBoxData.cornerPath = expandPath(root.child("boxCorner").text().get()); //list stuff mBoolMap["listCentered"] = !root.child("listLeftAlign"); mFloatMap["listOffsetX"] = strToFloat(root.child("listOffsetX").text().get(), mFloatMap["listOffsetX"]); mFloatMap["listTextOffsetX"] = strToFloat(root.child("listTextOffsetX").text().get(), mFloatMap["listTextOffsetX"]); //game image stuff std::string artPos = root.child("gameImagePos").text().get(); std::string artDim = root.child("gameImageDim").text().get(); std::string artOrigin = root.child("gameImageOrigin").text().get(); std::string artPosX, artPosY, artWidth, artHeight, artOriginX, artOriginY; splitString(artPos, ' ', &artPosX, &artPosY); splitString(artDim, ' ', &artWidth, &artHeight); splitString(artOrigin, ' ', &artOriginX, &artOriginY); mFloatMap["gameImageOffsetX"] = resolveExp(artPosX, mFloatMap["gameImageOffsetX"]); mFloatMap["gameImageOffsetY"] = resolveExp(artPosY, mFloatMap["gameImageOffsetY"]); mFloatMap["gameImageWidth"] = resolveExp(artWidth, mFloatMap["gameImageWidth"]); mFloatMap["gameImageHeight"] = resolveExp(artHeight, mFloatMap["gameImageHeight"]); mFloatMap["gameImageOriginX"] = resolveExp(artOriginX, mFloatMap["gameImageOriginX"]); mFloatMap["gameImageOriginY"] = resolveExp(artOriginY, mFloatMap["gameImageOriginY"]); mStringMap["imageNotFoundPath"] = expandPath(root.child("gameImageNotFound").text().get()); //sounds mSoundMap["menuScroll"]->loadFile(expandPath(root.child("menuScrollSound").text().get())); mSoundMap["menuSelect"]->loadFile(expandPath(root.child("menuSelectSound").text().get())); mSoundMap["menuBack"]->loadFile(expandPath(root.child("menuBackSound").text().get())); mSoundMap["menuOpen"]->loadFile(expandPath(root.child("menuOpenSound").text().get())); //fonts mListFont = resolveFont(root.child("listFont"), Font::getDefaultPath(), Renderer::getDefaultFont(Renderer::MEDIUM)->getSize()); mDescFont = resolveFont(root.child("descriptionFont"), Font::getDefaultPath(), Renderer::getDefaultFont(Renderer::SMALL)->getSize()); mFastSelectFont = resolveFont(root.child("fastSelectFont"), Font::getDefaultPath(), Renderer::getDefaultFont(Renderer::LARGE)->getSize()); //actually read the components createComponentChildren(root, this); LOG(LogInfo) << "Theme loading complete."; }
int main (int argc, char* argv[]) { SAMPLE sample; /* training sample */ LEARN_PARM learn_parm; KERNEL_PARM kernel_parm; STRUCT_LEARN_PARM struct_parm; STRUCTMODEL structmodel; int alg_type; svm_struct_learn_api_init(argc,argv); read_input_parameters(argc,argv,trainfile,modelfile,&verbosity, &struct_verbosity,&struct_parm,&learn_parm, &kernel_parm,&alg_type); if(struct_verbosity>=1) { //verbose = true; printf("Reading training examples..."); fflush(stdout); } /* read the training examples */ sample=read_struct_examples(trainfile,&struct_parm); if(struct_verbosity>=1) { printf("done\n"); fflush(stdout); } string config_tmp; bool update_loss_function = false; if(Config::Instance()->getParameter("update_loss_function", config_tmp)) { update_loss_function = config_tmp.c_str()[0] == '1'; } printf("[Main] update_loss_function=%d\n", (int)update_loss_function); if(!update_loss_function) { printf("update_loss_function should be true\n"); exit(-1); } eUpdateType updateType = UPDATE_NODE_EDGE; if(Config::Instance()->getParameter("update_type", config_tmp)) { updateType = (eUpdateType)atoi(config_tmp.c_str()); } printf("[Main] update_type=%d\n", (int)updateType); mkdir(loss_dir, 0777); // check if parameter vector files exist const char* parameter_vector_dir = "parameter_vector"; int idx = 0; string parameter_vector_dir_last = findLastFile(parameter_vector_dir, "", &idx); string parameter_vector_file_pattern = parameter_vector_dir_last + "/iteration_"; int idx_1 = 1; string parameter_vector_file_last = findLastFile(parameter_vector_file_pattern, ".txt", &idx_1); printf("[Main] Checking parameter vector file %s\n", parameter_vector_file_last.c_str()); // vectors used to store RF weights vector<double>* alphas = new vector<double>[sample.n]; vector<double>* alphas_edge = 0; if(updateType == UPDATE_NODE_EDGE) { alphas_edge = new vector<double>[sample.n]; } int alphas_idx = 0; if(fileExists("alphas.txt") && fileExists(parameter_vector_file_last)) { // Loading alpha coefficients ifstream ifs("alphas.txt"); string line; int lineIdx = 0; while(lineIdx < sample.n && getline(ifs, line)) { vector<string> tokens; splitString(line, tokens); for(vector<string>::iterator it = tokens.begin(); it != tokens.end(); ++it) { alphas[lineIdx].push_back(atoi(it->c_str())); } ++lineIdx; } ifs.close(); if(lineIdx > 0) { alphas_idx = alphas[0].size(); } // Loading parameters printf("[Main] Found parameter vector file %s\n", parameter_vector_file_last.c_str()); struct_parm.ssvm_iteration = idx + 1; update_output_dir(struct_parm.ssvm_iteration); //EnergyParam param(parameter_vector_file_last.c_str()); //updateCoeffs(sample, param, struct_parm, updateType, alphas, alphas_idx); //alphas_idx = 1; } else { struct_parm.ssvm_iteration = 0; // insert alpha coefficients for first iteration for(int i = 0; i < sample.n; ++i) { alphas[i].push_back(1); } ofstream ofs("alphas.txt", ios::app); int i = 0; for(; i < sample.n - 1; ++i) { ofs << alphas[i][alphas_idx] << " "; } if(i < sample.n) { ofs << alphas[i][alphas_idx]; } ofs << endl; ofs.close(); // edges for(int i = 0; i < sample.n; ++i) { alphas_edge[i].push_back(1); } ofstream ofse("alphas_edge.txt", ios::app); i = 0; for(; i < sample.n - 1; ++i) { ofse << alphas_edge[i][alphas_idx] << " "; } if(i < sample.n) { ofse << alphas_edge[i][alphas_idx]; } ofse << endl; ofse.close(); ++alphas_idx; } const int nMaxIterations = 5; bool bIterate = true; do { printf("-----------------------------------------SSVM-ITERATION-%d-START\n", struct_parm.ssvm_iteration); struct_parm.iterationId = 1; /* Do the learning and return structmodel. */ if(alg_type == 0) svm_learn_struct(sample,&struct_parm,&learn_parm,&kernel_parm,&structmodel,NSLACK_ALG); else if(alg_type == 1) svm_learn_struct(sample,&struct_parm,&learn_parm,&kernel_parm,&structmodel,NSLACK_SHRINK_ALG); else if(alg_type == 2) svm_learn_struct_joint(sample,&struct_parm,&learn_parm,&kernel_parm,&structmodel,ONESLACK_PRIMAL_ALG); else if(alg_type == 3) svm_learn_struct_joint(sample,&struct_parm,&learn_parm,&kernel_parm,&structmodel,ONESLACK_DUAL_ALG); else if(alg_type == 4) svm_learn_struct_joint(sample,&struct_parm,&learn_parm,&kernel_parm,&structmodel,ONESLACK_DUAL_CACHE_ALG); else if(alg_type == 9) svm_learn_struct_joint_custom(sample,&struct_parm,&learn_parm,&kernel_parm,&structmodel); else exit(1); char _modelfile[BUFFER_SIZE]; //sprintf(_modelfile, "%s_%d", modelfile, struct_parm.ssvm_iteration); sprintf(_modelfile, "%s_%d", modelfile, struct_parm.ssvm_iteration); printf("[Main] Writing learned model to %s\n", _modelfile); write_struct_model(_modelfile, &structmodel, &struct_parm); // Run inference on training data and increase loss for misclassified points printf("[Main] Loading learned model to %s\n", _modelfile); EnergyParam param(_modelfile); updateCoeffs(sample, param, struct_parm, updateType, alphas, alphas_edge, struct_parm.ssvm_iteration + 1); ofstream ofs("alphas.txt", ios::app); int i = 0; for(; i < sample.n - 1; ++i) { ofs << alphas[i][alphas_idx] << " "; } if(i < sample.n) { ofs << alphas[i][alphas_idx]; } ofs << endl; ofs.close(); ofstream ofse("alphas_edge.txt", ios::app); i = 0; for(; i < sample.n - 1; ++i) { ofse << alphas_edge[i][alphas_idx] << " "; } if(i < sample.n) { ofse << alphas_edge[i][alphas_idx]; } ofse << endl; ofse.close(); ++alphas_idx; printf("-----------------------------------------SSVM-ITERATION-%d-END\n", struct_parm.ssvm_iteration); ++struct_parm.ssvm_iteration; bIterate = (nMaxIterations == -1 || struct_parm.ssvm_iteration < nMaxIterations); } while(bIterate); // Output final segmentation for all examples long nExamples = sample.n; int nRFs = struct_parm.ssvm_iteration; double* lossPerLabel = 0; labelType* groundTruthLabels = 0; for(int i = 0; i < nExamples; i++) { /*** example loop ***/ Slice_P* slice = sample.examples[i].x.slice; Feature* feature = sample.examples[i].x.feature; //map<sidType, nodeCoeffType>* nodeCoeffs = sample.examples[i].x.nodeCoeffs; //map<sidType, edgeCoeffType>* edgeCoeffs = sample.examples[i].x.edgeCoeffs; map<sidType, nodeCoeffType>* nodeCoeffs = 0; map<sidType, edgeCoeffType>* edgeCoeffs = 0; int nNodes = slice->getNbSupernodes(); stringstream soutPb; soutPb << loss_dir; soutPb << "pb_"; soutPb << getNameFromPathWithoutExtension(slice->getName()); soutPb << "_"; soutPb << "combined"; //soutPb << setw(5) << setfill('0') << ssvm_iteration; soutPb << ".tif"; printf("[Main] Exporting %s\n", soutPb.str().c_str()); labelType* inferredLabels = computeCombinedLabels(slice, feature, groundTruthLabels, lossPerLabel, nRFs, alphas, i, nodeCoeffs, edgeCoeffs, soutPb.str().c_str()); stringstream sout; sout << loss_dir; sout << getNameFromPathWithoutExtension(slice->getName()); sout << "_"; sout << "combined"; //sout << setw(5) << setfill('0') << ssvm_iteration; sout << ".tif"; printf("[Main] Exporting %s\n", sout.str().c_str()); slice->exportOverlay(sout.str().c_str(), inferredLabels); stringstream soutBW; soutBW << loss_dir; soutBW << getNameFromPathWithoutExtension(slice->getName()); soutBW << "_"; soutBW << "combined"; //soutBW << setw(5) << setfill('0') << ssvm_iteration; soutBW << "_BW.tif"; printf("[Main] Exporting %s\n", soutBW.str().c_str()); slice->exportSupernodeLabels(soutBW.str().c_str(), struct_parm.nClasses, inferredLabels, nNodes, &(struct_parm.labelToClassIdx)); delete[] inferredLabels; } free_struct_sample(sample); free_struct_model(structmodel); svm_struct_learn_api_exit(); return 0; }
int xslDbgShellSetVariable(xsltTransformContextPtr styleCtxt, xmlChar * arg) { int result = 0, showUsage = 0; xmlChar *name, *nameURI, *selectExpr, *opts[3]; if (!styleCtxt) { xsldbgGenericErrorFunc(i18n("Error: Stylesheet is not valid.\n")); return result; } if (!arg) { #ifdef WITH_XSLDBG_DEBUG_PROCESS xsltGenericError(xsltGenericErrorContext, "Error: NULL argument provided\n"); #endif return result; } if (xmlStrLen(arg) > 1) { if (splitString(arg, 2, opts) == 2) { nameURI = NULL; /* ignore any "$" prefix as user probably didn't mean that "$" is part of variable name*/ if (*opts[0] =='$'){ opts[0] = opts[0] + 1; } name = xmlSplitQName2(opts[0], &nameURI); if (name == NULL) name = xmlStrdup(opts[0]); selectExpr = xmlStrdup(opts[1]); if (name && selectExpr) { xsltStackElemPtr def = NULL; if (styleCtxt->varsBase) { /* try finding varaible in stack */ xsltStackElemPtr item = styleCtxt->varsTab[styleCtxt->varsBase]; while (item) { if ((xmlStrCmp(name, item->name) == 0) && (item->nameURI == NULL || (xmlStrCmp(name, item->nameURI) == 0))) { def = item; break; } item = item->next; } } if (def == NULL) def = (xsltStackElemPtr) xmlHashLookup2(styleCtxt->globalVars, name, nameURI); if (def != NULL) { if (def->select) { /* we've found the variable so change it */ xmlFree((void*)def->select); def->select = selectExpr; if (def->comp->comp) xmlXPathFreeCompExpr(def->comp->comp); def->comp->comp = xmlXPathCompile(def->select); if (def->value) xmlXPathFreeObject(def->value); def->value = xmlXPathEval(def->select, styleCtxt->xpathCtxt); result = 1; } else { xmlFree(selectExpr); xsldbgGenericErrorFunc(i18n("Error: Cannot change a variable that does not use the select attribute.\n")); } } else xsldbgGenericErrorFunc(i18n("Error: Variable %1 was not found.\n").arg(xsldbgText(name))); xmlFree(name); } else xsldbgGenericErrorFunc(i18n("Error: Out of memory.\n")); } else { showUsage = 1; } if (showUsage == 1) xsldbgGenericErrorFunc(i18n("Error: Invalid arguments to command %1.\n").arg("set")); } return result; }
StyleParam::Value StyleParam::parseString(StyleParamKey key, const std::string& _value) { switch (key) { case StyleParamKey::extrude: { return parseExtrudeString(_value); } case StyleParamKey::text_wrap: { int textWrap; if (_value == "false") { return std::numeric_limits<uint32_t>::max(); } if (_value == "true") { return uint32_t(15); // DEFAULT } if (parseInt(_value, textWrap) > 0 && textWrap > 0) { return static_cast<uint32_t>(textWrap); } return std::numeric_limits<uint32_t>::max(); } case StyleParamKey::text_offset: case StyleParamKey::offset: { UnitVec<glm::vec2> vec; if (!parseVec2(_value, { Unit::pixel }, vec) || std::isnan(vec.value.y)) { LOGW("Invalid offset parameter '%s'.", _value.c_str()); } return vec.value; } case StyleParamKey::size: { UnitVec<glm::vec2> vec; if (!parseVec2(_value, { Unit::pixel }, vec)) { LOGW("Invalid size parameter '%s'.", _value.c_str()); } return vec.value; } case StyleParamKey::transition_hide_time: case StyleParamKey::transition_show_time: case StyleParamKey::transition_selected_time: case StyleParamKey::text_transition_hide_time: case StyleParamKey::text_transition_show_time: case StyleParamKey::text_transition_selected_time: { float time = 0.0f; if (!parseTime(_value, time)) { LOGW("Invalid time param '%s'", _value.c_str()); } return time; } case StyleParamKey::text_font_family: case StyleParamKey::text_font_weight: case StyleParamKey::text_font_style: { std::string normalized = _value; std::transform(normalized.begin(), normalized.end(), normalized.begin(), ::tolower); return normalized; } case StyleParamKey::anchor: case StyleParamKey::text_anchor: { LabelProperty::Anchors anchors; for (auto& anchor : splitString(_value, ',')) { if (anchors.count == LabelProperty::max_anchors) { break; } LabelProperty::Anchor labelAnchor; if (LabelProperty::anchor(anchor, labelAnchor)) { anchors.anchor[anchors.count++] = labelAnchor; } else { LOG("Invalid anchor %s", anchor.c_str()); } } return anchors; } case StyleParamKey::placement: { LabelProperty::Placement placement = LabelProperty::Placement::vertex; if (!LabelProperty::placement(_value, placement)) { LOG("Invalid placement parameter, Setting vertex as default."); } return placement; } case StyleParamKey::text_align: case StyleParamKey::text_source: case StyleParamKey::text_transform: case StyleParamKey::sprite: case StyleParamKey::sprite_default: case StyleParamKey::style: case StyleParamKey::outline_style: case StyleParamKey::repeat_group: case StyleParamKey::text_repeat_group: return _value; case StyleParamKey::text_font_size: { float fontSize = 0.f; if (!parseFontSize(_value, fontSize)) { LOGW("Invalid font-size '%s'.", _value.c_str()); } return fontSize; } case StyleParamKey::flat: case StyleParamKey::interactive: case StyleParamKey::text_interactive: case StyleParamKey::tile_edges: case StyleParamKey::visible: case StyleParamKey::text_visible: case StyleParamKey::outline_visible: case StyleParamKey::collide: case StyleParamKey::text_optional: case StyleParamKey::text_collide: if (_value == "true") { return true; } if (_value == "false") { return false; } LOGW("Invalid boolean value %s for key %s", _value.c_str(), StyleParam::keyName(key).c_str()); break; case StyleParamKey::text_order: LOGW("text:order parameter is ignored."); break; case StyleParamKey::order: case StyleParamKey::outline_order: case StyleParamKey::priority: case StyleParamKey::text_priority: { int num; if (parseInt(_value, num) > 0) { if (num >= 0) { return static_cast<uint32_t>(num); } } LOGW("Invalid '%s' value '%s'", keyName(key).c_str(), _value.c_str()); break; } case StyleParamKey::placement_spacing: { ValueUnitPair placementSpacing; placementSpacing.unit = Unit::pixel; int pos = parseValueUnitPair(_value, 0, placementSpacing); if (pos < 0) { LOGW("Invalid placement spacing value '%s'", _value.c_str()); placementSpacing.value = 80.0f; placementSpacing.unit = Unit::pixel; } else { if (placementSpacing.unit != Unit::pixel) { LOGW("Invalid unit provided for placement spacing"); } } return Width(placementSpacing); } case StyleParamKey::repeat_distance: case StyleParamKey::text_repeat_distance: { ValueUnitPair repeatDistance; repeatDistance.unit = Unit::pixel; int pos = parseValueUnitPair(_value, 0, repeatDistance); if (pos < 0) { LOGW("Invalid repeat distance value '%s'", _value.c_str()); repeatDistance.value = 256.0f; repeatDistance.unit = Unit::pixel; } else { if (repeatDistance.unit != Unit::pixel) { LOGW("Invalid unit provided for repeat distance"); } } return Width(repeatDistance); } case StyleParamKey::width: case StyleParamKey::outline_width: { ValueUnitPair width; width.unit = Unit::meter; int pos = parseValueUnitPair(_value, 0, width); if (pos < 0) { LOGW("Invalid width value '%s'", _value.c_str()); width.value = 2.0f; width.unit = Unit::pixel; } return Width(width); } case StyleParamKey::angle: { double num; if (_value == "auto") { return std::nanf("1"); } else if (parseFloat(_value, num) > 0) { return static_cast<float>(num); } break; } case StyleParamKey::miter_limit: case StyleParamKey::outline_miter_limit: case StyleParamKey::placement_min_length_ratio: case StyleParamKey::text_font_stroke_width: { double num; if (parseFloat(_value, num) > 0) { return static_cast<float>(num); } break; } case StyleParamKey::color: case StyleParamKey::outline_color: case StyleParamKey::text_font_fill: case StyleParamKey::text_font_stroke_color: return parseColor(_value); case StyleParamKey::cap: case StyleParamKey::outline_cap: return static_cast<uint32_t>(CapTypeFromString(_value)); case StyleParamKey::join: case StyleParamKey::outline_join: return static_cast<uint32_t>(JoinTypeFromString(_value)); default: break; } return none_type{}; }
// *************************************************************************** void CSkeletonSpawnScript::parseCache(CScene *scene, CSkeletonModel *skeleton) { uint i; nlassert(scene); nlassert(_Cache.empty() || skeleton); static std::vector<std::string> newLines; newLines.clear(); splitString(_Cache,"\n",newLines); // **** compare the 2 set of script line to know what to add, and what to remove. // NB: this is an O(N2), but the number of spawned objects should be small (0, 1 or 2 surely) static std::vector<bool> srcToRemove; static std::vector<bool> dstToAdd; srcToRemove.clear(); dstToAdd.clear(); srcToRemove.resize(_Instances.size(), true); dstToAdd.resize(newLines.size(), true); for(uint i=0;i<_Instances.size();i++) { for(uint j=0;j<newLines.size();j++) { // if the new line script is the same than the old one, then reuse! // NB: the script line contains an "instance number", so there is no risk of "reuse same twice" if(newLines[j] == _Instances[i].ScriptLine) { srcToRemove[i]= false; dstToAdd[j]= false; } } } // **** remove the no more used instances vector<CInstance>::iterator it= _Instances.begin(); for(i=0;i<srcToRemove.size();i++) { // if must remove this entry if(srcToRemove[i]) { // then erase the entry if(it->Model) scene->deleteInstance(it->Model); it= _Instances.erase(it); } else it++; } // **** create the new instances for(i=0;i<dstToAdd.size();i++) { // if not reused if(dstToAdd[i]) { // parse the line const std::string &line= newLines[i]; static std::vector<string> words; words.clear(); splitString(line, " ", words); if(words.size()>=3) { // command if(words[0]=="objw") { // format: "objw inst shapeName" // inst is a number only used to generate line difference (for cache comparison) _Instances.push_back(CInstance()); CInstance &inst= _Instances.back(); inst.ScriptLine= line; // Delay the model creation at end of CScene::render() CSSSModelRequest req; req.Skel= skeleton; req.InstanceId= (uint)_Instances.size()-1; req.Shape= words[2]; // World Spawned Objects are sticked to the root bone (for CLod hiding behavior) req.BoneId= 0; // but have a special feature to compute their world matrix req.SSSWO= true; addModelCreationRequest(req, scene); } else if(words[0]=="objl" && words.size()>=4) { // format: "objl inst shapeName boneName" // inst is a number only used to generate line difference (for cache comparison) // get the bone name, but may have space in its name => words[3] is not the correct name uint pos= 0; bool inWord= false; uint wordId= 0; // skip first spaces while(pos<line.size() && line[pos]==' ') pos++; // count word until reach while(pos<line.size()) { if(line[pos]!=' ') { if(!inWord) { inWord= true; wordId++; // reach bone name! stop if(wordId==4) break; } } else { inWord= false; } pos++; } // and get the bone name string boneName= line.substr(pos); // create _Instances.push_back(CInstance()); CInstance &inst= _Instances.back(); inst.ScriptLine= line; // try to get the bone id from name sint32 boneId= skeleton->getBoneIdByName(boneName); // if fails, then don't create the instance if(boneId>=0) { // Delay the model creation at end of CScene::render() CSSSModelRequest req; req.Skel= skeleton; req.InstanceId= (uint)_Instances.size()-1; req.Shape= words[2]; req.BoneId= boneId; req.SSSWO= false; addModelCreationRequest(req, scene); } else { // avoid flooding (animation) #ifdef NL_DEBUG nlwarning("ERROR: SkeletonSpawnScript: boneId not found in: %s", line.c_str()); #endif } } // unknown command else { // avoid flooding (animation) #ifdef NL_DEBUG nlwarning("ERROR: SkeletonSpawnScript: error in command: %s", line.c_str()); #endif } } } } }
/* *每个socket对应的线程的入口函数,客户端的socket信息处理.主要是区分web端和一般的lmt端 *此线程针对单独的客户端进行处理 */ void * proClientSocket(void *socketHandle) { bool bWebType = false; //是否为web类型 int iErrorCount = 0; //计数器 int i = 0; u_short iClientID = CARICCP_MAX_SHORT; CSocketHandle *socket_handle = ((CSocketHandle *) socketHandle); //SOCKET sock_client = socket_handle->sock_client;//此socket需要保持起来 //sockaddr_in addr_client = socket_handle->addr_client; //int nNetTimeout=3000;//3秒 //接收时限,此处设置会影响网络状态的情况判断 //setsockopt(sock_client,SOL_SOCKET,SO_RCVTIMEO,(char *)&nNetTimeout,sizeof(int)); //int nZero=0; //setsockopt(sock_client,SOL_SOCKET,SO_RCVBUF,(char *)&nZero,sizeof(int)); char *pClientIP; int sock_client = socket_handle->sock_client; //此socket需要保持起来 #if defined(_WIN32) || defined(WIN32) struct sockaddr_in addr_client = socket_handle->addr_client; pClientIP = inet_ntoa(addr_client.sin_addr); #else struct sockaddr addr_client = socket_handle->addr_client; //pClientIP = /*inet_ntoa(addr_client)*/addr_client.sa_data; //要获得client端的ip地址,必须把sockaddr结构强制转换成sockaddr_in结构,因为字节大小是相同的 pClientIP = inet_ntoa(((struct sockaddr_in *) (&addr_client))->sin_addr); //打印16进制的mac地址信息 //printf("%02x:%02x:%02x:%02x:%02x:%02x\n", // (unsigned char)addr_client.sa_data[0], // (unsigned char)addr_client.sa_data[1], // (unsigned char)addr_client.sa_data[2], // (unsigned char)addr_client.sa_data[3], // (unsigned char)addr_client.sa_data[4], // (unsigned char)addr_client.sa_data[5]); #endif //及时释放销毁当前socket句柄对象 CARI_CCP_VOS_DEL(socket_handle); switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "+++ begin :Succeed linked with client(IP :%s, socketID :%d).\n", pClientIP, sock_client); //定义socket的三元组 socket3element clientSocketElement;//是否需要新创建,每个线程独享的临时变量 initSocket3element(clientSocketElement); clientSocketElement.socketClient = sock_client;//保存此socket号 clientSocketElement.addr = addr_client; //方式1: 分配客户端号,此处预先分配好,等待client下发命令查询的时候直接返回即可 //iClientID = CModuleManager::getInstance()->assignClientID(); //clientSocketElement.sClientID = iClientID; //方式2: client下发命令的时候再进行分配,考虑到以前使用的id号能重用 //目前采用这种方式 //把此客户端的socket保存起来 CModuleManager::getInstance()->saveSocket(clientSocketElement); //switch_status_t ret; int recvbytes = 0;//命名接收处理结果 #ifdef WIN32 #else //test 字符转换 CodeConverter cc = CodeConverter("gb2312","UTF-8"); #endif //针对于固定的客户端,对应的线程一直循环处理,设置时限/监测连接是否正常 while (loopFlag){//使用循环标识控制 bool bWeb = false; char recvBuf[sizeof(common_CmdReq_Frame)]; memset(recvBuf, 0, sizeof(recvBuf)); recvbytes = recv(sock_client, recvBuf, sizeof(recvBuf), 0); //要保证是阻塞模式的,如果客户端(异常)退出,会导致死循环 //网络出现异常,网络中断 if (-1 == recvbytes) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "--- end :Disconnect with client (IP :%s, socketID :%d)! \n", pClientIP, sock_client); break; } //收到的数据帧错误或客户端退出,或者初始建立连接,此时收到的数据帧的大小都是0 if (0 == recvbytes) { iErrorCount ++; //连续收到不正确的数据N次,就要退出循环,重新等待客户端的连接 if (CARICCP_MAX_ERRRORFRAME_COUNT < iErrorCount) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "--- end :Client %s already exited.\n", pClientIP); iErrorCount = 0; break; } continue; } //shutdown指令 if (shutdownFlag){ break; } ////////////////////////////////////////////////////////////////////////// //帧的销毁遵守:谁调用谁负责销毁!!!!!!!!!!!!!!!!!!! //关键的命令逻辑处理,逆解析来自客户端的请求帧 //新建客户端的请求帧,由调用者负责清除 common_CmdReq_Frame *clientReqFrame = CARI_CCP_VOS_NEW(common_CmdReq_Frame); initCommonRequestFrame(clientReqFrame); //add by xxl 2010-5-5: 需要判断一下此命令是来自web还是一般的client if(!bWebType){ char chHeader = recvBuf[0]; if ('[' ==chHeader){//判断是否为web发送的命令格式 bWeb = true; } } //需要重新解析构造请求帧,根据字符串进行转换 if (bWebType || bWeb){ string strres = recvBuf,strHeader,strCmd,strParam,strVal,strName; int ival =0; int index = strres.find_first_of("]"); strHeader = strres.substr(1,index-1); strCmd= strres.substr(index+1); //1 先构造消息头 vector<string> resultVec; splitString(strHeader, ",", resultVec); vector<string>::const_iterator it = resultVec.begin(); for (;it != resultVec.end(); it++){ strVal = *it; index = strVal.find_first_of("="); if (0 < index){ strName = strVal.substr(0,index); strVal = strVal.substr(index+1); trim(strName); trim(strVal); //解析关键的参数 if(isEqualStr("clientID",strName)){ clientReqFrame->header.sClientID = 0;//web的比较固定 } else if(isEqualStr("modId",strName)){ clientReqFrame->header.sClientChildModID = stringToInt(strVal.c_str()); } else if(isEqualStr("cmdID",strName)){ clientReqFrame->body.iCmdCode = stringToInt(strVal.c_str()); } else if(isEqualStr("logUserName",strName)){ myMemcpy(clientReqFrame->header.strLoginUserName,strVal.c_str(),strVal.length()); } } }//end for //2 再解析命令名和参数区 strName = ""; trim(strCmd); index = strCmd.find_first_of(":"); if (0 < index){ strName = strCmd.substr(0,index); strParam = strCmd.substr(index+1); } else{ strParam = strCmd; } myMemcpy(clientReqFrame->body.strCmdName,strName.c_str(),strName.length()); myMemcpy(clientReqFrame->param.strParamRegion,strParam.c_str(),CARICCP_MIN(strParam.length(),CARICCP_MAX_LENGTH)); //3 其他区域的初始化 clientReqFrame->body.bSynchro = 1; clientReqFrame->header.sClientID = 0;//web的比较固定 //4 重新设置socket,只需要设置一次即可 if(!bWebType){ bWebType = true; //重新设置clientID号 CModuleManager::getInstance()->eraseSocket(clientSocketElement.socketClient); clientSocketElement.sClientID = 0;//默认情况为CARICCP_MAX_SHORT CModuleManager::getInstance()->saveSocket(clientSocketElement); } } else{//一般的lmt,按照以前的方式处理 memcpy(clientReqFrame,recvBuf,sizeof(recvBuf)); } //add by xxl 2010-5-5 end //char strParamRegion[CARICCP_MAX_LENGTH]; #ifdef WIN32 #else //printf("before: %s\n",clientReqFrame->param.strParamRegion); ////test 字符转换 //char out[CARICCP_MAX_LENGTH]; //memset(out,0,sizeof(out)); //cc.convert(clientReqFrame->param.strParamRegion, CARICCP_MAX_LENGTH,out,CARICCP_MAX_LENGTH); //printf("convert: %s\n",out); //memset(clientReqFrame->param.strParamRegion,0,sizeof(clientReqFrame->param.strParamRegion)); //myMemcpy(clientReqFrame->param.strParamRegion,out,sizeof(out)); //printf("after: %s\n",clientReqFrame->param.strParamRegion); #endif //如果此命令执行时间过长,此处会产生阻塞,当前客户端一直收不到信息!!!!!!!!! //如果再另起线程处理,将不能保证命令执行的有序性,所以上述情况还是较少的 //不必再过多考虑!!!! //由请求帧的处理模块(入口函数)负责细节处理 //帧的销毁遵守:谁调用谁负责销毁!!!!!!!!!!!!!!!!!!!!!! CMsgProcess::getInstance()->proCmd(sock_client, clientReqFrame); //结果集合的发送不再此处设计,直接放到对应的syncProCmd函数中 //另外,如果结果集分块发送显示,此处也不适合 //发送send单独考虑 //如何保证结果集能正确的发送给对应的客户端呢??? iErrorCount = 0; }//end while(client端循环获得请求帧) //如果是强制退出(shutdown命令操作),不需要考虑释放client id号等 if (!shutdownFlag){ //先释放client id号 CModuleManager::getInstance()->releaseClientIDBySocket(sock_client); //下面进行清除客户端连接,从保存的容器中清除掉 CModuleManager::getInstance()->eraseSocket(sock_client); //关闭当前客户端的socket CARI_CLOSE_SOCKET(sock_client); } //登录的用户数量减少 global_client_num--; //线程实例清除掉 //CModuleManager::getInstance()->eraseThrd(sock_client); //退出重连接的线程 //pthread_exit(NULL); return NULL; //return也会导致本函数所在的线程退出 }
bool SBMLModelSimulation::LoadSettings(const string& settingsFName) { string fName(settingsFName); if(!fName.size()) { Log(Logger::LOG_ERROR)<<"Empty file name for setings file"; return false; } else { map<string, string> settings; map<string, string>::iterator it; //Read each line in the settings file vector<string> lines = getLinesInFile(fName); for(u_int i = 0; i < lines.size(); i++) { vector<string> line = splitString(lines[i], ":"); if(line.size() == 2) { settings.insert( pair<string, string>(line[0], line[1])); } else { Log(lDebug2)<<"Empty line in settings file: "<<lines[i]; } } Log(lDebug3)<<"Settings File ============="; for (it = settings.begin() ; it != settings.end(); it++ ) { Log(lDebug) << (*it).first << " => " << (*it).second; } Log(lDebug)<<"==========================="; //Assign values it = settings.find("start"); mSettings.start = (it != settings.end()) ? toDouble((*it).second) : 0; it = settings.find("duration"); mSettings.duration = (it != settings.end()) ? toDouble((*it).second) : 0; it = settings.find("steps"); mSettings.steps = (it != settings.end()) ? toInt((*it).second) : 50; it = settings.find("absolute"); mSettings.absolute = (it != settings.end()) ? toDouble((*it).second) : 1.e-7; it = settings.find("relative"); mSettings.relative = (it != settings.end()) ? toDouble((*it).second) : 1.e-4; it = settings.find("variables"); if(it != settings.end()) { vector<string> vars = splitString((*it).second, ","); for(u_int i = 0; i < vars.size(); i++) { mSettings.variables.push_back(trim(vars[i])); } } it = settings.find("amount"); if(it != settings.end()) { vector<string> vars = splitString((*it).second, ","); for(u_int i = 0; i < vars.size(); i++) { string rec = trim(vars[i]); if(rec.size()) { mSettings.amounts.push_back(rec); } } } it = settings.find("concentration"); if(it != settings.end()) { vector<string> vars = splitString((*it).second, ","); for(u_int i=0; i < vars.size(); i++) { string rec = trim(vars[i]); if(rec.size()) { mSettings.concentrations.push_back(rec); } } } } if(mEngine) { mEngine->setSimulateOptions(mSettings); } return true; }
/******************************************************************* * recorders */ EXPORT int open_recorder(struct recorder *my, char *fname, char *flags) { char32 extension; char1024 columnlist; char **columns; time_t now=time(NULL); OBJECT *obj=OBJECTHDR(my); static int block=0; set_recorder(my); if (!block) { atexit(close_recorder_wrapper); block=1; } columns = (char **)calloc(MAXCOLUMNS, sizeof(char *)); for(int i=0; i<MAXCOLUMNS; i++){ columns[i] = (char *)malloc(33); memset(columns[i],'\0',32); } my->fp = (strcmp(fname,"-")==0?stdout:fopen(fname,flags)); if (my->fp==NULL) { //gl_error( fprintf(stderr, "recorder file %s: %s", fname, strerror(errno)); my->status = TS_DONE; return 0; } my->type = FT_FILE; my->last.ts = TS_ZERO; my->status=TS_OPEN; my->samples=0; /* put useful header information in file first */ fprintf(my->fp,"# file...... %s\n", my->file); fprintf(my->fp,"# date...... %s", asctime(localtime(&now))); #ifdef WIN32 fprintf(my->fp,"# user...... %s\n", getenv("USERNAME")); fprintf(my->fp,"# host...... %s\n", getenv("MACHINENAME")); #else fprintf(my->fp,"# user...... %s\n", getenv("USER")); fprintf(my->fp,"# host...... %s\n", getenv("HOST")); #endif fprintf(my->fp,"# target.... %s %d\n", obj->parent->oclass->name, obj->parent->id); fprintf(my->fp,"# trigger... %s\n", my->trigger[0]=='\0'?"(none)":my->trigger); fprintf(my->fp,"# interval.. %d\n", my->interval); fprintf(my->fp,"# limit..... %d\n", my->limit); fprintf(my->fp,"# timestamp,%s\n", my->property); /* Split the property list into items */ splitString(my->property, columns); /* Array 'columns' contains the separated items from the property list for (int i=0;i<MAXCOLUMNS;i++){ if (strlen(columns[i])>0) fprintf(my->fp,"%s\n",columns[i]); } */ /* Put gnuplot commands in the header portion */ fprintf(my->fp,"# GNUplot commands below: \n"); switch (my->output) { case SCREEN: #ifdef WIN32 fprintf(my->fp, "set terminal windows color;\n"); #else fprintf(my->fp, "set terminal x11;\n"); #endif break; case EPS: fprintf(my->fp, "set terminal epslatex;\n"); strcpy(extension, "EPS"); break; case GIF: fprintf(my->fp, "set terminal gif;\n"); strcpy(extension, "GIF"); break; case JPG: fprintf(my->fp, "set terminal jpeg;\n"); strcpy(extension, "JPG"); break; case PDF: fprintf(my->fp, "set terminal pdf;\n"); strcpy(extension, "PDF"); break; case PNG: fprintf(my->fp, "set terminal png;\n"); strcpy(extension, "PNG"); break; case SVG: fprintf(my->fp, "set terminal svg;\n"); strcpy(extension, "SVG"); break; default: fprintf(my->fp, "set terminal jpeg;\n"); strcpy(extension, "JPG"); break; } write_default_plot_commands_rec(my, extension); if (my->columns[0]){ sscanf(my->columns,"%s %s", columnlist); fprintf(my->fp, "plot \'-\' using %s with lines;\n", columnlist); } free(columns); return 1; }
static KEY_NAME_TABLES_REFERENCE getKeyNameTables (const char *keyTableName) { KEY_NAME_TABLES_REFERENCE keyNameTables = NULL; int componentsLeft; char **nameComponents = splitString(keyTableName, '-', &componentsLeft); if (nameComponents) { char **currentComponent = nameComponents; if (componentsLeft) { const char *keyTableType = (componentsLeft--, *currentComponent++); if (strcmp(keyTableType, "kbd") == 0) { if (componentsLeft) { componentsLeft--; currentComponent++; keyNameTables = KEY_NAME_TABLES(keyboard); } else { logMessage(LOG_ERR, "missing keyboard bindings name"); } } else if (strcmp(keyTableType, "brl") == 0) { if (componentsLeft) { void *driverObject; const char *driverCode = (componentsLeft--, *currentComponent++); if (loadBrailleDriver(driverCode, &driverObject, opt_driversDirectory)) { char *keyTablesSymbol; { const char *strings[] = {"brl_ktb_", driverCode}; keyTablesSymbol = joinStrings(strings, ARRAY_COUNT(strings)); } if (keyTablesSymbol) { const KeyTableDefinition *const *keyTableDefinitions; if (findSharedSymbol(driverObject, keyTablesSymbol, &keyTableDefinitions)) { const KeyTableDefinition *const *currentDefinition = keyTableDefinitions; if (componentsLeft) { const char *bindingsName = (componentsLeft--, *currentComponent++); while (*currentDefinition) { if (strcmp(bindingsName, (*currentDefinition)->bindings) == 0) { keyNameTables = (*currentDefinition)->names; break; } currentDefinition += 1; } if (!keyNameTables) { logMessage(LOG_ERR, "unknown %s braille driver bindings name: %s", driverCode, bindingsName); } } else { logMessage(LOG_ERR, "missing braille driver bindings name"); } } free(keyTablesSymbol); } else { logMallocError(); } } } else { logMessage(LOG_ERR, "missing braille driver code"); } } else { logMessage(LOG_ERR, "unknown key table type: %s", keyTableType); } } else { logMessage(LOG_ERR, "missing key table type"); } } if (keyNameTables) { if (componentsLeft) { logMessage(LOG_ERR, "too many key table name components"); keyNameTables = NULL; } } deallocateStrings(nameComponents); return keyNameTables; }
nsresult nsAbOutlookCard::Init(const char *aUri) { nsresult retCode = nsRDFResource::Init(aUri) ; NS_ENSURE_SUCCESS(retCode, retCode) ; nsCAutoString entry ; nsCAutoString stub ; mAbWinType = getAbWinType(kOutlookCardScheme, mURI.get(), stub, entry) ; if (mAbWinType == nsAbWinType_Unknown) { PRINTF(("Huge problem URI=%s.\n", mURI.get())) ; return NS_ERROR_INVALID_ARG ; } nsAbWinHelperGuard mapiAddBook (mAbWinType) ; if (!mapiAddBook->IsOK()) { return NS_ERROR_FAILURE ; } mMapiData->Assign(entry) ; nsStringArray unichars ; ULONG i = 0 ; if (mapiAddBook->GetPropertiesUString(*mMapiData, OutlookCardMAPIProps, index_LastProp, unichars)) { SetFirstName(*unichars[index_FirstName]); SetLastName(*unichars[index_LastName]); SetDisplayName(*unichars[index_DisplayName]); SetNickName(*unichars[index_NickName]); SetPrimaryEmail(*unichars[index_EmailAddress]); SetWorkPhone(*unichars[index_WorkPhoneNumber]); SetHomePhone(*unichars[index_HomePhoneNumber]); SetFaxNumber(*unichars[index_WorkFaxNumber]); SetPagerNumber(*unichars[index_PagerNumber]); SetCellularNumber(*unichars[index_MobileNumber]); SetHomeCity(*unichars[index_HomeCity]); SetHomeState(*unichars[index_HomeState]); SetHomeZipCode(*unichars[index_HomeZip]); SetHomeCountry(*unichars[index_HomeCountry]); SetWorkCity(*unichars[index_WorkCity]); SetWorkState(*unichars[index_WorkState]); SetWorkZipCode(*unichars[index_WorkZip]); SetWorkCountry(*unichars[index_WorkCountry]); SetJobTitle(*unichars[index_JobTitle]); SetDepartment(*unichars[index_Department]); SetCompany(*unichars[index_Company]); SetWebPage1(*unichars[index_WorkWebPage]); SetWebPage2(*unichars[index_HomeWebPage]); SetNotes(*unichars[index_Comments]); } ULONG cardType = 0 ; nsCAutoString normalChars ; if (mapiAddBook->GetPropertyLong(*mMapiData, PR_OBJECT_TYPE, cardType)) { SetIsMailList(cardType == MAPI_DISTLIST) ; if (cardType == MAPI_DISTLIST) { buildAbWinUri(kOutlookDirectoryScheme, mAbWinType, normalChars) ; normalChars.Append(entry) ; SetMailListURI(normalChars.get()) ; } } nsAutoString unichar ; nsAutoString unicharBis ; if (mapiAddBook->GetPropertyUString(*mMapiData, PR_HOME_ADDRESS_STREET_W, unichar)) { splitString(unichar, unicharBis) ; SetHomeAddress(unichar) ; SetHomeAddress2(unicharBis) ; } if (mapiAddBook->GetPropertyUString(*mMapiData, PR_BUSINESS_ADDRESS_STREET_W, unichar)) { splitString(unichar, unicharBis) ; SetWorkAddress(unichar) ; SetWorkAddress2(unicharBis) ; } WORD year = 0 ; WORD month = 0 ; WORD day = 0 ; if (mapiAddBook->GetPropertyDate(*mMapiData, PR_BIRTHDAY, year, month, day)) { wordToUnicode(year, unichar); SetBirthYear(unichar); wordToUnicode(month, unichar); SetBirthMonth(unichar); wordToUnicode(day, unichar); SetBirthDay(unichar); } return retCode ; }
int readQueries(const std::string& queryList, std::vector<std::string>& queries){ splitString(queryList, ';', queries); return 0; }
bool Risiko::createFromFile(char* file) { string filename="felder/"; filename.append(file); ifstream datei; datei.open(filename.c_str(),ios::in); if(datei.is_open()) { bool inhalt=false; bool grenzen=false; string inhaltzeile; char buffer[512]; while(datei.getline(buffer,sizeof(buffer))) { inhaltzeile=buffer; buffer[0]='\0'; if(!trim(inhaltzeile)) //Wenn nach Kürzen nurnoch leere Zeile continue; //cout << "String: " << inhaltzeile << " ,Länge: " <<inhaltzeile.size() << endl; if(inhaltzeile == "[Land]") { inhalt=true; grenzen=false; continue; } else if(inhaltzeile == "[Grenzen]") { inhalt=false; grenzen=true; continue; } if(inhalt) { vector<string> p; if(splitString(inhaltzeile, p, " \t",0)==2) { string s= p[0];//Name des Lands // replace (s.begin(),s.end(),'_',' '); int i = atoi(p[1].c_str()); //Nummer des Kontinents felder.setNode(s,i); //cout << "Erstelle Land:" << p[0] <<" Index:" << felder.getNumNodes () << endl; continue; } } else if(grenzen) { vector<string> p; int c; if((c=splitString(inhaltzeile, p, " \t",0))!=0) { int i=atoi(p[0].c_str()); while(p.size()>1) { string s = p.at(p.size()-1); felder.setEdge(i,atoi(s.c_str())); p.pop_back(); } // cout << "Setze Grenze zwischen Land " << felder.getNode(i)->getId() << " und " << felder.getNode(j)->getId() <<endl; continue; } } if(datei.eof() || datei.fail()) { break; } } cout << felder.getMap()<<endl; if(rd->storefile("map",felder.getMap())) return true; return false; } else { cerr << "Konnte Map-File: " <<filename << " nicht öffnen" << endl; return false; } }
Tags::Tags(const std::string tags) { std::vector<std::string> strings = splitString(tags, ','); for (auto& strings_it : strings) { addTag(Tag(trim(strings_it))); } }
void CIdentifierStorage::requestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback) { auto pair = splitString(name.String(), ':'); // remoteScope:name requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback)); }
/******************************************************************* * collectors */ EXPORT int open_collector(struct collector *my, char *fname, char *flags) { unsigned int count=0; time_t now=time(NULL); char32 extension; char1024 columnlist; char **columns; OBJECT *obj=OBJECTHDR(my); columns = (char **)calloc(MAXCOLUMNS, sizeof(char *)); for(int i=0; i<MAXCOLUMNS; i++){ columns[i] = (char *)malloc(33); memset(columns[i],'\0',32); } my->fp = (strcmp(fname,"-")==0?stdout:fopen(fname,flags)); if (my->fp==NULL) { //gl_error( fprintf(stderr, "collector file %s: %s", fname, strerror(errno)); my->status = TS_DONE; return 0; } my->last.ts = TS_ZERO; my->status=TS_OPEN; my->type = FT_FILE; my->samples=0; /* put useful header information in file first */ count += fprintf(my->fp,"# file...... %s\n", my->file); count += fprintf(my->fp,"# date...... %s", asctime(localtime(&now))); #ifdef WIN32 count += fprintf(my->fp,"# user...... %s\n", getenv("USERNAME")); count += fprintf(my->fp,"# host...... %s\n", getenv("MACHINENAME")); #else count += fprintf(my->fp,"# user...... %s\n", getenv("USER")); count += fprintf(my->fp,"# host...... %s\n", getenv("HOST")); #endif count += fprintf(my->fp,"# group..... %s\n", my->group); count += fprintf(my->fp,"# trigger... %s\n", my->trigger[0]=='\0'?"(none)":my->trigger); count += fprintf(my->fp,"# interval.. %d\n", my->interval); count += fprintf(my->fp,"# limit..... %d\n", my->limit); count += fprintf(my->fp,"# property.. timestamp,%s\n", my->property); splitString(my->property, columns); /* Put gnuplot commands in the header portion */ fprintf(my->fp,"# GNUplot commands below: \n"); switch (my->output) { case SCREEN: #ifdef WIN32 fprintf(my->fp, "set terminal windows color;\n"); #else fprintf(my->fp, "set terminal x11;\n"); #endif break; case EPS: fprintf(my->fp, "set terminal epslatex;\n"); strcpy(extension, "EPS"); break; case GIF: fprintf(my->fp, "set terminal gif;\n"); strcpy(extension, "GIF"); break; case JPG: fprintf(my->fp, "set terminal jpeg;\n"); strcpy(extension, "JPG"); break; case PDF: fprintf(my->fp, "set terminal pdf;\n"); strcpy(extension, "PDF"); break; case PNG: fprintf(my->fp, "set terminal png;\n"); strcpy(extension, "PNG"); break; case SVG: fprintf(my->fp, "set terminal svg;\n"); strcpy(extension, "SVG"); break; default: fprintf(my->fp, "set terminal jpeg;\n"); strcpy(extension, "JPG"); break; } write_default_plot_commands_col(my, extension); if (my->columns){ sscanf(my->columns,"%s %s", columnlist); fprintf(my->fp, "plot \'-\' using %s with lines;\n", columnlist); } free(columns); return count; }
string Markovsky::Reply(string message) { FilterMessage(message); string replystring; vector<string> curlines; splitString(message, curlines, ". "); vector<string> curwords; int sz, i; for (sz = curlines.size(), i = 0; i < sz; i++) { tokenizeString(curlines[i], curwords); } if (curwords.empty()) return replystring; // Filter out the words we don't know about int known = -1; vector<string> index; for (sz = curwords.size(), i = 0; i < sz; i++) { string &x = curwords[i]; if (words.find(x) == words.end()) continue; int k = words[x].size(); if ((known == -1) || (k < known)) { index.clear(); index.push_back(x); known = k; } else if (k == known) { index.push_back(x); } } if (index.empty()) return replystring; deque<string> sentence; // pick a random word to start building the reply int x = rand() % (index.size()); sentence.push_back(index[x]); // Build on the left edge bool done = false; while (!done) { // cline = line, w = word number int c = this->words[sentence[0]].size(); context_t l = this->words[sentence[0]][rand() % (c)]; int w = l.second; // NOTE: cline is needed since tokenizeString messes with its arguments string cline = *(l.first); vector<string> cwords; tokenizeString (cline, cwords); int depth = rand() % (max_context_depth - min_context_depth) + min_context_depth; for (int i = 1; i <= depth; i++) { if ((w - i) < 0) { done = true; break; } else { sentence.push_front(cwords[w-i]); } if ((w - i) == 0) { done = true; break; } } } // Build on the right edge done = false; while (!done) { if (words.find(sentence.back()) == words.end()) { printf ("%s:%i: words.find(sentence.back()) == words.end()\n", __FILE__, __LINE__); } int c = this->words[sentence.back()].size(); context_t l = this->words[sentence.back()][rand() % (c)]; int w = l.second; string cline = *(l.first); vector<string> cwords; tokenizeString (cline, cwords); int depth = rand() % (max_context_depth - min_context_depth) + min_context_depth; for (int i = 1; i <= depth; i++) { if ((w + i) >= cwords.size()) { done = true; break; } else { sentence.push_back(cwords[w+i]); } } } for (i = 0, sz = sentence.size() - 1; i < sz; i++) { replystring += sentence[i]; replystring += ' '; } replystring += sentence.back(); return replystring; }
void loadObj(const string& fileName, const D3DXCOLOR& color, float scale, vector<Vertex>& vertices, unsigned int normalCount, unsigned int positionCount, unsigned int texCoordCount, unsigned int vertexCount) { vertices.reserve(vertexCount); ifstream inputFileStream(fileName.c_str()); if (inputFileStream.fail()) { throw exception(); } char* rawSplit = new char[MAX_SPLIT_LENGTH]; vector<string> lines = splitString(rawSplit, inputFileStream, '\n', normalCount + positionCount + texCoordCount + vertexCount / 3 + 50); vector<vector<string> > faces; faces.reserve(vertexCount / 3); vector<D3DXVECTOR3> normals; normals.reserve(normalCount); vector<D3DXVECTOR3> positions; positions.reserve(positionCount); vector<D3DXVECTOR2> texCoords; texCoords.reserve(texCoordCount); for (unsigned int lineIndex = 0; lineIndex < lines.size(); lineIndex++) { if (lines[lineIndex].empty()) { continue; } istringstream inputLineStream(lines[lineIndex]); vector<string> splitLine = splitString(rawSplit, inputLineStream, ' ', 4); if (splitLine[0] == "v") { D3DXVECTOR3 position( (float) atof(splitLine[1].c_str()) * scale, (float) atof(splitLine[2].c_str()) * scale, (float) atof(splitLine[3].c_str()) * scale); positions.push_back(position); } else if (splitLine[0] == "vn") { D3DXVECTOR3 normal( (float) atof(splitLine[1].c_str()), (float) atof(splitLine[2].c_str()), (float) atof(splitLine[3].c_str())); normals.push_back(normal); } else if (splitLine[0] == "vt") { D3DXVECTOR2 texCoord( (float) atof(splitLine[1].c_str()), 1.0f - (float) atof(splitLine[2].c_str())); texCoords.push_back(texCoord); } else if (splitLine[0] == "f") { faces.push_back(splitLine); } } // Read the faces from the file and populate the arrays. for (unsigned int faceIndex = 0; faceIndex < faces.size(); faceIndex++) { vector<string> face = faces[faceIndex]; for (unsigned int vertexIndex = 1; vertexIndex < face.size() - 1; vertexIndex++) { istringstream inputFaceStream(face[vertexIndex]); vector<string> splitVertex = splitString(rawSplit, inputFaceStream, '/', 3); Vertex vertex; vertex.color = color; if (!normals.empty()) { vertex.normal = normals[atoi(splitVertex[2].c_str()) - 1]; } vertex.position = positions[atoi(splitVertex[0].c_str()) - 1]; if (!texCoords.empty()) { vertex.texCoord = texCoords[atoi(splitVertex[1].c_str()) - 1]; } vertices.push_back(vertex); } // Create face normals if none were provided. if (normals.empty()) { unsigned int vertexCount = vertices.size(); D3DXVECTOR3 edge0 = vertices[vertexCount - 1].position - vertices[vertexCount - 2].position; D3DXVECTOR3 edge1 = vertices[vertexCount - 1].position - vertices[vertexCount - 3].position; D3DXVECTOR3 faceNormal; D3DXVec3Cross(&faceNormal, &edge0, &edge1); D3DXVec3Normalize(&faceNormal, &faceNormal); vertices[vertexCount - 1].normal = faceNormal; vertices[vertexCount - 2].normal = faceNormal; vertices[vertexCount - 3].normal = faceNormal; } } delete rawSplit; }
void loadVtk_old(string path, VRTransformPtr res) { cout << "load VTK file " << path << endl; ifstream file(path.c_str()); string line; auto next = [&]() -> string& { getline(file, line); return line; }; VTKProject project; project.version = splitString( next() )[4]; project.title = next(); project.format = next(); project.dataset = splitString( next() )[1]; VRGeoData geo; // build geometry if (project.dataset == "STRUCTURED_POINTS") { auto r = splitString( next() ); Vec3i dims = toValue<Vec3i>( r[1] + " " + r[2] + " " + r[3] ); r = splitString( next() ); Vec3d p0 = toValue<Vec3d>( r[1] + " " + r[2] + " " + r[3] ); r = splitString( next() ); Vec3d d = toValue<Vec3d>( r[1] + " " + r[2] + " " + r[3] ); for (int k=0; k<dims[2]; k++) { for (int j=0; j<dims[1]; j++) { for (int i=0; i<dims[0]; i++) { geo.pushVert(p0 + Vec3d(d[0]*i, d[1]*j, d[2]*k) ); geo.pushPoint(); } } } } if (project.dataset == "STRUCTURED_GRID") { auto r = splitString( next() ); Vec3i dims = toValue<Vec3i>( r[1] + " " + r[2] + " " + r[3] ); r = splitString( next() ); int N = toInt(r[1]); string type = r[2]; // points vector<Vec3d> points; for (int i=0; i<N; i++) { Vec3d p = toValue<Vec3d>( next() ); points.push_back(p); geo.pushVert(p); geo.pushPoint(); } } if (project.dataset == "RECTILINEAR_GRID") { ; } if (project.dataset == "UNSTRUCTURED_GRID") { ; } if (project.dataset == "POLYDATA") { auto r = splitString( next() ); int N = toInt(r[1]); string type = r[2]; // points for (int i=0; i<N; i++) geo.pushVert( toValue<Vec3d>( next() ) ); while (next() != "") { r = splitString( line ); string type = r[0]; N = toInt(r[1]); //int size = toInt(r[2]); for (int i=0; i<N; i++) { // for each primitive r = splitString( next() ); int Ni = toInt(r[0]); // length of primitive cout << line << " " << Ni << endl; //if (Ni == 2) geo.pushLine(toInt(r[1]), toInt(r[2])); if (Ni == 3) geo.pushTri(toInt(r[1]), toInt(r[2]), toInt(r[3])); if (Ni == 4) geo.pushQuad(toInt(r[1]), toInt(r[2]), toInt(r[3]), toInt(r[4])); } } } if (project.dataset == "FIELD") { ; } // parsing finished cout << project.toString() << endl; file.close(); auto m = VRMaterial::create(project.title + "_mat"); m->setLit(0); m->setDiffuse(Color3f(0.3,0.7,1.0)); VRGeometryPtr g = geo.asGeometry(project.title); g->setMaterial(m); //g->updateNormals(); res->addChild( g ); }