void PathGenerate::findFaceImage(string id_temp, string path) { DIR *dp; struct dirent *dirp; string temp; if ((dp = opendir(path.c_str())) == NULL) { cout << "Error(" << errno << ") opening " << face_training << endl; return; } while ((dirp = readdir(dp)) != NULL) { temp = string(dirp->d_name); if ((temp.compare(".") != 0) && (temp.compare("..") != 0)) { temp = path + "/" + temp; if (checkPath(temp) == 2) { files.push_back(temp); id.push_back(id_temp); } } } savePath(); closedir(dp); return; }
Common::StringArray DefaultSaveFileManager::listSavefiles(const Common::String &pattern) { Common::String savePathName = getSavePath(); checkPath(Common::FSNode(savePathName)); if (getError().getCode() != Common::kNoError) return Common::StringArray(); // recreate FSNode since checkPath may have changed/created the directory Common::FSNode savePath(savePathName); Common::FSDirectory dir(savePath); Common::ArchiveMemberList savefiles; Common::StringArray results; Common::String search(pattern); if (dir.listMatchingMembers(savefiles, search) > 0) { for (Common::ArchiveMemberList::const_iterator file = savefiles.begin(); file != savefiles.end(); ++file) { results.push_back((*file)->getName()); } } return results; }
Hdf5Dataset::Hdf5Dataset(std::string fullpath) { std::stringstream fp(fullpath); std::string segment; std::vector<std::string> seglist; char the_path[256]; while(std::getline(fp, segment, '/')) { seglist.push_back(segment); } std::ostringstream oss_file; oss_file<< seglist.back(); this->filename_ = oss_file.str(); seglist.pop_back(); std::ostringstream oss_path; if (!seglist.empty()) { std::copy(seglist.begin(), seglist.end()-1, std::ostream_iterator<std::string>(oss_path, "/")); oss_path << seglist.back(); oss_path<<"/"; } else { getcwd(the_path, 255); strcat(the_path, "/"); oss_path << the_path; } this->path_ = oss_path.str(); checkPath(this->path_); checkfilename(this->filename_); }
void CPathFinder::bruteForceSearch(std::vector<bool> &visited, std::vector<size_t> &way, double &wayLength, std::vector<size_t> &bestWay, double &bestWayLength) const { if (way.size() == pointsAmount) { way.push_back(way[0]); double wayLength = checkPath(way); if (wayLength < bestWayLength || bestWayLength < 0) { bestWay = way; bestWayLength = wayLength; } way.pop_back(); } else { for (size_t i = 0; i < pointsAmount; ++i) { if (!visited[i]) { double newLength = 0; if (!way.empty()) { newLength = wayLength + calculateDistance(points[*(way.end() - 1)], points[i]); } if (newLength >= bestWayLength && bestWayLength >= 0) { continue; } visited[i] = true; way.push_back(i); bruteForceSearch(visited, way, newLength, bestWay, bestWayLength); way.pop_back(); visited[i] = false; } } } }
void WireCreator::calcPathes() { QVector<int> vec={0, 1, 2, 4, 2, 3}; qDebug()<<"vec:"<<vec; qDebug()<<"test"<<containsAllE(vec); auto nextPoint=deadEnds[0]; auto nextEdge=edges[0]; for(auto edge: edges){ if(edge.first==nextPoint || edge.second==nextPoint) nextEdge=edge; } QVector<int> currPath; currPath<<nextPoint; QVector<QPair<int,int>> usedEdges; calcAllPathes(currPath, usedEdges, nextEdge); for(auto p: allPathes){ qDebug()<<checkPath(p); if(allPathes.length())break; } }
void checkPath(int **graph, int path[], int pos) { // Check if we came to a desired position if (path[pos-1] == stop_vertex) { if (pos == max_pos) { numpaths++; printf("Paths found so far: %d\n", numpaths); } return; } int v; for (v = 0; v < graph_len; v++) { // If this element is adjancent to the previous one // ...go this path recursively if (graph[ path[pos-1] ][v] == 1) { // Check if vertex is already added int i; int cont = 0; for (i = 0; i < pos; i++) { if (path[i] == v) { cont = 1; break; } } if (cont == 1) continue; path[pos] = v; checkPath(graph, path, pos+1); path[pos] = -1; } } }
int main() { FILE *fp; /* Standard 파일 구조체 */ int t, m, n, i; point start; /* 나이트 첫 위치 */ fp = fopen("input.txt", "r"); /* 파일 읽기 모드 */ if (fp == NULL) return -1; /* 예외 처리 */ fscanf(fp, "%d", &t); /* 데이터의 갯수 읽음 */ while (t--) { fscanf(fp, "%d %d %d %d", &m, &n, &start.y, &start.x); /* 데이터 읽음 */ memset(board, 0, sizeof(int)*(MAXSIZE*MAXSIZE)); /* 체스판 초기화 */ memset(path, 0, sizeof(int)*(MAXSIZE*MAXSIZE)); /* 투어 경로 초기화 */ board[start.y][start.x] = MARK; /* 시작 위치 표시 */ path[start.y][start.x] = 1; /* 투어 경로 표시 */ knightTour(m, n, start, 1); /* 나이트 투어 */ if(checkPath(m,n)) printTour(m, n); /* 투어 경로 존재시 출력 */ else printf("0\n"); /* 투어 경로 존재하지 않으면 '0' 출력 */ } fclose(fp); /* 파일 닫음 */ return 0; /* 프로그램 종료 */ }
void LoginDialog::prepareUpdate() { mLoginData->username = mUserField->getText(); mLoginData->password = mPassField->getText(); mLoginData->remember = mKeepCheck->isSelected(); UpdateTypeT updateType = static_cast<UpdateTypeT>( mUpdateTypeDropDown->getSelected()); if (mCustomUpdateHost->isSelected() && !mUpdateHostText->getText().empty()) { updateType = static_cast<UpdateTypeT>( updateType | UpdateType::Custom); serverConfig.setValue("customUpdateHost", mUpdateHostText->getText()); if (checkPath(mUpdateHostText->getText())) { mLoginData->updateHost = mUpdateHostText->getText(); *mUpdateHost = mLoginData->updateHost; } else { mLoginData->updateHost.clear(); (*mUpdateHost).clear(); } } else { std::string str; if (mUpdateHostDropDown) { str = mUpdateHostDropDown->getSelectedString(); } else if (mLoginData->updateHost.empty() && !mLoginData->updateHosts.empty()) { str = mLoginData->updateHosts[0]; } serverConfig.setValue("updateHost2", str); if (!str.empty() && checkPath(str)) { mLoginData->updateHost = str; *mUpdateHost = str; } else { mLoginData->updateHost.clear(); (*mUpdateHost).clear(); } } mLoginData->updateType = updateType; serverConfig.setValue("updateType", static_cast<int>(updateType)); mRegisterButton->setEnabled(false); mServerButton->setEnabled(false); mLoginButton->setEnabled(false); LoginDialog::savedPassword = mPassField->getText(); if (mLoginData->remember) LoginDialog::savedPasswordKey = mServerName; else LoginDialog::savedPasswordKey = "-"; }
static void parseOptions(const int argc, char *const argv[]) { const char *const optstring = "hvud:U:P:Dc:p:l:L:C:s:t:T:a:r"; const struct option long_options[] = { { "config-dir", required_argument, nullptr, 'C' }, { "data", required_argument, nullptr, 'd' }, { "default", no_argument, nullptr, 'D' }, { "password", required_argument, nullptr, 'P' }, { "character", required_argument, nullptr, 'c' }, { "help", no_argument, nullptr, 'h' }, { "localdata-dir", required_argument, nullptr, 'L' }, { "update-host", required_argument, nullptr, 'H' }, { "port", required_argument, nullptr, 'p' }, { "server", required_argument, nullptr, 's' }, { "skip-update", no_argument, nullptr, 'u' }, { "username", required_argument, nullptr, 'U' }, { "no-opengl", no_argument, nullptr, 'O' }, { "chat-log-dir", required_argument, nullptr, 'a' }, { "version", no_argument, nullptr, 'v' }, { "log-file", required_argument, nullptr, 'l' }, { "screenshot-dir", required_argument, nullptr, 'i' }, { "safemode", no_argument, nullptr, 'm' }, { "tests", no_argument, nullptr, 'T' }, { "test", required_argument, nullptr, 't' }, { "renderer", required_argument, nullptr, 'r' }, { nullptr, 0, nullptr, 0 } }; Options &options = settings.options; while (optind < argc) { const int result = getopt_long(argc, argv, optstring, long_options, nullptr); if (result == -1) break; switch (result) { case 'C': options.configDir = optarg; break; case 'd': options.dataPath = optarg; break; case 'D': options.chooseDefault = true; break; case '?': // Unknown option case ':': // Missing argument case 'h': options.printHelp = true; break; case 'H': if (checkPath(optarg)) options.updateHost = optarg; else options.updateHost.clear(); break; case 'c': options.character = optarg; break; case 'P': options.password = optarg; break; case 's': options.serverName = optarg; break; case 'p': options.serverPort = static_cast<uint16_t>(atoi(optarg)); break; case 'u': options.skipUpdate = true; break; case 'U': options.username = optarg; break; case 'v': options.printVersion = true; break; case 'L': options.localDataDir = optarg; break; case 'O': options.noOpenGL = true; break; case 'l': options.logFileName = std::string(optarg); break; case 'a': options.chatLogDir = std::string(optarg); break; case 'i': options.screenshotDir = optarg; break; case 'm': options.safeMode = true; break; case 'T': options.testMode = true; options.test.clear(); break; case 't': options.testMode = true; options.test = std::string(optarg); break; case 'r': options.renderer = static_cast<int>(atoi(optarg)); break; default: break; } } // when there are still options left use the last // one as branding file if (optind < argc) { options.brandingPath = argv[optind]; } }
/* * Main Function: runs loop giving user a prompt to enter a command and its * arguments, until the keyword 'exit' is recieved */ int main(int argc, char *argv[]){ char buffer[BUFSIZE]; /* input buffer with command + args */ char cwd[DIRSIZE]; /* current working directory */ char *path = getenv("PATH"); /* PATH env var */ char *execPath; /* PATH where the command is located */ char *token; /* used for tokenizing args and paths */ int pid; /* parent process id (for forking) */ /* List of arguments parsed from buffer. */ char **arguments = malloc(sizeof(char*) * MAXARG); int maxArgs = MAXARG; int numArgs = 0; /* List of paths parsed from PATH. */ char **paths = malloc(sizeof(char*) * MAXPATH); int numPaths = 0; int maxPaths = MAXPATH; /* Split the path env var into an array with individual paths. */ token = strtok(path, PATH_DELIM); do { /* Double the size of the paths array if it's full. */ if (numPaths >= maxPaths - 1) { maxPaths *= 2; paths = realloc(paths, sizeof(char*) * maxPaths); } paths[numPaths] = token; numPaths++; } while ((token = strtok(NULL, PATH_DELIM))); /* Debug info for checking paths. */ if (DEBUG) { for (int i = 0; i < numPaths; i++) { printf("Path %d: %s\n", i, paths[i]); } } /* Continuously prompt for and execute commands until "exit" is input. */ while (1){ numArgs = 0; /* reset current arg count */ execPath = NULL; /* reset execution path */ /* Reset CWD. */ getcwd(cwd, DIRSIZE); /* Null out arguments list. */ for (int i = 0; i < maxArgs; i++) { arguments[i] = NULL; } /* Print prompt and read in command line. */ printf("esh/:-> "); fgets(buffer, BUFSIZE, stdin); /* Pull the command from the input buffer. */ token = strtok(buffer, ARG_DELIM); /* Tokenize arguments from buffer and store in arguments array. */ do { /* Double the size of the arguments array if it's full. */ if(token != NULL && numArgs >= maxArgs - 1){ maxArgs *= 2; arguments = realloc(arguments, (maxArgs * sizeof(char*))); } arguments[numArgs] = token; numArgs++; } while ((token = strtok(NULL, ARG_DELIM))); /* Check for exit, break the loop if specified. */ if(!strcmp(arguments[0], "exit")){ free(arguments); break; } /* Debug info for verifying command and arguments. */ if (DEBUG){ printf("Command: %s \n", arguments[0]); for (int i = 1; i < numArgs; i++){ printf("Argument %d: %s \n", i, arguments[i]); } } /* Check if command exists in environment paths. */ for (int i = 0; i < numPaths; i++) { if (checkPath(paths[i], arguments[0])) { execPath = paths[i]; } } /* Check if command exists in cwd (if not found in paths). */ if (!execPath && checkPath(cwd, arguments[0])) { execPath = cwd; } /* If the file was not found at any path, check for new input. */ if (!execPath) { printf("Command `%s' not found.\n", arguments[0]); continue; } /* If it was found, fork and execute. */ pid = fork(); /* * If this is the parent branch and & isn't last arg, wait for child * to die. */ if (pid != 0) { if(strcmp("&", arguments[numArgs - 1]) == 0){ continue; }else{ wait(NULL); } } /* If this is the child branch, execute the command. */ else { if (strcmp("&", arguments[numArgs - 1]) == 0) { arguments[numArgs - 1] = NULL; } char *merged = mergePath(execPath, arguments[0]); execv(merged, arguments); exit(0); } } return 0; }
foreach(QString path, list) { checkPath(path, Qt::Unchecked); }
static int cfs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { if (checkPath(path)) return -EACCES; int index = 0,tempOff = 0, i = 0, blockNum = 0, read = 0, left = 0; int fd = open(cfsFile, O_RDONLY); COLA = (struct fileInfo*)mmap(0, colaSize, PROT_READ, MAP_SHARED, fd, 0); index = find(path+1,COLA); if (index == EMPTY) { munmap(COLA,colaSize); close(fd); return -ENOENT; } if (offset >= COLA[index].size) { munmap(COLA,colaSize); close(fd); return 0; } if (size + offset > COLA[index].size) { size = COLA[index].size - offset; } blockNum = COLA[index].blockNum; munmap(COLA,colaSize); tempOff = offset; if (tempOff >= block) { FAT = (int*)mmap(0, FATSize, PROT_READ, MAP_SHARED, fd, OFFC); while (tempOff >= block) { blockNum = FAT[blockNum]; tempOff = tempOff - block; } munmap(FAT,FATSize); } if (size + tempOff > block) { data = (char*)mmap(0,block,PROT_READ, MAP_SHARED, fd, OFFF + blockNum*block); memcpy(buf, data + tempOff, block - tempOff); munmap(data,block); read = block - tempOff; left = size - (block - tempOff); FAT = (int*)mmap(0, FATSize, PROT_READ, MAP_SHARED, fd, OFFC); blockNum = FAT[blockNum]; munmap(FAT,FATSize); while (left > 0) { if (left > block) { data = (char*)mmap(0,block,PROT_READ, MAP_SHARED, fd, OFFF + blockNum*block); memcpy(buf + read, data, block); munmap(data,block); FAT = (int*)mmap(0, FATSize, PROT_READ, MAP_SHARED, fd, OFFC); blockNum = FAT[blockNum]; munmap(FAT,FATSize); left = left - block; read += block; } else { data = (char*)mmap(0,block,PROT_READ,MAP_SHARED,fd,OFFF + blockNum*block); memcpy(buf + read, data, left); munmap(data,block); left = 0; } } } else { data = (char*)mmap(0,block,PROT_READ, MAP_SHARED,fd,OFFF + blockNum*block); memcpy(buf, data + tempOff, size); munmap(data,block); } close(fd); return size; }
void CalibrateAction::executeCB(const calibrate_twist::CalibrateGoalConstPtr &goal) { success = true; // read all necessary parameters ros::NodeHandle nhPriv("~"); nhPriv.getParamCached("odo_cache_depths", odo_cache_depths); nhPriv.getParamCached("stability_timeout", stability_timeout); nhPriv.getParamCached("stability_intervalDuration", stability_intervalDuration); nhPriv.getParamCached("stability_xThreshold", stability_xThreshold); nhPriv.getParamCached("stability_zThreshold", stability_zThreshold); nhPriv.getParamCached("calibration_calc_interval", calibration_calc_interval); nhPriv.getParamCached("tfFixedFrame", tfFixedFrame); nhPriv.getParamCached("robotFrame", robotFrame); nhPriv.getParamCached("cmdVelTopic", cmdVelTopic); nhPriv.getParamCached("minStabilityDuration", minStabilityDuration); nhPriv.getParamCached("transforms_interval_size", transforms_interval_size); nhPriv.getParamCached("cal_costmap", cal_costmap); nhPriv.getParamCached("traj_sim_granularity_", traj_sim_granularity_); nhPriv.getParamCached("traj_dist_threshold", traj_dist_threshold); nhPriv.getParamCached("accel_max_x", accel_max_x); nhPriv.getParamCached("accel_max_y", accel_max_y); nhPriv.getParamCached("accel_max_theta", accel_max_theta); nhPriv.getParamCached("min_time_clear", min_time_clear); goal_ = *goal; listener = new tf::TransformListener((goal_.duration)*2); // set cache time twice the time of the calibr. run cost_map = new costmap_2d::Costmap2DROS(cal_costmap, *listener); voronoi_.initializeEmpty(cost_map->getSizeInCellsX(), cost_map->getSizeInCellsY(), true); //ros::Subscriber cm_sub = nh_.subscribe("~/move_base/local_costmap/obstacles", 1, CalibrateAction::costmapCB); message_filters::Subscriber<nav_msgs::Odometry> sub(nh_, "/odom", 1); odo_cache = new message_filters::Cache<nav_msgs::Odometry> (sub, odo_cache_depths); estTraj_pub = nh_.advertise<geometry_msgs::PoseArray>("est_traj_", 10); calcTraj_pub = nh_.advertise<geometry_msgs::PoseArray>("calc_traj_", 10); twist_pub = nh_.advertise<geometry_msgs::Twist>(cmdVelTopic,1); voronoi_pub = nh_.advertise<visualization_msgs::MarkerArray>("voronoi_marker", 10); // necessary? how to initialize as empty? zero_twist.angular.x = 0; zero_twist.angular.y = 0; zero_twist.angular.z = 0; zero_twist.linear.x = 0; zero_twist.linear.y = 0; zero_twist.linear.z = 0; // publish info to the console for the user ROS_INFO("%s: Executing, running calibration run for %f seconds with linear speed %f, angular speed %f", action_name_.c_str(), goal_.duration.toSec(), goal_.twist_goal.linear.x, goal_.twist_goal.angular.z); // update voronoi at first, else no distance check is possible updateVoronoi(); // load values from costmap and push them into voronoi //************************************************** // bringing the robot to the goal speed //************************************************** bool stability_reached = false; bool check = estimateFullPathIsClear(goal_.twist_goal.linear.x, goal_.twist_goal.linear.y, goal_.twist_goal.angular.z, goal_.duration.toSec(), accel_max_x, accel_max_y, accel_max_theta); ROS_INFO("Full check results in %i", check); if(checkPath(0, 0, 0, goal_.twist_goal.linear.x, goal_.twist_goal.linear.y, goal_.twist_goal.angular.z, accel_max_x, accel_max_y, accel_max_theta)) { stability_reached = bringupGoalSpeed(); } // not stopping robot here because we want to have continuous movement! if(!stability_reached) { twist_pub.publish(zero_twist); // safety first, stop robot as_.setAborted(); ROS_INFO("%s: Aborted. No stability reached within timeout", action_name_.c_str()); success = false; return; } //************************************************** // starting calibration run for given duration //************************************************** else if(success) { ROS_INFO("Speed up successful, starting calibration run"); if(checkPath(goal_.twist_goal.linear.x, goal_.twist_goal.linear.y, goal_.twist_goal.angular.z, goal_.duration.toSec(), goal_.twist_goal.linear.x, goal_.twist_goal.linear.y, goal_.twist_goal.angular.z, 0.0, 0.0, 0.0)) { success = startCalibrationRun(); // check whether we finished the run successfully or not } else { twist_pub.publish(zero_twist); // safety first, stop robot as_.setAborted(); ROS_INFO("%s: Aborted. No space to drive planned trajectory", action_name_.c_str()); success = false; return; } } // end of movement, therefore robo is stopped twist_pub.publish(zero_twist); // safety first, stop robot //************************************************** // calculating the result //************************************************** if(success) { ROS_INFO("Calibration run finished, calculating result..."); calculateResult(); } else { ROS_INFO("Calibration aborted"); as_.setAborted(); return; } //************************************************** // publishing the result //************************************************** if(success) { result_.calibrated_result = twistWCFromTf; result_.odo_result = twistWCFromOdometry; ROS_INFO("%s: Succeeded", action_name_.c_str()); // set the action state to succeeded as_.setSucceeded(result_); } // callback finished }
void ConfigManager::initConfiguration() { #ifdef DEBUG_CONFIG config.setIsMain(true); #endif // Fill configuration with defaults config.setValue("hwaccel", false); #ifdef USE_OPENGL #if (defined __APPLE__) config.setValue("opengl", CAST_S32(RENDER_NORMAL_OPENGL)); #elif (defined ANDROID) config.setValue("opengl", CAST_S32(RENDER_GLES_OPENGL)); #elif (defined WIN32) config.setValue("opengl", CAST_S32(RENDER_SAFE_OPENGL)); #else config.setValue("opengl", CAST_S32(RENDER_SOFTWARE)); #endif #else config.setValue("opengl", CAST_S32(RENDER_SOFTWARE)); #endif config.setValue("screen", false); config.setValue("sound", true); config.setValue("guialpha", 0.8F); // config.setValue("remember", true); config.setValue("sfxVolume", 100); config.setValue("musicVolume", 60); config.setValue("fpslimit", 60); std::string defaultUpdateHost = branding.getValue("defaultUpdateHost", ""); if (!checkPath(defaultUpdateHost)) defaultUpdateHost.clear(); config.setValue("updatehost", defaultUpdateHost); config.setValue("useScreenshotDirectorySuffix", true); config.setValue("ChatLogLength", 128); std::string configPath; if (settings.options.test.empty()) configPath = settings.configDir + "/config.xml"; else configPath = settings.configDir + "/test.xml"; FILE *configFile = fopen(configPath.c_str(), "r"); if (!configFile) { configFile = fopen(configPath.c_str(), "wt"); logger->log1("Creating new config"); } if (!configFile) { logger->log("Can't create %s. Using defaults.", configPath.c_str()); } else { fclose(configFile); config.init(configPath); logger->log1("init 3"); config.setDefaultValues(getConfigDefaults()); logger->log("configPath: " + configPath); } }
// build maximal weighted spanning tree and rank the vertices based on tc size of their BFS tree void GraphUtil::buildMaxWST(Graph& g, ReducedGraph& sptree, vector<int>& rank) { ReducedGraph::iterator rit; vector<int>::iterator vit; map<int,int>::iterator mit; SparseVec::iterator svit; int gsize = g.num_vertices(); map<int,pair<int,int> > pred_succ; SparseVec weight = SparseVec(gsize,map<int,int>()); multimap<int,int> mrank; int tree_tc = 0; for (int i = 0; i < gsize; i++) { if(i%100==0) printf("buildMaxWST %d\n",i); ReducedGraph tree; tree_tc = BFSTree(g, i, tree); #ifdef ALLPATHS treestat(tree, pred_succ, i, gsize); #endif for (rit = tree.begin(); rit != tree.end(); rit++) { for (vit = rit->second.begin(); vit != rit->second.end(); vit++) #ifdef ALLPATHS weight[rit->first][*vit] += pred_succ[rit->first].first*pred_succ[*vit].second; #else weight[rit->first][*vit] += 1; #endif } #ifdef ALLPATHS map<int,pair<int,int> >().swap(pred_succ); #endif ReducedGraph().swap(tree); mrank.insert(make_pair(tree_tc,i)); } // set ranking results // rank.clear(); vector<int>().swap(rank); multimap<int,int>::const_reverse_iterator mcit; for (mcit = mrank.rbegin(); mcit != mrank.rend(); mcit++) rank.push_back(mcit->second); // mrank.clear(); multimap<int,int>().swap(mrank); multimap<int,pair<int,int> > wmap; multimap<int,pair<int,int> >::reverse_iterator mmit; for (int i = 0; i < weight.size(); i++) { for (mit = weight[i].begin(); mit != weight[i].end(); mit++) { wmap.insert(make_pair(mit->second,make_pair(i,mit->first))); } } // weight.clear(); SparseVec().swap(weight); // greedy algorithm to extract maximal weight spanning tree int numedge = 0; Graph tree = Graph(gsize); pair<int,int> edge; for (mmit = wmap.rbegin(); mmit != wmap.rend(); mmit++) { edge = mmit->second; if (tree.in_edges(edge.second).size()>0 || checkPath(tree,edge.second,edge.first)) continue; tree.addEdge(edge.first,edge.second); numedge++; if (numedge>=(gsize-1)) break; } // compute all pairs shortest paths in the spanning tree // computeShortestDistance(tree,treedist); EdgeList el; for (int i = 0; i < gsize; i++) { el = tree.out_edges(i); if (el.size()>0) sptree[i] = vector<int>(el.begin(),el.end()); // sptree.push_back(vector<int>(el.begin(),el.end())); // sptree.insert(el.begin(),el.end()); } }
int main(void) { int width, height; // Ask for field's width and height printf("Width and height? "); scanf("%1i %1i", &width, &height); if ((width < 1 || width > 10) || (height < 1 || height > 10)) { printf("ERROR: Width/height are out of range\n"); return -1; } // Create playing field char field[width][height]; int i, j; char *line; line = (char *)malloc(width*2 * sizeof *line); for (i = 0; i < height; i++) { printf("Line %2d? ", i); scanf(" %20[^\n]s", line); if ((int)strlen(line) != width*2 - 1) { printf("ERROR: You should enter exact number of values"); free(line); return -1; } for (j = 0; j < width*2; j++) { field[i][j] = line[j*2] - '0'; } } free(line); // Initialize graph graph_len = width*height; int **graph; // Allocate an array graph = (int **)malloc(graph_len * sizeof *graph); for (i = 0; i < graph_len; i++) { graph[i] = (int *)malloc(graph_len * sizeof *graph[i]); } // Fill-in default values for (i = 0; i < graph_len; i++) { for (j = 0; j < graph_len; j++) { graph[i][j] = 0; } } // Build graph int start_vertex = -1; int current_vertex = -1; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if (field[i][j] != 1) { // Calculate vertex number current_vertex = i*width + j; // Find start and stop vertices if (field[i][j] == 2) start_vertex = current_vertex; if (field[i][j] == 3) stop_vertex = current_vertex; //graph[current_vertex][current_vertex] = 1; if (i+1 < height && (field[i+1][j] == 0 || field[i+1][j] == 3)) { graph[current_vertex][(i+1)*width+j] = 1; } if (i-1 >= 0 && (field[i-1][j] == 0 || field[i-1][j] == 3)) { graph[current_vertex][(i-1)*width+j] = 1; } if (j+1 < width && (field[i][j+1] == 0 || field[i][j+1] == 3)) { graph[current_vertex][i*width+(j+1)] = 1; } if (j-1 >= 0 && (field[i][j-1] == 0 || field[i][j-1] == 3)) { graph[current_vertex][i*width+(j-1)] = 1; } } else { bad_nodes++; } } } // DEBUG: print graph matrix and additional info /* printf(" "); for (j = 0; j < graph_len; j++) { printf("%0.2d ", j); } printf("\n"); for (i = 0; i < graph_len; i++) { printf("%0.2d: ", i); for (j = 0; j < graph_len; j++) { printf("%2d ", graph[i][j]); } printf("\n"); } printf("Bad Nodes: %d\n", bad_nodes); printf("Start Vertex: %d\n", start_vertex); printf("Stop Vertex: %d\n", stop_vertex); */ // Initialize path int path[graph_len]; for (i = 0; i < graph_len; i++) { path[i] = -1; } // Add initial vertex path[0] = start_vertex; // Max position max_pos = graph_len - bad_nodes; // Backtracing checkPath(graph, path, 1); printf("Paths: %d\n", numpaths); // Deallocate an array for (i = 0; i < graph_len; i++) { free(graph[i]); } free(graph); return 0; }
/** * Parse the update host and determine the updates directory * Then verify that the directory exists (creating if needed). */ void Dirs::initUpdatesDir() { std::stringstream updates; // If updatesHost is currently empty, fill it from config file if (settings.updateHost.empty()) settings.updateHost = config.getStringValue("updatehost"); if (!checkPath(settings.updateHost)) return; // Don't go out of range int he next check if (settings.updateHost.length() < 2) { if (settings.updatesDir.empty()) { settings.updatesDir = std::string("updates/").append( settings.serverName); } return; } const size_t sz = settings.updateHost.size(); // Remove any trailing slash at the end of the update host if (settings.updateHost.at(sz - 1) == '/') settings.updateHost.resize(sz - 1); // Parse out any "http://" or "https://", and set the updates directory const size_t pos = settings.updateHost.find("://"); if (pos != settings.updateHost.npos) { if (pos + 3 < settings.updateHost.length() && !settings.updateHost.empty()) { updates << "updates/" << settings.updateHost.substr(pos + 3); settings.updatesDir = updates.str(); } else { logger->log("Error: Invalid update host: %s", settings.updateHost.c_str()); // TRANSLATORS: update server initialisation error errorMessage = strprintf(_("Invalid update host: %s."), settings.updateHost.c_str()); client->setState(STATE_ERROR); } } else { logger->log1("Warning: no protocol was specified for the update host"); updates << "updates/" << settings.updateHost; settings.updatesDir = updates.str(); } #ifdef WIN32 if (settings.updatesDir.find(":") != std::string::npos) replaceAll(settings.updatesDir, ":", "_"); #endif const std::string updateDir("/" + settings.updatesDir); // Verify that the updates directory exists. Create if necessary. if (!PhysFs::isDirectory(updateDir.c_str())) { if (!PhysFs::mkdir(updateDir.c_str())) { #if defined WIN32 std::string newDir = settings.localDataDir + "\\" + settings.updatesDir; size_t loc = newDir.find("/", 0); while (loc != std::string::npos) { newDir.replace(loc, 1, "\\"); loc = newDir.find("/", loc); } if (!CreateDirectory(newDir.c_str(), nullptr) && GetLastError() != ERROR_ALREADY_EXISTS) { logger->log("Error: %s can't be made, but doesn't exist!", newDir.c_str()); // TRANSLATORS: update server initialisation error errorMessage = _("Error creating updates directory!"); client->setState(STATE_ERROR); } #else logger->log("Error: %s/%s can't be made, but doesn't exist!", settings.localDataDir.c_str(), settings.updatesDir.c_str()); // TRANSLATORS: update server initialisation error errorMessage = _("Error creating updates directory!"); client->setState(STATE_ERROR); #endif } } const std::string updateLocal = updateDir + "/local"; const std::string updateFix = updateDir + "/fix"; if (!PhysFs::isDirectory(updateLocal.c_str())) PhysFs::mkdir(updateLocal.c_str()); if (!PhysFs::isDirectory(updateFix.c_str())) PhysFs::mkdir(updateFix.c_str()); }
void HTML_Convert_to_image(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT ParamHtml; ARRAY_LONGINT ParamKeys; ARRAY_TEXT ParamValues; C_BLOB returnValue; ParamHtml.fromParamAtIndex(pParams, 1); ParamKeys.fromParamAtIndex(pParams, 2); ParamValues.fromParamAtIndex(pParams, 3); CUTF8String paramValue, path; wkhtmltoimage_global_settings *gs; wkhtmltoimage_converter *c; gs = _wkhtmltoimage_create_global_settings(); for(unsigned int i = 0; i < ParamKeys.getSize(); ++i){ ParamValues.copyUTF8StringAtIndex(¶mValue, i); switch (ParamKeys.getIntValueAtIndex(i)){ case HTML_IMAGE_USE_SMART_WIDTH: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltoimage_set_global_setting(gs, "smartWidth", "true"); }else{ _wkhtmltoimage_set_global_setting(gs, "smartWidth", "false"); } break; case HTML_IMAGE_USE_BACKGROUND: if(!paramValue.compare((const uint8_t *)"false")){ _wkhtmltoimage_set_global_setting(gs, "transparent", "true"); }else{ _wkhtmltoimage_set_global_setting(gs, "transparent", "false"); } break; case HTML_IMAGE_CROP_LEFT: _wkhtmltoimage_set_global_setting(gs, "crop.left", (const char *)paramValue.c_str()); break; case HTML_IMAGE_CROP_TOP: _wkhtmltoimage_set_global_setting(gs, "crop.top", (const char *)paramValue.c_str()); break; case HTML_IMAGE_CROP_WIDTH: _wkhtmltoimage_set_global_setting(gs, "crop.width", (const char *)paramValue.c_str()); break; case HTML_IMAGE_CROP_HEIGHT: _wkhtmltoimage_set_global_setting(gs, "crop.height", (const char *)paramValue.c_str()); break; case HTML_IMAGE_JPEG_QUALITY: _wkhtmltoimage_set_global_setting(gs, "quality", (const char *)paramValue.c_str()); break; case HTML_IMAGE_SCREEN_WIDTH: _wkhtmltoimage_set_global_setting(gs, "screenWidth", (const char *)paramValue.c_str()); break; case HTML_IMAGE_FORMAT: if( (!paramValue.compare((const uint8_t *)"jpg")) || (!paramValue.compare((const uint8_t *)"png")) || (!paramValue.compare((const uint8_t *)"bmp")) || (!paramValue.compare((const uint8_t *)"svg"))){ _wkhtmltoimage_set_global_setting(gs, "fmt", (const char *)paramValue.c_str()); } break; } } if(ParamHtml.getUTF16Length()){ CUTF8String htmlPath, html, htmlUrl; ParamHtml.copyPath(&htmlPath); ParamHtml.copyUTF8String(&htmlUrl); if( (htmlUrl.find((const uint8_t *)"http://") == 0) || (htmlUrl.find((const uint8_t *)"https://") == 0) || (htmlUrl.find((const uint8_t *)"ftp://") == 0) || (htmlUrl.find((const uint8_t *)"ftps://") == 0)){ _wkhtmltoimage_set_global_setting(gs, "in",(const char *)htmlUrl.c_str()); c = _wkhtmltoimage_create_converter(gs, NULL); }else{ if(checkPath(&htmlPath)){ _wkhtmltoimage_set_global_setting(gs, "in",(const char *)htmlPath.c_str()); c = _wkhtmltoimage_create_converter(gs, NULL); }else{ ParamHtml.copyUTF8String(&html); c = _wkhtmltoimage_create_converter(gs, (const char *)html.c_str()); } } if(_wkhtmltoimage_convert(c)){ const unsigned char *bytes; long len = _wkhtmltoimage_get_output(c, &bytes); returnValue.setBytes((const uint8_t *)bytes, len); } } _wkhtmltoimage_destroy_converter(c); returnValue.setReturn(pResult); }
void HTML_Convert_to_pdf(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT ParamHtml; ARRAY_LONGINT ParamKeys; ARRAY_TEXT ParamValues; C_BLOB returnValue; ParamHtml.fromParamAtIndex(pParams, 1); ParamKeys.fromParamAtIndex(pParams, 2); ParamValues.fromParamAtIndex(pParams, 3); CUTF8String paramValue, path; wkhtmltopdf_global_settings *gs; wkhtmltopdf_object_settings *os; wkhtmltopdf_converter *c; gs = _wkhtmltopdf_create_global_settings(); os = _wkhtmltopdf_create_object_settings(); /*hard code these options http://www.cs.au.dk/~jakobt/libwkhtmltox_0.10.0_doc/pagesettings.html#pagePdfGlobal */ _wkhtmltopdf_set_object_setting(os, "load.blockLocalFileAccess", "false"); _wkhtmltopdf_set_object_setting(os, "load.stopSlowScript", "true"); _wkhtmltopdf_set_object_setting(os, "load.debugJavascript", "false"); _wkhtmltopdf_set_object_setting(os, "load.loadErrorHandling", "ignore"); _wkhtmltopdf_set_object_setting(os, "includeInOutline", "true"); _wkhtmltopdf_set_global_setting(gs, "outputFormat", "pdf"); for(unsigned int i = 0; i < ParamKeys.getSize(); ++i){ ParamValues.copyUTF8StringAtIndex(¶mValue, i); switch (ParamKeys.getIntValueAtIndex(i)){ case HTML_USE_BACKGROUND: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "web.background", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "web.background", "false"); } break; case HTML_USE_IMAGES: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "web.loadImages", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "web.loadImages", "false"); } break; case HTML_USE_JAVASCRIPT: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "web.enableJavascript", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "web.enableJavascript", "false"); } break; case HTML_USE_SMART_RESIZE: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "web.enableIntelligentShrinking", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "web.enableIntelligentShrinking", "false"); } break; case HTML_USE_PRINT_MEDIA: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "web.printMediaType", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "web.printMediaType", "false"); } break; case HTML_USE_PLUGINS: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "web.enablePlugins", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "web.enablePlugins", "false"); } break; case HTML_PDF_USE_COMPRESSION: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_global_setting(gs, "useCompression", "true"); }else{ _wkhtmltopdf_set_global_setting(gs, "useCompression", "false"); } break; case HTML_PDF_USE_OUTLINE: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_global_setting(gs, "outline", "true"); }else{ _wkhtmltopdf_set_global_setting(gs, "outline", "false"); } break; case HTML_PDF_HEADER_USE_LINE: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "header.line", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "header.line", "false"); } break; case HTML_PDF_FOOTER_USE_LINE: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "footer.line", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "footer.line", "false"); } break; case HTML_PDF_TOC_USE_DOTTED_LINES: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "toc.useDottedLines", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "toc.useDottedLines", "false"); } break; case HTML_PDF_TOC_USE_FORWARD_LINKS: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "toc.forwardLinks", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "toc.forwardLinks", "false"); } break; case HTML_PDF_TOC_USE_BACK_LINKS: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "toc.backLinks", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "toc.backLinks", "false"); } break; case HTML_PDF_USE_EXTERNAL_LINKS: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "useExternalLinks", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "useExternalLinks", "false"); } break; case HTML_PDF_USE_LOCAL_LINKS: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "useLocalLinks", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "useLocalLinks", "false"); } break; case HTML_PDF_USE_FORMS: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "produceForms", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "produceForms", "false"); } break; case HTML_PDF_USE_PAGES_COUNT: if(!paramValue.compare((const uint8_t *)"true")){ _wkhtmltopdf_set_object_setting(os, "pagesCount", "true"); }else{ _wkhtmltopdf_set_object_setting(os, "pagesCount", "false"); } break; case HTML_MINIMUM_FONT_SIZE: _wkhtmltopdf_set_object_setting(os, "web.minimumFontSize", (const char *)paramValue.c_str()); break; case HTML_DEFAULT_ENCODING: _wkhtmltopdf_set_object_setting(os, "web.defaultEncoding", (const char *)paramValue.c_str()); break; case HTML_ZOOM_FACTOR: _wkhtmltopdf_set_object_setting(os, "load.zoomFactor",(const char *)paramValue.c_str()); break; case HTML_PDF_PAPER_SIZE: _wkhtmltopdf_set_global_setting(gs, "size.paperSize",(const char *)paramValue.c_str()); break; case HTML_PDF_DOCUMENT_WIDTH: _wkhtmltopdf_set_global_setting(gs, "size.width",(const char *)paramValue.c_str()); break; case HTML_PDF_DOCUMENT_HEIGHT: _wkhtmltopdf_set_global_setting(gs, "size.height",(const char *)paramValue.c_str()); break; case HTML_PDF_DPI: _wkhtmltopdf_set_global_setting(gs, "dpi",(const char *)paramValue.c_str()); break; case HTML_PDF_JPEG_QUALITY: _wkhtmltopdf_set_global_setting(gs, "imageQuality",(const char *)paramValue.c_str()); break; case HTML_PDF_IMAGE_DPI: _wkhtmltopdf_set_global_setting(gs, "imageDPI",(const char *)paramValue.c_str()); break; case HTML_PDF_ORIENTATION: if( (!paramValue.compare((const uint8_t *)"Landscape")) || (!paramValue.compare((const uint8_t *)"Portrait"))){ _wkhtmltopdf_set_global_setting(gs, "orientation", (const char *)paramValue.c_str()); } break; case HTML_PDF_COLOR_MODE: if( (!paramValue.compare((const uint8_t *)"Color")) || (!paramValue.compare((const uint8_t *)"Grayscale"))){ _wkhtmltopdf_set_global_setting(gs, "colorMode", (const char *)paramValue.c_str()); } break; case HTML_PDF_OUTPUT_FORMAT: if( (!paramValue.compare((const uint8_t *)"pdf")) || (!paramValue.compare((const uint8_t *)"ps"))){ _wkhtmltopdf_set_global_setting(gs, "outputFormat", (const char *)paramValue.c_str()); } break; case HTML_PDF_MARGIN_RIGHT: _wkhtmltopdf_set_global_setting(gs, "margin.right",(const char *)paramValue.c_str()); break; case HTML_PDF_MARGIN_LEFT: _wkhtmltopdf_set_global_setting(gs, "margin.left",(const char *)paramValue.c_str()); break; case HTML_PDF_MARGIN_BOTTOM: _wkhtmltopdf_set_global_setting(gs, "margin.bottom",(const char *)paramValue.c_str()); break; case HTML_PDF_MARGIN_TOP: _wkhtmltopdf_set_global_setting(gs, "margin.top",(const char *)paramValue.c_str()); break; case HTML_PDF_DOCUMENT_TITLE: _wkhtmltopdf_set_global_setting(gs, "documentTitle",(const char *)paramValue.c_str()); break; case HTML_PDF_PAGE_NUMBER_OFFSET: _wkhtmltopdf_set_global_setting(gs, "pageOffset",(const char *)paramValue.c_str()); break; case HTML_PDF_NUMBER_OF_COPIES: _wkhtmltopdf_set_global_setting(gs, "copies",(const char *)paramValue.c_str()); break; case HTML_PDF_OUTLINE_DEPTH: _wkhtmltopdf_set_global_setting(gs, "outlineDepth",(const char *)paramValue.c_str()); break; case HTML_PDF_HEADER_FONT_SIZE: _wkhtmltopdf_set_object_setting(os, "header.fontSize",(const char *)paramValue.c_str()); break; case HTML_PDF_HEADER_FONT_NAME: _wkhtmltopdf_set_object_setting(os, "header.fontName",(const char *)paramValue.c_str()); break; case HTML_PDF_HEADER_LEFT: _wkhtmltopdf_set_object_setting(os, "header.left",(const char *)paramValue.c_str()); break; case HTML_PDF_HEADER_CENTER: _wkhtmltopdf_set_object_setting(os, "header.center",(const char *)paramValue.c_str()); break; case HTML_PDF_HEADER_RIGHT: _wkhtmltopdf_set_object_setting(os, "header.right",(const char *)paramValue.c_str()); break; case HTML_PDF_HEADER_SPACE: _wkhtmltopdf_set_object_setting(os, "header.space",(const char *)paramValue.c_str()); break; case HTML_PDF_FOOTER_FONT_SIZE: _wkhtmltopdf_set_object_setting(os, "footer.fontSize",(const char *)paramValue.c_str()); break; case HTML_PDF_FOOTER_FONT_NAME: _wkhtmltopdf_set_object_setting(os, "footer.fontName",(const char *)paramValue.c_str()); break; case HTML_PDF_FOOTER_LEFT: _wkhtmltopdf_set_object_setting(os, "footer.left",(const char *)paramValue.c_str()); break; case HTML_PDF_FOOTER_CENTER: _wkhtmltopdf_set_object_setting(os, "footer.center",(const char *)paramValue.c_str()); break; case HTML_PDF_FOOTER_RIGHT: _wkhtmltopdf_set_object_setting(os, "footer.right",(const char *)paramValue.c_str()); break; case HTML_PDF_FOOTER_SPACE: _wkhtmltopdf_set_object_setting(os, "footer.space",(const char *)paramValue.c_str()); break; case HTML_PDF_TOC_CAPTION_TEXT: _wkhtmltopdf_set_object_setting(os, "toc.captionText",(const char *)paramValue.c_str()); break; case HTML_PDF_TOC_INDENTATION: _wkhtmltopdf_set_object_setting(os, "toc.indentation",(const char *)paramValue.c_str()); break; case HTML_PDF_TOC_FONT_SCALE: _wkhtmltopdf_set_object_setting(os, "toc.fontScale",(const char *)paramValue.c_str()); break; case HTML_WEB_USERNAME: _wkhtmltopdf_set_object_setting(os, "load.username",(const char *)paramValue.c_str()); break; case HTML_WEB_PASSWORD: _wkhtmltopdf_set_object_setting(os, "load.password",(const char *)paramValue.c_str()); break; case HTML_WEB_PROXY: _wkhtmltopdf_set_object_setting(os, "load.proxy",(const char *)paramValue.c_str()); break; case HTML_PDF_OUTLINE_PATH: ParamValues.copyPathAtIndex(&path, i); _wkhtmltopdf_set_object_setting(os, "dumpOutline",(const char *)path.c_str()); break; case HTML_PDF_OUTLINE_XSL_PATH: // ParamValues.copyUTF16StringAtIndex(&path, i); // _wkhtmltopdf_set_object_setting(os, "tocXsl",(const char *)path.c_str()); break; case HTML_CUSTOM_CSS_PATH: ParamValues.copyPathAtIndex(&path, i); _wkhtmltopdf_set_object_setting(os, "web.userStyleSheet",(const char *)path.c_str()); break; case HTML_COOKIE_JAR_PATH: ParamValues.copyPathAtIndex(&path, i); _wkhtmltopdf_set_object_setting(os, "load.cookieJar",(const char *)path.c_str()); break; } } c = _wkhtmltopdf_create_converter(gs); if(ParamHtml.getUTF16Length()){ CUTF8String htmlPath, html, htmlUrl; ParamHtml.copyPath(&htmlPath); ParamHtml.copyUTF8String(&htmlUrl); if( (htmlUrl.find((const uint8_t *)"http://") == 0) || (htmlUrl.find((const uint8_t *)"https://") == 0) || (htmlUrl.find((const uint8_t *)"ftp://") == 0) || (htmlUrl.find((const uint8_t *)"ftps://") == 0)){ _wkhtmltopdf_set_object_setting(os, "page",(const char *)htmlUrl.c_str()); _wkhtmltopdf_add_object(c, os, NULL); }else{ if(checkPath(&htmlPath)){ _wkhtmltopdf_set_object_setting(os, "page",(const char *)htmlPath.c_str()); _wkhtmltopdf_add_object(c, os, NULL); }else{ ParamHtml.copyUTF8String(&html); _wkhtmltopdf_add_object(c, os, (const char *)html.c_str()); } } if(_wkhtmltopdf_convert(c)){ const unsigned char *bytes; long len = _wkhtmltopdf_get_output(c, &bytes); returnValue.setBytes((const uint8_t *)bytes, len); } } _wkhtmltopdf_destroy_converter(c); returnValue.setReturn(pResult); }
int GraphUtil::buildSpanningTree2(Graph& g, SparseVec& treedist, SparseVec& dist, ReducedGraph& sptree) { ReducedGraph::iterator rit; vector<int>::iterator vit; map<int,int>::iterator mit; SparseVec::iterator svit; int gsize = g.num_vertices(); SparseVec weight = SparseVec(gsize,map<int,int>()); for (int i = 0; i < gsize; i++) { ReducedGraph tree; BFSTree(g, i, tree); for (rit = tree.begin(); rit != tree.end(); rit++) { for (vit = rit->second.begin(); vit != rit->second.end(); vit++) weight[rit->first][*vit] += 1; } tree.clear(); } // for test /* cout << "weight summary "; Util::printSparseVec(weight); */ multimap<int,pair<int,int> > wmap; multimap<int,pair<int,int> >::reverse_iterator mmit; for (int i = 0; i < weight.size(); i++) { for (mit = weight[i].begin(); mit != weight[i].end(); mit++) { wmap.insert(make_pair(mit->second,make_pair(i,mit->first))); } } weight.clear(); // greedy algorithm to extract maximal weight spanning tree int numedge = 0; Graph tree = Graph(gsize); pair<int,int> edge; for (mmit = wmap.rbegin(); mmit != wmap.rend(); mmit++) { // for test // cout << "(" << mmit->second.first << "," << mmit->second.second << ")" << mmit->first << endl; edge = mmit->second; if (tree.in_edges(edge.second).size()>0 || checkPath(tree,edge.second,edge.first)) continue; tree.addEdge(edge.first,edge.second); numedge++; if (numedge>=(gsize-1)) break; } // for test // tree.writeGraph(cout); computeShortestDistance(tree,treedist); int tnum = 0; EdgeList el; for (int i = 0; i < gsize; i++) { treedist[i].erase(i); tnum += treedist[i].size(); for (mit = treedist[i].begin(); mit != treedist[i].end(); ) { if (mit->second != dist[i][mit->first]) { treedist[i].erase(mit++); } else mit++; } el = tree.out_edges(i); sptree[i] = vector<int>(el.begin(),el.end()); // sptree.push_back(vector<int>(el.begin(),el.end())); } // for test // Util::printSparseVec(treedist); return tnum; }
bool checkStoragePaths(QStringList &probs) { bool problemFound = false; QString recordFilePrefix = gCoreContext->GetSetting("RecordFilePrefix", "EMPTY"); MSqlQuery query(MSqlQuery::InitCon()); query.prepare("SELECT count(groupname) FROM storagegroup;"); if (!query.exec() || !query.isActive() || query.size() < 1) { MythDB::DBError("checkStoragePaths", query); return false; } query.next(); if (query.value(0).toInt() == 0) { QString trMesg = QObject::tr("No Storage Group directories are defined. You " "must add at least one directory to the Default " "Storage Group where new recordings will be " "stored."); probs.push_back(trMesg); LOG(VB_GENERAL, LOG_ERR, trMesg); return true; } query.prepare("SELECT groupname, dirname " "FROM storagegroup " "WHERE hostname = :HOSTNAME;"); query.bindValue(":HOSTNAME", gCoreContext->GetHostName()); if (!query.exec() || !query.isActive()) { MythDB::DBError("checkStoragePaths", query); return false; } else if (query.size() < 1) { if (gCoreContext->IsMasterHost()) { // Master backend must have a defined Default SG QString trMesg = QObject::tr("No Storage Group directories are defined. " "You must add at least one directory to the " "Default Storage Group where new recordings " "will be stored."); probs.push_back(trMesg); LOG(VB_GENERAL, LOG_ERR, trMesg); return true; } else return false; } QDir checkDir(""); QString dirname; while (query.next()) { /* The storagegroup.dirname column uses utf8_bin collation, so Qt * uses QString::fromAscii() for toString(). Explicitly convert the * value using QString::fromUtf8() to prevent corruption. */ dirname = QString::fromUtf8(query.value(1) .toByteArray().constData()); QStringList tokens = dirname.split(","); int curToken = 0; while (curToken < tokens.size()) { checkDir.setPath(tokens[curToken]); if (checkPath(tokens[curToken], probs)) { problemFound = true; } curToken++; } } return problemFound; }
bool Config::Load() { TiXmlDocument *mDoc; TiXmlElement *mRoot; TiXmlElement *mElem; TiXmlElement *mel, *mels; boost::filesystem::path p; p = boost::filesystem::path(mFileName); if(!boost::filesystem::is_regular_file(p)) { exit("does not regular file: "+mFileName); } std::clog<<"config file: "<<mFileName<<std::endl; mIsInited = false; mDoc = new TiXmlDocument(mFileName); if(!mDoc) { exit("does not found config file: "+mFileName); } if(!mDoc->LoadFile()) { std::clog<<"load file: "<<mFileName <<" error: "<<mDoc->ErrorDesc() <<" row: "<<mDoc->ErrorRow() <<" col: "<<mDoc->ErrorCol() <<". exit." <<std::endl; ::exit(1); } if(p.has_parent_path()) { cfgFilePath = p.parent_path().string() + "/"; } else { cfgFilePath = "./"; } #ifdef DEBUG std::cout<<"config path: "<<cfgFilePath<<std::endl; #endif // DEBUG mRoot = mDoc->FirstChildElement("root"); if(!mRoot) { exit("does not found root section in file: "+mFileName); } instanceId = atoi(mRoot->Attribute("id")); //main config if( (mElem = mRoot->FirstChildElement("server")) ) { if( (mel = mElem->FirstChildElement("ip")) && (mel->GetText()) ) { server_ip_ = mel->GetText(); } if( (mel = mElem->FirstChildElement("geocity_path")) && (mel->GetText()) ) { geocity_path_ = mel->GetText(); if(!checkPath(geocity_path_, false, true, mes)) { exit(mes); } } if( (mel = mElem->FirstChildElement("socket_path")) && (mel->GetText()) ) { server_socket_path_ = mel->GetText(); if(!checkPath(server_socket_path_, true, true, mes)) { exit(mes); } if(boost::filesystem::exists(server_socket_path_)) { unlink(server_socket_path_.c_str()); } } if( (mel = mElem->FirstChildElement("children")) && (mel->GetText()) ) { server_children_ = atoi(mel->GetText()); } if( (mel = mElem->FirstChildElement("lock_file")) && (mel->GetText()) ) { lock_file_ = mel->GetText(); if(!checkPath(lock_file_,true, true, mes)) { exit(mes); } } if( (mel = mElem->FirstChildElement("pid_file")) && (mel->GetText()) ) { pid_file_ = mel->GetText(); if(!checkPath(pid_file_,true, true, mes)) { exit(mes); } } if( (mel = mElem->FirstChildElement("user")) && (mel->GetText()) ) { user_ = mel->GetText(); } if( (mel = mElem->FirstChildElement("templates")) ) { if( (mels = mel->FirstChildElement("out")) && (mels->GetText()) ) { if(!checkPath(cfgFilePath + mels->GetText(),false,true, mes)) { exit(mes); } template_out_ = getFileContents(cfgFilePath + mels->GetText()); } else { exit("element template_out is not inited"); } if( (mels = mel->FirstChildElement("error")) && (mels->GetText()) ) { if(!checkPath(cfgFilePath + mels->GetText(),false,true, mes)) { exit(mes); } template_error_ = getFileContents(cfgFilePath + mels->GetText()); } else { exit("element template_error is not inited"); } } if( (mel = mElem->FirstChildElement("cookie")) ) { if( (mels = mel->FirstChildElement("name")) && (mels->GetText()) ) cookie_name_ = mels->GetText(); else { Log::warn("element cookie_name is not inited"); } if( (mels = mel->FirstChildElement("domain")) && (mels->GetText()) ) cookie_domain_ = mels->GetText(); else { Log::warn("element cookie_domain is not inited"); } if( (mels = mel->FirstChildElement("path")) && (mels->GetText()) ) cookie_path_ = mels->GetText(); else { Log::warn("element cookie_path is not inited"); } } if( (mel = mElem->FirstChildElement("mq_path")) && (mel->GetText()) ) { mq_path_ = mel->GetText(); } if( (mel = mElem->FirstChildElement("sqlite")) ) { if( (mels = mel->FirstChildElement("db")) && (mels->GetText()) ) { dbpath_ = mels->GetText(); if(dbpath_!=":memory:" && !checkPath(dbpath_,true, true, mes)) { exit(mes); } } else { Log::warn("element db is not inited: :memory:"); dbpath_ = ":memory:"; } if( (mels = mel->FirstChildElement("schema")) && (mels->GetText()) ) { db_dump_path_ = cfgFilePath + mels->GetText(); if(!checkPath(db_dump_path_,false, false, mes)) { exit(mes); } } } } else { exit("no server section in config file. exit"); } if( (mElem = mRoot->FirstChildElement("retargeting")) ) { int redis_retargeting_ttl = REDIS_DEFAULT_TTL; if( (mel = mElem->FirstChildElement("ttl")) && (mel->GetText()) ) { redis_retargeting_ttl = strtol(mel->GetText(),NULL,10); } for(mel = mElem->FirstChildElement("redis"); mel; mel = mel->NextSiblingElement()) { if( (mels = mel->FirstChildElement("host")) && (mels->GetText()) ) { redis_server srv; srv.host = mels->GetText(); srv.ttl = redis_retargeting_ttl; if( (mels = mel->FirstChildElement("port")) && (mels->GetText()) ) { srv.port = mels->GetText(); } redis_retargeting_.push_back(srv); } } } else { exit("no section: retargeting"); } if( (mElem = mRoot->FirstChildElement("short_term")) ) { int redis_short_term_ttl = REDIS_DEFAULT_TTL; if( (mel = mElem->FirstChildElement("ttl")) && (mel->GetText()) ) { redis_short_term_ttl = strtol(mel->GetText(),NULL,10); } for(mel = mElem->FirstChildElement("redis"); mel; mel = mel->NextSiblingElement()) { if( (mels = mel->FirstChildElement("host")) && (mels->GetText()) ) { redis_server srv; srv.host = mels->GetText(); srv.ttl = redis_short_term_ttl; if( (mels = mel->FirstChildElement("port")) && (mels->GetText()) ) { srv.port = mels->GetText(); } redis_short_term_.push_back(srv); } } } else { exit("no section: short_term"); } if( (mels = mRoot->FirstChildElement("mongo")) ) { if( (mel = mels->FirstChildElement("main")) ) { for(mElem = mel->FirstChildElement("host"); mElem; mElem = mElem->NextSiblingElement("host")) { mongo_main_host_.push_back(mElem->GetText()); } if( (mElem = mel->FirstChildElement("db")) && (mElem->GetText()) ) mongo_main_db_ = mElem->GetText(); if( (mElem = mel->FirstChildElement("set")) && (mElem->GetText()) ) mongo_main_set_ = mElem->GetText(); if( (mElem = mel->FirstChildElement("slave")) && (mElem->GetText()) ) mongo_main_slave_ok_ = strncmp(mElem->GetText(),"false", 5) > 0 ? false : true; if( (mElem = mel->FirstChildElement("login")) && (mElem->GetText()) ) mongo_main_login_ = mElem->GetText(); if( (mElem = mel->FirstChildElement("passwd")) && (mElem->GetText()) ) mongo_main_passwd_ = mElem->GetText(); } else { exit("no main section in mongo in config file. exit"); } } else { exit("no mongo section in config file. exit"); } if( (mElem = mRoot->FirstChildElement("log")) ) { if( (mel = mElem->FirstChildElement("coretime")) && (mel->GetText()) ) { logCoretime = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("key")) && (mel->GetText()) ) { logKey = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("country")) && (mel->GetText()) ) { logCountry = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("region")) && (mel->GetText()) ) { logRegion = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("context")) && (mel->GetText()) ) { logContext = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("search")) && (mel->GetText()) ) { logSearch = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("accountId")) && (mel->GetText()) ) { logAccountId = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("OutPutOfferIds")) && (mel->GetText()) ) { logOutPutOfferIds = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } } else { logCoretime = logKey = logCountry = logRegion = logContext = logSearch = logAccountId = logOutPutOfferIds = false; } delete mDoc; mIsInited = true; std::clog<<"config file loaded"<<std::endl; return mIsInited; }
bool JsonCppWrap::checkPath(const string& elUrl) const noexcept(true){ return checkPath(elUrl.c_str()); }
/**************************************************************************** * * FUNCTION: TunnelTree(CString szFindPath) * * PURPOSE: Too crude to explain, just use it * * WARNING: Only works if you use the default PopulateTree() * Not guaranteed to work on any future or existing * version of windows. Use with caution. Pretty much * ok if you're using on local drives * ****************************************************************************/ void CShellTreeCtrl::TunnelTree(CString szFindPath) { HTREEITEM subNode = GetRootItem(); CString szPathHop; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; char delimiter[]="\\"; // LPTVITEMDATA lptvid; //Long pointer to TreeView item data // HRESULT hr; LPSHELLFOLDER lpsf2=NULL; static char szBuff[MAX_PATH]; // TV_SORTCB tvscb; CFileName checkPath(szFindPath); if(!checkPath.Exist()) { MessageBox(szFindPath,"Folder not found",MB_ICONERROR); return; } if(szFindPath.ReverseFind('\\') != szFindPath.GetLength()-1) { szFindPath += "\\"; } _splitpath(szFindPath,drive,dir,fname,ext); //search the drive first bool found = false; szPathHop=drive; subNode=GetChildItem(subNode); if(subNode) { found = SearchTree(subNode,szPathHop, CShellTreeCtrl::type_drive); if(!found) { subNode = GetRootItem(); subNode = GetNextSiblingItem(subNode); Expand(subNode, TVE_EXPAND); subNode = GetChildItem(subNode); if(subNode) found = SearchTree(subNode,szPathHop, CShellTreeCtrl::type_drive); } if(found) { //break down subfolders and search char *p=strtok(dir,delimiter); while(p) { subNode = GetSelectedItem(); //expand it Expand(subNode, TVE_EXPAND); subNode = GetChildItem(subNode); if(SearchTree(subNode,p,CShellTreeCtrl::type_folder)) p=strtok(NULL,delimiter); else p=NULL; } } } }
static int cfs_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { if (checkPath(path)) return -EACCES; int index = 0, blockNum = 0, tempOff = 0, left = 0, written = 0; int fd = open(cfsFile, O_RDWR); COLA = (struct fileInfo*)mmap(0, colaSize, PROT_READ, MAP_SHARED, fd, 0); index = find(path+1,COLA); if (index == EMPTY) { munmap(COLA,colaSize); close(fd); return -ENOENT; } blockNum = COLA[index].blockNum; munmap(COLA,colaSize); tempOff = offset; if (tempOff > block) { FAT = (int*)mmap(0, FATSize, PROT_READ, MAP_SHARED, fd, OFFC); while (tempOff > block) { blockNum = FAT[blockNum]; tempOff = tempOff - block; } munmap(FAT,FATSize); } if (tempOff + size > block) { data = (char*)mmap(0,block,PROT_READ | PROT_WRITE,MAP_SHARED,fd,OFFF + blockNum*block); memcpy(data + tempOff, buf, block - tempOff); munmap(data,block); written = block - tempOff; left = size - (block - tempOff); FAT = (int*)mmap(0, FATSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, OFFC); //if (FAT[blockNum] == EMPTY) FAT[blockNum] = searchFAT(FAT); if (FAT[blockNum] == EMPTY) { FAT[blockNum] = END; munmap(FAT,FATSize); return -ENOMEM; } blockNum = FAT[blockNum]; munmap(FAT,FATSize); while (left > 0) { if (left > block) { data = (char*)mmap(0,block,PROT_READ | PROT_WRITE,MAP_SHARED,fd,OFFF + blockNum*block); memcpy(data, buf + written, block); munmap(data,block); FAT = (int*)mmap(0, FATSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, OFFC); //if (FAT[blockNum] == EMPTY) FAT[blockNum] = searchFAT(FAT); if (FAT[blockNum] == EMPTY) { FAT[blockNum] = END; munmap(FAT,FATSize); return -ENOMEM; } blockNum = FAT[blockNum]; munmap(FAT,FATSize); left = left - block; written += block; } else { data = (char*)mmap(0,block,PROT_READ | PROT_WRITE,MAP_SHARED,fd,OFFF + blockNum*block); memcpy(data, buf + written, left); munmap(data,block); FAT = (int*)mmap(0, FATSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, OFFC); int cur = FAT[blockNum]; int temp = 0; while (FAT[cur] != EMPTY && FAT[cur] != END) { temp = FAT[cur]; FAT[cur] = EMPTY; cur = temp; } FAT[cur] = EMPTY; FAT[blockNum] = END; munmap(FAT,FATSize); written += left; left = 0; } } } else { data = (char*)mmap(0,block,PROT_READ | PROT_WRITE,MAP_SHARED,fd,OFFF + blockNum*block); memcpy(data + tempOff, buf, size); munmap(data,block); written += size; } COLA = (struct fileInfo*)mmap(0, colaSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); COLA[index].size = written + offset; munmap(COLA,colaSize); close(fd); return size; }
bool Hdf5Dataset::saveMap(const VecVecDouble &pose_reach, const VecVecDouble &spheres, const VecDouble &ri, const double resolution) { if(!checkPath(this->path_)) { createPath(this->path_); } const char *filepath = this->path_.c_str(); const char *name = this->filename_.c_str(); char fullpath[100]; strcpy(fullpath, filepath); strcat(fullpath, name); ROS_INFO("Saving map %s", this->filename_.c_str()); this->file_ = H5Fcreate(fullpath, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); this->group_poses_ = H5Gcreate(this->file_, "/Poses", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); this->group_spheres_ = H5Gcreate(this->file_, "/Spheres", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); ROS_INFO("Saving poses in reachability map"); const hsize_t ndims = 2; const hsize_t ncols = 10; int posSize =pose_reach.size(); int chunk_size; int PY = 10; if (posSize % 2) { chunk_size = (posSize / 2) + 1; } else { chunk_size = (posSize / 2); } // Create Dataspace hsize_t dims[ndims] = {0, ncols}; // Starting with an empty buffer hsize_t max_dims[ndims] = {H5S_UNLIMITED, ncols}; // Creating dataspace hid_t file_space = H5Screate_simple(ndims, dims, max_dims); // Create Dataset Property list hid_t plist = H5Pcreate(H5P_DATASET_CREATE); H5Pset_layout(plist, H5D_CHUNKED); hsize_t chunk_dims[ndims] = {chunk_size, ncols}; H5Pset_chunk(plist, ndims, chunk_dims); // Create the datset this->poses_dataset_ = H5Dcreate(this->group_poses_, "poses_dataset", H5T_NATIVE_FLOAT, file_space, H5P_DEFAULT, plist, H5P_DEFAULT); // Closing resources H5Pclose(plist); H5Sclose(file_space); // Creating the first buffer hsize_t nlines = chunk_size; float *buffer = new float[nlines * ncols]; float **dset1_data = new float *[nlines]; for (hsize_t i = 0; i < nlines; ++i) { dset1_data[i] = &buffer[i * ncols]; } // Data for the first chunk for (int i = 0; i < chunk_size; i++) { for (int j = 0; j < PY; j++) { dset1_data[i][j] = pose_reach[i][j]; } } // Memory dataspace indicating size of the buffer dims[0] = chunk_size; dims[1] = ncols; hid_t mem_space = H5Screate_simple(ndims, dims, NULL); // Extending dataset dims[0] = chunk_size; dims[1] = ncols; H5Dset_extent(this->poses_dataset_, dims); // Selecting hyperslab on the dataset file_space = H5Dget_space(this->poses_dataset_); hsize_t start[2] = {0, 0}; hsize_t count[2] = {chunk_size, ncols}; H5Sselect_hyperslab(file_space, H5S_SELECT_SET, start, NULL, count, NULL); // Writing buffer to the dataset H5Dwrite(this->poses_dataset_, H5T_NATIVE_FLOAT, mem_space, file_space, H5P_DEFAULT, buffer); // Closing file dataspace H5Sclose(file_space); // Data for the Second chunk for (int i = chunk_size; i < posSize; i++) { for (int j = 0; j < PY; j++) { dset1_data[i - chunk_size][j] = pose_reach[i][j]; } } // Resizing new memory dataspace indicating new size of the buffer dims[0] = posSize - chunk_size; dims[1] = ncols; H5Sset_extent_simple(mem_space, ndims, dims, NULL); // Extend dataset dims[0] = posSize; dims[1] = ncols; H5Dset_extent(this->poses_dataset_, dims); // Selecting hyperslab file_space = H5Dget_space(this->poses_dataset_); start[0] = chunk_size; start[1] = 0; count[0] = posSize - chunk_size; count[1] = ncols; H5Sselect_hyperslab(file_space, H5S_SELECT_SET, start, NULL, count, NULL); // Writing buffer to dataset H5Dwrite(this->poses_dataset_, H5T_NATIVE_FLOAT, mem_space, file_space, H5P_DEFAULT, buffer); // Closing all the resources delete[] dset1_data; delete[] buffer; // Creating Sphere dataset ROS_INFO("Saving spheres in Reachability map"); hid_t sphere_dataspace; const int SX = spheres.size(); const int SY = 4; hsize_t dims2[2]; // dataset dimensions dims2[0] = SX; dims2[1] = SY; double dset2_data[SX][SY]; for(int i=0;i<spheres.size();++i) { for(int j=0;j<spheres[i].size();++j) { dset2_data[i][j] = spheres[i][j]; } for (int j = 3; j < SY; j++) { dset2_data[i][j] = ri[i]; } } sphere_dataspace = H5Screate_simple(2, dims2, NULL); this->sphere_dataset_ = H5Dcreate2(this->group_spheres_, "sphere_dataset", H5T_NATIVE_DOUBLE, sphere_dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); H5Dwrite(this->sphere_dataset_, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, dset2_data); // Creating attribute hsize_t attr_dims; float attr_data[1]; attr_data[0] = resolution; attr_dims = 1; sphere_dataspace = H5Screate_simple(1, &attr_dims, NULL); this->attr_ = H5Acreate2(this->sphere_dataset_, "Resolution", H5T_NATIVE_FLOAT, sphere_dataspace, H5P_DEFAULT, H5P_DEFAULT); H5Awrite(this->attr_, H5T_NATIVE_FLOAT, attr_data); //H5Aclose(this->attr_); // Closing all H5Sclose(sphere_dataspace); H5Sclose(file_space); H5Sclose(mem_space); close(); }
static _TCHAR* findLibrary(_TCHAR* library, _TCHAR* program) { _TCHAR* c; _TCHAR* path; _TCHAR* fragment; _TCHAR* result; _TCHAR* dot = _T_ECLIPSE("."); size_t progLength, pathLength; size_t fragmentLength; struct _stat stats; if (library != NULL) { path = checkPath(library, programDir, 1); if (_tstat(path, &stats) == 0 && (stats.st_mode & S_IFDIR) != 0) { /* directory, find the highest version eclipse_* library */ result = findFile(path, _T_ECLIPSE("eclipse")); } else { /* file, return it */ result = _tcsdup(path); } if (path != library) free(path); return result; } /* build the equinox.launcher fragment name */ fragmentLength = _tcslen(DEFAULT_EQUINOX_STARTUP) + 1 + _tcslen(wsArg) + 1 + _tcslen(osArg) + 1 + _tcslen(osArchArg) + 1; fragment = malloc(fragmentLength * sizeof(_TCHAR)); _tcscpy(fragment, DEFAULT_EQUINOX_STARTUP); _tcscat(fragment, dot); _tcscat(fragment, wsArg); _tcscat(fragment, dot); _tcscat(fragment, osArg); //!(fragmentOS.equals(Constants.OS_MACOSX) && !Constants.ARCH_X86_64.equals(fragmentArch)) #if !(defined(MACOSX) && !defined(__x86_64__)) /* The Mac fragment covers both archs and does not have that last segment */ _tcscat(fragment, dot); _tcscat(fragment, osArchArg); #endif progLength = pathLength = _tcslen(programDir); #ifdef MACOSX pathLength += 9; #endif path = malloc( (pathLength + 1 + 7 + 1) * sizeof(_TCHAR)); _tcscpy(path, programDir); if (!IS_DIR_SEPARATOR(path[progLength - 1])) { path[progLength] = dirSeparator; path[progLength + 1] = 0; } #ifdef MACOSX _tcscat(path, _T_ECLIPSE("../../../")); #endif _tcscat(path, _T_ECLIPSE("plugins")); c = findFile(path, fragment); free(fragment); if (c == NULL) return c; fragment = c; result = findFile(fragment, _T_ECLIPSE("eclipse")); free(fragment); free(path); return result; }
// Check whether we can find $PATH/bin/java.exe // Returns the Java version found (e.g. 1006 for 1.6) or 0 in case of error. static int checkBinPath(CPath *inOutPath) { inOutPath->addPath("bin"); return checkPath(inOutPath); }