Ejemplo n.º 1
0
int
main(int argc, char **argv)
{
	int		c, i;
	char		**pathv;
	char		*manpath = NULL;
	static struct man_node *mandirs = NULL;
	int		bmp_flags = 0;
	int		ret = 0;
	char		*opts;
	char		*mwstr;
	int		catman = 0;

	(void) setlocale(LC_ALL, "");
	(void) strcpy(language, setlocale(LC_MESSAGES, (char *)NULL));
	if (strcmp("C", language) != 0)
		(void) strlcpy(localedir, language, MAXPATHLEN);

#if !defined(TEXT_DOMAIN)
#define	TEXT_DOMAIN "SYS_TEST"
#endif
	(void) textdomain(TEXT_DOMAIN);

	if (strcmp(__progname, "apropos") == 0) {
		apropos++;
		opts = "M:ds:";
	} else if (strcmp(__progname, "whatis") == 0) {
		apropos++;
		whatis++;
		opts = "M:ds:";
	} else if (strcmp(__progname, "catman") == 0) {
		catman++;
		makewhatis++;
		opts = "P:M:w";
	} else if (strcmp(__progname, "makewhatis") == 0) {
		makewhatis++;
		makewhatishere++;
		manpath = ".";
		opts = "";
	} else {
		opts = "FM:P:T:adfklprs:tw";
		if (argc > 1 && strcmp(argv[1], "-") == 0) {
			pager = "cat";
			optind++;
		}
	}

	opterr = 0;
	while ((c = getopt(argc, argv, opts)) != -1) {
		switch (c) {
		case 'M':	/* Respecify path for man pages */
			manpath = optarg;
			break;
		case 'a':
			all++;
			break;
		case 'd':
			debug++;
			break;
		case 'f':
			whatis++;
			/*FALLTHROUGH*/
		case 'k':
			apropos++;
			break;
		case 'l':
			list++;
			all++;
			break;
		case 'p':
			printmp++;
			break;
		case 's':
			mansec = optarg;
			sargs++;
			break;
		case 'r':
			lintout++;
			break;
		case 't':
			psoutput++;
			break;
		case 'T':
		case 'P':
		case 'F':
			/* legacy options, compatibility only and ignored */
			break;
		case 'w':
			makewhatis++;
			break;
		case '?':
		default:
			if (apropos)
				usage_whatapro();
			else if (catman)
				usage_catman();
			else if (makewhatishere)
				usage_makewhatis();
			else
				usage_man();
		}
	}
	argc -= optind;
	argv += optind;

	if (argc == 0) {
		if (apropos) {
			(void) fprintf(stderr, gettext("%s what?\n"),
			    __progname);
			exit(1);
		} else if (!printmp && !makewhatis) {
			(void) fprintf(stderr,
			    gettext("What manual page do you want?\n"));
			exit(1);
		}
	}

	init_bintoman();
	if (manpath == NULL && (manpath = getenv("MANPATH")) == NULL) {
		if ((manpath = getenv("PATH")) != NULL)
			bmp_flags = BMP_ISPATH | BMP_APPEND_DEFMANDIR;
		else
			manpath = DEFMANDIR;
	}
	pathv = split(manpath, ':');
	mandirs = build_manpath(pathv, bmp_flags);
	freev(pathv);
	fullpaths(&mandirs);

	if (makewhatis) {
		do_makewhatis(mandirs);
		exit(0);
	}

	if (printmp) {
		print_manpath(mandirs);
		exit(0);
	}

	/* Collect environment information */
	if (isatty(STDOUT_FILENO) && (mwstr = getenv("MANWIDTH")) != NULL &&
	    *mwstr != '\0') {
		if (strcasecmp(mwstr, "tty") == 0) {
			struct winsize	ws;

			if (ioctl(0, TIOCGWINSZ, &ws) != 0)
				warn("TIOCGWINSZ");
			else
				manwidth = ws.ws_col;
		} else {
			manwidth = (int)strtol(mwstr, (char **)NULL, 10);
			if (manwidth < 0)
				manwidth = 0;
		}
	}
	if (manwidth != 0) {
		DPRINTF("-- Using non-standard page width: %d\n", manwidth);
	}

	if (pager == NULL) {
		if ((pager = getenv("PAGER")) == NULL || *pager == '\0')
			pager = PAGER;
	}
	DPRINTF("-- Using pager: %s\n", pager);

	for (i = 0; i < argc; i++) {
		char		*cmd;
		static struct man_node *mp;
		char		*pv[2];

		/*
		 * If full path to command specified, customize
		 * the manpath accordingly.
		 */
		if ((cmd = strrchr(argv[i], '/')) != NULL) {
			*cmd = '\0';
			if ((pv[0] = strdup(argv[i])) == NULL)
				err(1, "strdup");
			pv[1] = NULL;
			*cmd = '/';
			mp = build_manpath(pv,
			    BMP_ISPATH | BMP_FALLBACK_DEFMANDIR);
		} else {
			mp = mandirs;
		}

		if (apropos)
			whatapro(mp, argv[i]);
		else
			ret += manual(mp, argv[i]);

		if (mp != NULL && mp != mandirs) {
			free(pv[0]);
			free_manp(mp);
		}
	}

	return (ret == 0 ? 0 : 1);
}
 /**
  * This method will be invoked second, the argument data is what exactly
  * you serialized at method "serialize", that means the data is not given by
  * system, it's given by your own serialize method. So the format of data is
  * designed by yourself, and deserialize it here as you serialize it in 
  * "serialize" method.
  */
 TreeNode *deserialize(string data) {
     vector<string> strs = split(data, ',');
     return _deserialize(strs);
 }
Ejemplo n.º 3
0
void cv::split(const Mat& src, vector<Mat>& mv)
{
    split(_InputArray(src), _OutputArray(mv));
}
Ejemplo n.º 4
0
list<PropTerm> PropTerm::ontic_prog(const OnticAction& ontic_action)
{
    list<PropTerm> progression; //Maybe need to make current PropTerm split into some PropTerms

    vector<int> missing_atom;
    vector<PropTerm> conditions; //convert each con in effect triple to PropTerm 
    for (size_t eff_i = 0; eff_i < ontic_action.con_eff.size(); eff_i++) {
        ConEffect cur_con_eff = ontic_action.con_eff[eff_i];  //current effect triple         
        //convert vector<int> to PropTerm
        PropTerm condition(length);
        for (size_t i = 0; i < cur_con_eff.condition.size(); i++) {
            condition.literals.set(cur_con_eff.condition[i], true);
        }
        conditions.push_back(condition);
        //check current PropTerm. Mostly, splitting is necessary 
        if (!(this->entails(condition) || this->entails(condition.negation()))) {            
            // 把condition里面出现,但this里面没有出现过的原子加入missing_atom里面
            for (int l = 1; l <= length/2; ++ l) {
                int pos = (l - 1) * 2;
                int neg = (l - 1) * 2 + 1;
                if (! this->literals[pos] && ! this->literals[neg] && 
                        (condition.literals[pos] || condition.literals[neg])) {
                    missing_atom.push_back(l);
                }
            }
        }
    }

    if (missing_atom.empty())
        progression.push_back(*this);
    else {
        list<PropTerm> splitting_result;
        PropTerm cur_propTerm = *this;
        split(missing_atom, 0, cur_propTerm, splitting_result);
        progression.insert(progression.end(), splitting_result.begin(), 
                splitting_result.end());
    }

    //begin ontic progression for each PropTerm (many PropTerms are split by current PropTerm)
    for (list<PropTerm>::iterator it = progression.begin(); it != progression.end(); ++it) {
        PropTerm origin = *it;//保存没做之前的状态,用作判断条件
        for (size_t eff_i = 0; eff_i < ontic_action.con_eff.size(); ++eff_i) {
            if (origin.entails(conditions[eff_i])) {
                // deal with the elements in the lit set
                for (size_t lit_i = 0; lit_i < ontic_action.con_eff[eff_i].lits.size(); ++lit_i) {
                    size_t pos = ontic_action.con_eff[eff_i].lits[lit_i];
                    if (pos % 2 == 0) {
                        // positive literal
                        it->literals.set(pos, true);
                        it->literals.set(pos+1, false);
                    } else {
                        // negative literal
                        it->literals.set(pos, true);
                        it->literals.set(pos-1, false);
                    }
                }
            }
        }
    }
    
    return progression;
}
Ejemplo n.º 5
0
/**
 * Creates and returns a PropertyMap type from a string formatted as a Java properties file.
 *
 * @param propertyString A string formatted as a Java properties file containing name/value pairs.
 * @return A PropertyMap comprised of the name/value pairs in the propertyString.
 */
PropertyMap Updater::getPropertyMap(std::string propertyString)
{
  // Create an empty map associating a PropertyType with a string value
  PropertyMap propertyMap;

  // Create a vector to hold the lines in the properties string
  std::vector<std::string> lines;

  // Split propertyString into lines and store in a vector
  lines = split(propertyString, '\n');

  // Loop over all tokens
  for (unsigned int i = 0; i < lines.size(); i++)
  {
    std::string line = lines[i];

    // Create a new vector to hold the name and value
    std::vector<std::string> pair;

    // If the "=" character is found in this line
    if (line.find("=") != std::string::npos)
    {
      // Split the line into a property/value pair
      pair = split(line, '=');

      // Get the property name
      std::string property = pair[0];

      // Get the property value
      std::string value = pair[1];

      // FIXME! This switch can be removed with a map. ~JJB 20140404 15:06

      // If the property is "item_id"
      if (property == "item_id")
      {
        // Insert PropertyType ITEM_ID and the value
        propertyMap.insert(PropertyMap::value_type(ITEM_ID, value));
        // If the property is "url"
      }
      else if (property == "url")
      {
        // Insert PropertyType URL and the value
        propertyMap.insert(PropertyMap::value_type(URL, value));
        // If the property is "client_key"
      }
      else if (property == "client_key")
      {
        // Insert PropertyType CLIENT_KEY and the value
        propertyMap.insert(PropertyMap::value_type(CLIENT_KEY, value));
      }
      else if (property == "username")
      {
        // Insert the username into the map
        propertyMap.insert(PropertyMap::value_type(USERNAME, value));
      }
      else if (property == "password")
      {
        // Insert the password into the map
        propertyMap.insert(PropertyMap::value_type(PASSWORD, value));
      }
    }
  }

  // Return the property map
  return propertyMap;
}
Ejemplo n.º 6
0
ObjModel::ObjModel(std::string fileName, Singleton* s): s(s) {
    xpos = ypos = zpos = xrot = yrot = zrot = 0;
    this->obj = this;

    if(fileName == ""){
        return;
    }

    std::string dirName = fileName;
    if (dirName.rfind("/") != std::string::npos)
        dirName = dirName.substr(0, dirName.rfind("/"));
    if (dirName.rfind("\\") != std::string::npos)
        dirName = dirName.substr(0, dirName.rfind("\\"));
    if (fileName == dirName)
        dirName = "";


    std::ifstream pFile(fileName.c_str());

    if (!pFile.is_open()) {
        //std::cout << "Could not open file " << fileName << std::endl;
        return;
    }


    ObjGroup *currentGroup = new ObjGroup();
    currentGroup->materialIndex = -1;


    while (!pFile.eof()) {
        std::string line;
        std::getline(pFile, line);

        line = replace(line, "\t", " ");
        while (line.find("  ") != std::string::npos)
            line = replace(line, "  ", " ");
        if (line == "")
            continue;
        if (line[0] == ' ')
            line = line.substr(1);
        if (line == "")
            continue;
        if (line[line.length() - 1] == ' ')
            line = line.substr(0, line.length() - 1);
        if (line == "")
            continue;
        if (line[0] == '#')
            continue;

        std::vector<std::string> params = split(line, " ");
        params[0] = toLower(params[0]);

        if (params[0] == "v")
            vertices.push_back(new Vec3f((float) atof(params[1].c_str()), (float) atof(params[2].c_str()),
                                         (float) atof(params[3].c_str())));
        else if (params[0] == "vn")
            normals.push_back(new Vec3f((float) atof(params[1].c_str()), (float) atof(params[2].c_str()),
                                        (float) atof(params[3].c_str())));
        else if (params[0] == "vt")
            texcoords.push_back(new Vec2f((float) atof(params[1].c_str()), (float) atof(params[2].c_str())));
        else if (params[0] == "f") {
            for (size_t ii = 4; ii <= params.size(); ii++) {
                Face face;

                for (size_t i = ii - 3; i < ii; i++)    //magische forlus om van quads triangles te maken ;)
                {
                    Vertex vertex;
                    std::vector<std::string> indices = split(params[i == (ii - 3) ? 1 : i], "/");
                    if (indices.size() >= 1)    //er is een positie
                        vertex.position = atoi(indices[0].c_str()) - 1;
                    if (indices.size() == 2)        //alleen texture
                        vertex.texcoord = atoi(indices[1].c_str()) - 1;
                    if (indices.size() == 3)        //v/t/n of v//n
                    {
                        if (indices[1] != "")
                            vertex.texcoord = atoi(indices[1].c_str()) - 1;
                        vertex.normal = atoi(indices[2].c_str()) - 1;
                    }
                    face.vertices.push_back(vertex);
                }
                currentGroup->faces.push_back(face);
            }
        }
        else if (params[0] == "s") {//smoothing
        }
        else if (params[0] == "mtllib") {
            loadMaterialFile(dirName + "/" + params[1], dirName);
        }
        else if (params[0] == "usemtl") {
            if (currentGroup->faces.size() != 0)
                groups.push_back(currentGroup);
            currentGroup = new ObjGroup();
            currentGroup->materialIndex = -1;

            for (size_t i = 0; i < materials.size(); i++) {
                MaterialInfo *info = materials[i];
                if (info->name == params[1]) {
                    currentGroup->materialIndex = i;
                    break;
                }
            }
            if (currentGroup->materialIndex == -1) {
                //std::cout << "Could not find material name " << params[1] << std::endl;
            }
        }
    }
    groups.push_back(currentGroup);

    CalcMinVertex();
    CalcMaxVertex();
    InitBoundingSpheres();
    CalcBoundingSpheres();
}
Ejemplo n.º 7
0
		static std::vector<std::string> split(const std::string &input, const std::string &delimiter)
		{
			std::vector<std::string> output;
			split(output, input, delimiter);
			return output;
		}
Ejemplo n.º 8
0
int MyProcessDatFileIII(char* DatFileBuffer, int procid, vector<int> AllColumnIDList, vector<vector<int> > ColKeyToAllAlleleByPopList, vector<vector<vector<int> > >& AllAlleleByPopList, vector<std::string>& FullAccessionNameList, vector<std::string>& IndivPerPop, vector<int>& AllAlleles, std::string Rarify)
{
	//declare variables
	std::string foo;
	vector<std::string> foovector;
	std::string OldLocusName;
	std::string CurrLocusName;
	vector<std::string> LocusNames;
	vector<vector<std::string> > ActiveAlleleList;
	vector<std::string> OldAlleles;
	vector<vector<std::string> > TempList2d;
	vector<std::string> FilteredData;
	vector<std::string> ListToFilter;
	std::string IsNewPop = "no";
	vector<std::string>::iterator it;
	
	//initialize important data structures, unsized
	vector<vector<set<int> > > AllAlleleByPopListSet; //structure of this 3D vector is:
	// { { {pop1,loc1 alleles},{pop1,loc2 alleles},...}, { {pop2,loc1 alleles},{pop2,loc2 alleles},...} } }
	// this is the same structure as the vector<vector<vector<int> > > AllAlleleByPopList
	// if Rarify == "yes", AllAlleleByPopList just becomes ByPop3d.  if Rarify == "no", ByPop3d is reduced
	// to unique alleles at each locus using AllAlleleByPopListSet, then converted back into the vector
	// AllAlleleByPopList, which is updated as a reference


	unsigned int i,j,k,l;
	vector<std::string> bufvec;
	std::string NewPopID;
	std::string OldPopID = "init*@#rt4"; //use an unlikely population name for the initialization value

	if (procid == 0) cout << "  Reading data matrix...\n";
	//start the clock
	time_t startm,endm;
	time (&startm);

	//put giant char array buffer into a stream, then delete the buffer to save memory 
	stringstream s(DatFileBuffer);
	strcpy(DatFileBuffer,""); //clear char* 
	
	
	//read buffer into a vector, one line per item
	while (getline(s, foo))//get line from s, put in foo, consecutively
	{
		bufvec.push_back(foo);  
	}
	
	s.str(""); //clear stringstream
	int row = bufvec.size();
		
	//sort vector so that individuals from the same population form consecutive elements
	std::sort(bufvec.begin(), bufvec.end()); //no need to use fancy sort, lexicographic should be fine
		
	//split lines of bufvec into 2d vector
	vector<vector<std::string> > bufvec2d(bufvec.size()); 
	for (i=0;i<bufvec.size();++i) bufvec2d[i] = split(bufvec[i]);
	vector<std::string>().swap(bufvec); //clear bufvec
	
	//stop the clock
	time (&endm);
	double dif = difftime (endm,startm);
	if (procid == 0) 
	{
		if (dif==1) cout << "    " << dif << " second.\n";	
		else cout << "    " << dif << " seconds.\n";
	}
	
	//convert alleles to integer coding to save memory, vector access order 2
	if (procid == 0) 
	{
		cout << "  Recoding data...\n";
		time (&startm);
	}

	vector<vector<int> > bufvec2dint(bufvec2d.size(), vector<int>(bufvec2d[0].size())); //declare and size vector to hold new integer coded alleles
	unsigned int iz = ColKeyToAllAlleleByPopList.size();
	for (unsigned int i=0;i<iz;++i) //go thru each locus
	{
		//get all alleles at the locus
		vector<std::string> AllelesEncountered; //will contain the unique set of alleles at the locus
		unsigned int kz = bufvec2d.size();
		for (unsigned int k=0;k<kz;++k) //go thru all individuals
		{
			unsigned int jz = ColKeyToAllAlleleByPopList[i].size();
			for (unsigned int j=0;j<jz;++j) //get all alleles for an individual at this locus, then move to next indiv
			{
				int ColIndex = ColKeyToAllAlleleByPopList[i][j];
				std::string a = bufvec2d[k][ColIndex];  
				if (a == "9999") bufvec2dint[k][ColIndex] = -9999; //add the missing data value
				else
				{
					int AlleleInt; //the new, integerized, name of the allele
					std::vector<std::string>::iterator itr = std::find(AllelesEncountered.begin(), AllelesEncountered.end(), a);
					if (itr != AllelesEncountered.end()) //the allele has been found before
					{
						AlleleInt = itr - AllelesEncountered.begin(); //convert itr to index, the index is the integerized allele name
						bufvec2dint[k][ColIndex] = AlleleInt; //add the new name
					}
					else // you have a new allele
					{
						AllelesEncountered.push_back(a); //add new allele to list of those encountered
						AlleleInt = AllelesEncountered.size() - 1;  //calculate integerized allele name, starts at 0
						bufvec2dint[k][ColIndex] = AlleleInt;
					}
				}
			}
		}
	}
	
	//stop the clock
	if (procid == 0) 
	{
		time (&endm);
		dif = difftime (endm,startm);
		if (dif==1) cout << "    " << dif << " second.\n";	
		else cout << "    " << dif << " seconds.\n";	
	}

	
	if (procid == 0) cout << "  Building data structures...\n";
	time (&startm);
	
	//simplify bufvec2d by retaining only the first column, with POPID, then swap clear to save memory
	vector<string> PopIDvec;
	for (i=0;i<bufvec2d.size();++i)
		PopIDvec.push_back(bufvec2d[i][0]);
	vector<vector<std::string> >().swap(bufvec2d); //clear bufvec2d

	//break up vector into a 3d vector by population:  { { {pop1ind1elems},{pop1ind2elems},...}, { {pop2ind1elems},{pop2ind2elems},...} }
	vector<vector<vector<int> > > ByPop3d;
	for (i=0;i<bufvec2dint.size();++i)
	{
		//NewPopID = bufvec2d[i][0];  //access string in bufvec2d
		NewPopID = PopIDvec[i];
		IndivPerPop.push_back(NewPopID); //add the pop ID to a list to calc pop sizes later

		if (NewPopID != OldPopID) //then create a new population in ByPop3D
		{
			ByPop3d.resize(ByPop3d.size() + 1);
			
			//add the new population name to the AccessionNameList
			FullAccessionNameList.push_back(NewPopID);
		}
		
		//push row of integer elements on current line, onto last item of ByPop3d, which might be a new population as added just above
		//remember that the first three columns are 0 in bufvec2dint, so will also be 0 in ByPop3d
		ByPop3d[ByPop3d.size()-1].push_back(bufvec2dint[i]);
		
		OldPopID = NewPopID;
	}
	vector<vector<int> >().swap(bufvec2dint); //clear bufvec2dint, the integerized data is in ByPop3d

	//stop the clock
	time (&endm);
	if (procid == 0) 
	{
		dif = difftime (endm,startm);
		if (dif==1) cout << "    " << dif << " second.\n";	
		else cout << "    " << dif << " seconds.\n";	
	}

/*	//print out ByPop3d
	for (i=0;i<ByPop3d.size();++i)
	{
		cout << "Pop" << i << "\n";
		for (j=0;j<ByPop3d[i].size();++j)
		{
			cout << " Ind" << j << "  ";
			for (k=0;k<ByPop3d[i][j].size();++k)
			{
				cout << ByPop3d[i][j][k] << ",";
			}
			cout << "\n";
		}
	
	}
*/

	if (procid == 0) cout << "  Condensing data...\n";
	time (&startm);

	//When Rarify=yes, information on allele frequencies must be retained so all alleles are
	//placed into the AllAlleleByPopList (excluding -9999 missing data).  When Rarify=no, 
	//all alleles are passaged through a set (AllAlleleByPopListSet) so that only unique 
	//alleles end up in AllAlleleByPopList.
	if (Rarify == "yes")
	{
		//resize AllAlleleByPopList
		AllAlleleByPopList.resize(ByPop3d.size());//resize number of populations
		for (i=0;i<AllAlleleByPopList.size();++i)
		{
			AllAlleleByPopList[i].resize(ColKeyToAllAlleleByPopList.size()); //resize number of loci
		}
		
		//calculate size of AllAlleles
		AllAlleles.reserve(row*AllColumnIDList.size());

		//condense alleles by locus in AllAllelesByPopList, within each population
		int AlleleIndex;
		for (i=0;i<ByPop3d.size();++i) //go thru pops
		{
			for (j=0;j<ByPop3d[i].size();++j) //go thru indivs
			{
				for (k=0;k<ColKeyToAllAlleleByPopList.size();++k) //go through each locus
				{
					for (l=0;l<ColKeyToAllAlleleByPopList[k].size();++l) //assign columns to loci
					{
						AlleleIndex = ColKeyToAllAlleleByPopList[k][l];
						int NewAllele = ByPop3d[i][j][AlleleIndex]; //get the allele in the specified column
						AllAlleles.push_back(NewAllele); //add the allele to the list of all alleles, missing data included
						if (NewAllele != -9999) //exclude missing data
							AllAlleleByPopList[i][k].push_back(NewAllele); //add the allele to the set of unique alleles at locus k, pop i	
					}
				}
			}
		}
		
 		//stop the clock on Condensing data...
		time (&endm);
		if (procid == 0) 
		{
			dif = difftime (endm,startm);
			if (dif==1) cout << "    " << dif << " second.\n";	
			else cout << "    " << dif << " seconds.\n";	
		}
	}
	else if (Rarify == "no")
	{
		//resize AllAlleleByPopListSet
		AllAlleleByPopListSet.resize(ByPop3d.size());//resize number of populations
		for (i=0;i<AllAlleleByPopListSet.size();++i)
		{
			AllAlleleByPopListSet[i].resize(ColKeyToAllAlleleByPopList.size()); //resize number of loci
																		   //the index in ColKey is the locus index in AllAllelesByPopList level 2
																		   //the value of ColKey is the index of the allele in ByPop3d level 3
		}
		
		//calculate size of AllAlleles
		AllAlleles.reserve(row*AllColumnIDList.size());

		//condense alleles by locus in AllAllelesByPopListSet, within each population
		int AlleleIndex;
		for (i=0;i<ByPop3d.size();++i) //go thru pops
		{
			for (j=0;j<ByPop3d[i].size();++j) //go thru indivs
			{
				for (k=0;k<ColKeyToAllAlleleByPopList.size();++k) //go through each locus
				{
					for (l=0;l<ColKeyToAllAlleleByPopList[k].size();++l) //assign columns to loci
					{
						AlleleIndex = ColKeyToAllAlleleByPopList[k][l];
						int NewAllele = ByPop3d[i][j][AlleleIndex]; //get the allele in the specified column
						AllAlleles.push_back(NewAllele); //add the allele to the list of all alleles, missing data included
						if (NewAllele != -9999) //exclude missing data
							AllAlleleByPopListSet[i][k].insert(NewAllele); //add the allele to the set of unique alleles at locus k, pop i	
					}
				}
			}
		}
	
		//stop the clock on Condensing data...
		time (&endm);
		if (procid == 0) 
		{
			dif = difftime (endm,startm);
			if (dif==1) cout << "    " << dif << " second.\n";	
			else cout << "    " << dif << " seconds.\n";	
		}
		
		//start the clock on Converting...
		time_t startd,endd;
		if (procid == 0) 
		{
			cout << "  Converting data structures...\n";
			time (&startd);
		}

		//resize AllAlleleByPopList
		AllAlleleByPopList.resize(ByPop3d.size());//resize number of populations
		for (i=0;i<AllAlleleByPopList.size();++i)
		{
			AllAlleleByPopList[i].resize(ColKeyToAllAlleleByPopList.size()); //resize number of loci
		}
		//convert set to vector for further processing
		for (i=0;i<AllAlleleByPopList.size();++i)
		{
			for (j=0;j<AllAlleleByPopList[i].size();++j)
			{
				vector<int> ttvec(AllAlleleByPopListSet[i][j].begin(), AllAlleleByPopListSet[i][j].end()); //use constructor to convert set to vector	
				AllAlleleByPopList[i][j] = ttvec;
			}
		}
		vector<vector<set<int> > >().swap(AllAlleleByPopListSet); //clear variable, no longer needed
	
		//stop the clock on Converting...
		if (procid == 0) 
		{
			time (&endd);
			dif = difftime (endd,startd);
			if (dif==1) cout << "    " << dif << " second.\n";	
			else cout << "    " << dif << " seconds.\n";	
		}
	}
	
	vector<vector<vector<int> > >().swap(ByPop3d); //clear ByPop3d
			
	return 0;
}
Ejemplo n.º 9
0
int MyProcessVarFile(char* VarFileBuffer, vector<int>& AllColumnIDList, vector<std::string>& AllLociNameList, vector<int>& ActiveColumnIDList, vector<std::string>& ActiveLociNameList, vector<int>& TargetColumnIDList, vector<std::string>& TargetLociNameList, vector<vector<int> >& ColKeyToAllAlleleByPopList, vector<int>& ReferenceOrTargetKey, vector<int>& PloidyList, vector<std::string>& UniqLociNameList)
{
    //declare variables
    std::string foo;
    vector<std::string> foovector;
    unsigned int k;

    int i=0; // i is the row number

	std::string vfb(VarFileBuffer); //convert char* to string
    std::istringstream iss(vfb); //open string as a stream
    while (std::getline(iss, foo)) //cycle line by line, placing line in foo
    {
	    //split foo on whitespace
		foovector = split(foo);
		
		if (foovector.size() != 0) //omit the hanging last line, which has no information
		{
		
			//identify active columns with qualitative data, classify those as reference or target
			if (foovector[1] == "2") //column holds qualitative data
			{
				AllColumnIDList.push_back(i);
				AllLociNameList.push_back(foovector[0]);
				
				if ((foovector[2] == "1") && (foovector[3] == "0")) //reference variable
				{
					ActiveColumnIDList.push_back(i);
					ActiveLociNameList.push_back(foovector[0]);
				}
				else if ((foovector[2] == "0") && (foovector[3] == "1"))  //target variable
				{
					TargetColumnIDList.push_back(i);
					TargetLociNameList.push_back(foovector[0]);
				}
			}
		 
			i++;
			foovector.clear();  //zero vector foovector
		}
    }
	
	//make a key showing which loci are target and which are reference
	//this will be used later to sort out the AllAlleleByPopList
	std::string uniqloc;
	std::string currloc;
	
	//find unique locus names, retains sort order
	UniqLociNameList = unsortedRemoveDuplicates(AllLociNameList);

	//tabulate the ploidy for each locus
	PloidyList = GetPloidy(AllLociNameList, UniqLociNameList);
	
	//define 2d vector that is key to columns, size to number of unique loci
	ColKeyToAllAlleleByPopList.resize( UniqLociNameList.size() ); //size to number of loci
	int b;
	for (unsigned int i=0;i<UniqLociNameList.size();++i)
	{
		uniqloc = UniqLociNameList[i];
		for (k=0;k<AllLociNameList.size();++k)
		{
			currloc = AllLociNameList[k];
			if (currloc == uniqloc)
			{
				b = AllColumnIDList[k]; //get the corresponding value in the columnID list
				ColKeyToAllAlleleByPopList[i].push_back(b);	
			}	
		}		
	}
	
	//define a 1d vector that describes whether the loci in the ColKey are reference(0) or target(1)
	double rt;
	ReferenceOrTargetKey.resize( ColKeyToAllAlleleByPopList.size() ); //sized to same length as key
	for (unsigned int i=0;i<ColKeyToAllAlleleByPopList.size();++i)
	{
		rt=0;
		//test whether all elements are categorized as reference or as target, if not, raise error
		for (k=0;k<ColKeyToAllAlleleByPopList[i].size();++k)
		{
			b=ColKeyToAllAlleleByPopList[i][k];
			if(std::find(ActiveColumnIDList.begin(), ActiveColumnIDList.end(), b) != ActiveColumnIDList.end())
			{
   			 	//column is reference
   			 	rt=rt+0;
			} 
			else if(std::find(TargetColumnIDList.begin(), TargetColumnIDList.end(), b) != TargetColumnIDList.end())
			{
    			//column is target
    			rt=rt+1;
			}
		}
		
		//test whether columns in key represent reference or target loci
		if (rt == 0) ReferenceOrTargetKey[i] = 0; //it is a reference
		else if (  rt/ColKeyToAllAlleleByPopList[i].size() == 1 ) ReferenceOrTargetKey[i] = 1; //it is a target
		else 
		{
			cout << "ERROR:  Some loci are described as both reference and target.  Please check your var file. Quitting...\n\n";
			exit (EXIT_FAILURE);
		}
	}
	return 0;
}
Ejemplo n.º 10
0
static const string * readnewline(FormatState * fs){
	return split(fs, Newline);
}
Ejemplo n.º 11
0
Polygon* Polygon_Reader::Parse_Polygon(string line)
{
	size_t start, end, pos;
	std::string head_str, gml_str;
	std::vector<std::string> temp_str_array;
	std::vector<std::string> coord_array;

	pos = line.find_first_of("<");
	head_str = line.substr(0, pos);
	split(head_str,':',temp_str_array);
	gml_str = line.substr(pos);

	start = gml_str.find_first_of("<");
	end= gml_str.find_first_of(">");
	std::string tag = gml_str.substr(start, end - start);
	std::string tag_name = "";

	start = tag.find_first_of("<"); 
	tag_name = tag_name + tag.substr(start, tag.find_first_of(" ") - start);
	tag_name = tag_name + ">";
	tag_name.insert(1, "/");

	start = end + 1;
	end = gml_str.find(tag_name);
	gml_str = gml_str.substr(start, end - start);    //get rid of polygon tag

	start = gml_str.find_first_of("<");
	end = gml_str.find_first_of(">");
	tag = gml_str.substr(start, end - start + 1);

	tag_name = tag;
	tag_name.insert(1, "/");

	//remove the tags of the outerBoundary
	start = end + 1;
	end = gml_str.find(tag_name);
	std::string tag_value = gml_str.substr(start, end - start);
	gml_str = gml_str.substr(gml_str.find(tag_name) + tag_name.length());   //rest of the string after remove the outer Boundary part

	start = tag_value.find("<gml:coordinates");
	end = tag_value.find("</gml:coordinates");
	std::string tmp_str = tag_value.substr(start, end - start);
	std::string Coord = tmp_str.substr(tmp_str.find_first_of(">") + 1);
		
	split(Coord, ' ', coord_array);
	std::vector<std::string> xy_array;
	LinearRing* lr_OB = new LinearRing();
	for (std::string xy : coord_array){
		split(xy, ',', xy_array);
		lr_OB->Add_Point(new Point(stod(xy_array[0]), stod(xy_array[1])));
		xy_array.clear();
	}

	OuterBoundary* OB = new OuterBoundary(lr_OB);
	Polygon* poly = new Polygon(stoi(temp_str_array[1]), stoi(temp_str_array[2]), OB);

	xy_array.clear();
	coord_array.clear();

	while (gml_str != "")
	{
		start = gml_str.find_first_of("<");
		end = gml_str.find_first_of(">");
		tag = gml_str.substr(start, end - start + 1);
		if (tag.find("innerBoundaryIs")!= 0){
			tag_name = tag;
			tag_name.insert(1, "/");

			start = end + 1;
			end = gml_str.find(tag_name);
			std::string tag_value = gml_str.substr(start, end - start);
			gml_str = gml_str.substr(gml_str.find(tag_name) + tag_name.length());
			
			start = tag_value.find("<gml:coordinates");
			end = tag_value.find("</gml:coordinates");
			tmp_str = tag_value.substr(start, end - start);
			Coord = tmp_str.substr(tmp_str.find_first_of(">") + 1);
			split(Coord, ' ', coord_array);

			LinearRing* lr_IB = new LinearRing();
			for (std::string xy: coord_array){
				split(xy, ',', xy_array);
				lr_IB->Add_Point(new Point(stod(xy_array[0]), stod(xy_array[1])));
				xy_array.clear();
			}
			poly->Add_Inner_Boundary(new InnerBoundary(lr_IB));
			xy_array.clear();
	        coord_array.clear();
		}
	}

	return poly;
}
Ejemplo n.º 12
0
int main(int argc, char const *argv[]) {

      FILE *fp;
      FILE* stream;
      char buf[MAXBUF];
      char buf2[MAXBUF];
      int i=0;
      int j=0;
      char *lines[MAXBUF];
      int status;
      int wpid;

      fp=fopen(argv[1], "r");
      if (fp == NULL)
            exit(EXIT_FAILURE);

      while(fgets(buf, MAXBUF, fp)){
                  lines[i]=strdup(buf);
                  i++;
      }

      pid_t *pids = malloc(i * sizeof(pid_t));
      buffer *text = malloc (i * sizeof(buffer));
      char *cmd[MAX_ARGS];

      for (int n  = 0 ; n < i ; n++) { // Start i at 0, not at 1

            if( pipe(text[n].mypipe) == -1){
                perror("Pipe failed");
                exit(1);
              }

            pid_t pid = fork();
            if (pid == -1) {                                                  //sono nel padre, errore della fork
                  fprintf(stderr, "forking error\n");
                  exit(1);
            } else if (pid == 0){
                  printf("Sono l'%d figlio\n", n );
                  close(STDOUT_FILENO);  //closing stdout
          		close(text[n].mypipe[0]);	   //closing pipe read
                  dup2(text[n].mypipe[1], 1);                                           //sono nel figlio quindi eseguo
                  split( cmd , lines[n]);
                  execvp(cmd[0], cmd);

          		exit(EXIT_FAILURE);
            } else {
            pids[n] = pid;
            text[n].pid=pid;                                                     //sono di nuovo nel padre ma è andato a buon fine quindi mi salvo il pid del figlio
            }

      }
      for (int k=0; k<i; k++){
            printf("%d\n", pids[k] );
      }
      wpid=wait(&status);
      printf("Child with PID %ld exited with status 0x%x.\n", (long)wpid, status);
      while (j<i) {
            if (wpid == text[j].pid) {
                  close(STDIN_FILENO);  //closing stdout
          		close(text[j].mypipe[1]);	   //closing pipe read
                  stream = fdopen(text[j].mypipe[0], "r");
                  while(fgets(buf2, MAXBUF, stream)){
                              printf("%s\n", buf2 );
                  }



            }
            else if(wpid != pids[j]) {
                  printf("%d\n", pids[j] );
                  if ( kill(pids[j], SIGKILL))
                        { printf("Failur\n" );}
                  }
            j++;
      }

      fclose(fp);
  return 0;
}
Ejemplo n.º 13
0
void DiscName::test() {
	DiscData d;
	d = split( "vcd://1//dev/dvd/" );
	d = split( "vcd://1/E:/" );
	d = split( "vcd://5" );
	d = split( "vcd://" );
	d = split( "vcd:////dev/dvdrecorder" );

	d = split( "dvd://1//dev/dvd" );
	d = split( "dvd://1/E:" );
	d = split( "dvd://5" );
	d = split( "dvd://" );
	d = split( "dvd:" );
	d = split( "dvd:////dev/dvdrecorder" );

	d = split( "cdda://1//dev/dvd" );
	d = split( "cdda://1/E:" );
	d = split( "cdda://5" );
	d = split( "cdda://" );
	d = split( "cdda:////dev/dvdrecorder" );

	d = split( "dvdnav://1//dev/dvd" );
	d = split( "dvdnav://1/D:/" );
	d = split( "dvdnav://5" );
	d = split( "dvdnav://" );
	d = split( "dvdnav:////dev/dvdrecorder/" );

	d = split( "br://1//dev/dvd" );
	d = split( "br://1/D:/" );
	d = split( "br://5" );
	d = split( "br://" );
	d = split( "br:////dev/dvdrecorder/" );

	QString s;
	s = join( DVD, 4, "/dev/dvd/" );
	s = join( DVD, 2, "E:" );
	s = join( DVD, 3, "E:/" );
	s = join( DVDNAV, 5, "/dev/dvdrecorder" );
	s = join( VCD, 1, "/dev/cdrom" );
	s = join( CDDA, 10, "/dev/cdrom" );
	s = joinDVD( 1, "/dev/cdrom", false );
	s = joinDVD( 2, "/dev/cdrom/", true );
	s = joinDVD( 3, "", true );
	s = join( VCD, 3, "" );
	s = join( BLURAY, 2, "/dev/cdrom");
}
Ejemplo n.º 14
0
/*
 * This routine builds the manpage structure from MANPATH or PATH,
 * depending on flags.  See BMP_* definitions above for valid
 * flags.
 */
static struct man_node *
build_manpath(char **pathv, int flags)
{
	struct man_node *manpage = NULL;
	struct man_node *currp = NULL;
	struct man_node *lastp = NULL;
	char		**p;
	char		**q;
	char		*mand = NULL;
	char		*mandir = DEFMANDIR;
	int		s;
	struct dupnode	*didup = NULL;
	struct stat	sb;

	s = sizeof (struct man_node);
	for (p = pathv; *p != NULL; ) {
		if (flags & BMP_ISPATH) {
			if ((mand = path_to_manpath(*p)) == NULL)
				goto next;
			free(*p);
			*p = mand;
		}
		q = split(*p, ',');
		if (stat(q[0], &sb) != 0 || (sb.st_mode & S_IFDIR) == 0) {
			freev(q);
			goto next;
		}

		if (access(q[0], R_OK | X_OK) == 0) {
			/*
			 * Some element exists.  Do not append DEFMANDIR as a
			 * fallback.
			 */
			flags &= ~BMP_FALLBACK_DEFMANDIR;

			if ((currp = (struct man_node *)calloc(1, s)) == NULL)
				err(1, "calloc");

			currp->frompath = (flags & BMP_ISPATH);

			if (manpage == NULL)
				lastp = manpage = currp;

			getpath(currp, p);
			getsect(currp, p);

			/*
			 * If there are no new elements in this path,
			 * do not add it to the manpage list.
			 */
			if (dupcheck(currp, &didup) != 0) {
				freev(currp->secv);
				free(currp);
			} else {
				currp->next = NULL;
				if (currp != manpage)
					lastp->next = currp;
				lastp = currp;
			}
		}
		freev(q);
next:
		/*
		 * Special handling of appending DEFMANDIR. After all pathv
		 * elements have been processed, append DEFMANDIR if needed.
		 */
		if (p == &mandir)
			break;
		p++;
		if (*p != NULL)
			continue;
		if (flags & (BMP_APPEND_DEFMANDIR | BMP_FALLBACK_DEFMANDIR)) {
			p = &mandir;
			flags &= ~BMP_ISPATH;
		}
	}

	free_dupnode(didup);

	return (manpage);
}
Ejemplo n.º 15
0
//******************************************************************************
// Mask the Fasta file based on the coordinates in the BED file.
//******************************************************************************
void MaskFastaFromBed::MaskFasta() {

    /* Make sure that we can open all of the files successfully*/

    // open the fasta database for reading
    ifstream fa(_fastaInFile.c_str(), ios::in);
    if ( !fa ) {
        cerr << "Error: The requested fasta file (" << _fastaInFile << ") could not be opened. Exiting!" << endl;
        exit (1);
    }

    // open the fasta database for reading
    ofstream faOut(_fastaOutFile.c_str(), ios::out);
    if ( !faOut ) {
        cerr << "Error: The requested fasta output file (" << _fastaOutFile << ") could not be opened. Exiting!" << endl;
        exit (1);
    }


    /* Read the fastaDb chromosome by chromosome*/
    string fastaInLine;
    string currChromFull;
    string currChrom;
    string currDNA = "";
    currDNA.reserve(500000000);
    int fastaWidth = -1;
    bool widthSet  = false;
    int start, end, length;
    string replacement;

    while (getline(fa,fastaInLine)) {

        if (fastaInLine.find(">",0) != 0 ) {
            if (widthSet == false) {
                fastaWidth = fastaInLine.size();
                widthSet = true;
            }
            currDNA += fastaInLine;
        }
        else {
            if (currDNA.size() > 0) {

                vector<BED> bedList = _bed->bedMapNoBin[currChrom];

                /*
                    loop through each BED entry for this chrom and
                    mask the requested sequence in the FASTA file.
                */
                for (unsigned int i = 0; i < bedList.size(); i++) {
                    start = bedList[i].start;
                    end = bedList[i].end;
                    length = end - start;

                    /*
                       (1) if soft masking, extract the sequence, lowercase it,
                           then put it back
                       (2) otherwise replace with Ns
                    */
                    if (_softMask) {
                        replacement = currDNA.substr(start, length);
                        toLowerCase(replacement);
                        currDNA.replace(start, length, replacement);
                    }
                    else {
                        string hardmask(length, _maskChar);
                        currDNA.replace(start, length, hardmask);
                    }
                }
                // write the masked chrom to the output file
                PrettyPrintChrom(faOut, _useFullHeader ? currChromFull : currChrom, currDNA, fastaWidth);
            }

            // reset for the next chromosome.
            currChromFull = fastaInLine.substr(1);
            currChrom = split(currChromFull, " \t").at(0);
            currDNA = "";
        }
    }

    // process the last chromosome.
    // exact same logic as in the main loop.
    if (currDNA.size() > 0) {

        vector<BED> bedList = _bed->bedMapNoBin[currChrom];

        for (unsigned int i = 0; i < bedList.size(); i++) {
            start = bedList[i].start;
            end = bedList[i].end;
            length = end - start;

            if (_softMask) {
                replacement = currDNA.substr(start, length);
                toLowerCase(replacement);
                currDNA.replace(start, length, replacement);
            }
            else {
                string hardmask(length, _maskChar);
                currDNA.replace(start, length, hardmask);
            }
        }
        PrettyPrintChrom(faOut, _useFullHeader ? currChromFull : currChrom, currDNA, fastaWidth);
    }

    // closed for business.
    fa.close();
    faOut.close();
}
Ejemplo n.º 16
0
int
PME::split(const std::wstring & s, unsigned maxfields)
{
	return split( Text::wideToAcp( s ), maxfields );
}
Ejemplo n.º 17
0
bool HardcodedGraphicsItem::GetHDCByName(std::string text, HDC* colorHDC, HDC* maskHDC)
{
    // 1. PARSE TEXT
    // If it has an ending, then remove it:
    if (text.find("."))
        text = removeExtension(text);

    // First extract the name:
    if (text.find("hardcoded-") != 0)
        return false;

    // Possible outcome:

    // hardcoded-1-3.png --> 
    //      hardcoded-1-3 
    // --> [0] = hardcoded 
    // --> [1] = 1
    // --> [2] = 3

    // hardcoded-1.png
    // --> [0] = hardcoded
    // --> [1] = 1
    std::vector<std::string> textPattern = split(text, '-');
    if (textPattern.size() != 2 && textPattern.size() != 3) // Size must be 2 or three (see above)
        return false;

    if (!is_number(textPattern[1])) // 2. value must be a number
        return false;
    if (textPattern.size() == 3) // If size is 3, then 3. value must be a number
        if (!is_number(textPattern[2]))
            return false;

    // Now convert them to numbers
    int index = atoi(textPattern[1].c_str());
    int arrayIndex = -1;
    if (textPattern.size() == 3)
        arrayIndex = atoi(textPattern[2].c_str());


    // 2. GET HARDCODED OBJECT AND VALIDATE
    // Check if index is in bounds
    if (index > (int)HardcodedGraphics.size() || index < 1)
        return false;

    // Get the item info:
    HardcodedGraphicsItem& hItemInfo = HardcodedGraphicsItem::Get(index);
    HardcodedGraphicsItem* hItemInfoMask = hItemInfo.getMaskObj();

    if (hItemInfo.state == HardcodedGraphicsItem::HITEMSTATE_INVALID) // We cannot access invalid items
        return false;

    // If it is not an array, but the item info tells it is an array, then it is invalid!
    if (arrayIndex == -1 && hItemInfo.isArray())
        return false;

    // If it is an array, but the item info tells it is NOT an array, then it is invalid!
    if (arrayIndex != -1 && !hItemInfo.isArray())
        return false;

    // If it is an array, then do validation further:
    // TODO: Mask Validation

    return hItemInfo.getHDC(arrayIndex, colorHDC, maskHDC);
}
Ejemplo n.º 18
0
Path* PathMaker::make_path_from_file(std::string fileName, LevelScreen * level){
    std::ifstream file(fileName.c_str());
    std::string line;
    Path * root = NULL;
    
    std::stack<Path *> tab_tree;
    std::stack<Point> multi_end;
    //will things get delted once out of stack?
    if (file.is_open()){
        while ( getline (file,line) ){
            Path * next_path = NULL;
            Path * current_path = NULL;
            
            int tab = get_tab_count(line);
            
            if(tab > tab_tree.size() + 1){
                debug("Tab Heirarchy ERROR");
                //TODO: goto clean up
            }else{
                int dif = (int)tab_tree.size() - tab;
//                debug(dif);
                if (root) {
                    for (int i = 0; i < dif; i++) tab_tree.pop();
                    current_path = tab_tree.top();
                }
                //something like this, so we don't need to worry about heirarch too much
            }

            std::vector<std::string> items = split(line, ' ');
            //stripe the tag
            std::string tag = items[0]; items.erase(items.begin());
            
            //
            Path * end_of_root = Path::end_of_path(current_path);
            
            bool flip_flag = false;
            FlipPath * flip_root = dynamic_cast<FlipPath *>(end_of_root);
            Point end_point;
            
            if (flip_root) {
                flip_flag = true;
                end_point = multi_end.top(); multi_end.pop();
            }else if (end_of_root) {
                end_point = end_of_root->get_transform()* end_of_root->get_end();
            }
            
            
            if (tag == "Path") {
                
                if(!root) {
                    root = make_path_from_string(items, Point());
                    next_path = root;
                }else{
                    Path * end_path = make_path_from_string(items, end_point);
                    if(end_path){
                        if (flip_flag) flip_root->add_next_path(end_path);
                        else Path::link_path(end_of_root, end_path);
                    }
                    next_path = end_path;
                }
                
            }else if(tag == "EndPath"){
                EndPath * end_path = make_endpath_from_string(items, end_point);
                if(end_path){
                    end_path->screen = level;
                    if (flip_flag) flip_root->add_next_path(end_path);
                    else Path::link_path(end_of_root, end_path);
                }
                next_path = end_path;
                
            }else if(tag == "FlipPath"){
                FlipPath * flip_path = make_flippath_from_string(items,end_point);
                if (flip_path) {
                    if (flip_flag) flip_root->add_next_path(flip_path);
                    else Path::link_path(end_of_root, flip_path);
                    
                    std::vector<Point> points = flip_path->get_end_point_list();
                    for (Point & p : points) multi_end.push(p);
                    
                }
                next_path = flip_path;
            
            }else if(tag == "FlipColorPath"){
                FlipColorPath * flipcolor_path = make_flipcolorpath(items, end_point);
                if(flipcolor_path){
                    if (flip_flag) flip_root->add_next_path(flipcolor_path);
                    else Path::link_path(end_of_root, flipcolor_path);
                }
                next_path = flipcolor_path;

            }else if (tag == "DyePath"){
                DyePath * dye_path = make_dyepath(items, end_point);
                if(dye_path){
                    if (flip_flag) flip_root->add_next_path(dye_path);
                    else Path::link_path(end_of_root, dye_path);
                }
                next_path = dye_path;
            }else if (tag == "SpritePath"){
                SpritePath * sprite_path = make_spritepath(items, end_point);
                if (sprite_path) {
                    if (flip_flag) flip_root->add_next_path(sprite_path);
                    else Path::link_path(end_of_root, sprite_path);
                }
                next_path = sprite_path;
            }
            
            //Check if we can proceed to process next path
            if (next_path == NULL) {
                Path::delete_path(root);
                root = NULL;
                break;
            }else{
                tab_tree.push(next_path);
            }
            
        }
        file.close();
    }
    if (!multi_end.empty()) {
        debug("Missing path hierarchy");
    }
    
    return root;
}
Ejemplo n.º 19
0
void SLAM_tumindoorImp::loadDataset(const string &path)
{
    train.push_back(vector< Ptr<Object> >());
    test.push_back(vector< Ptr<Object> >());
    validation.push_back(vector< Ptr<Object> >());

    string infoPath(path + "info/");

    // get info map name, .csv should be only one such file in folder
    string csvName;
    vector<string> infoNames;
    getDirList(infoPath, infoNames);
    for (vector<string>::iterator it=infoNames.begin(); it!=infoNames.end(); ++it)
    {
        string &name = *it;
        if (name.length()>3 && name.substr( name.length()-4, 4 )==".csv")
        {
            if (csvName.length()==0)
            {
                csvName = name;
            } else
            {
                printf("more than one .csv file in info folder\n");
                return;
            }
        }
    }
    if (csvName.length()==0)
    {
        printf("didn't find .csv file in info folder\n");
        return;
    }

    ifstream infile((infoPath + csvName).c_str());
    string line;
    while (getline(infile, line))
    {
        vector<string> elems;
        split(line, elems, ';');

        Ptr<SLAM_tumindoorObj> curr(new SLAM_tumindoorObj);

        curr->name = elems[0];
        if (curr->name.substr(0, strlen("dslr_left")) == "dslr_left")
        {
            curr->type = LEFT;
        } else
        if (curr->name.substr(0, strlen("dslr_right")) == "dslr_right")
        {
            curr->type = RIGHT;
        } else
        {
            curr->type = LADYBUG;
        }

        for (unsigned int i=0; i<4; ++i)
        {
            for (unsigned int j=0; j<4; ++j)
            {
                curr->transformMat(i, j) = atof(elems[1 + j + i*4].c_str());
            }
        }

        train.back().push_back(curr);
    }
}
Ejemplo n.º 20
0
std::vector<std::string> StringOperations::split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    return split(s, delim, elems);
}
Ejemplo n.º 21
0
void Logger::initialise( const std::string &id, const Options &options )
{
    char *envPtr;

    if ( !id.empty() )
        this->id( id );

    std::string tempLogFile;
    if ( options.mLogPath.size() )
    {
        mLogPath = options.mLogPath;
        tempLogFile = mLogPath+"/"+mId+".log";
    }
    if ( options.mLogFile.size() )
        tempLogFile = options.mLogFile;
    else
        tempLogFile = mLogPath+"/"+mId+".log";
    if ( (envPtr = getTargettedEnv( "LOG_FILE" )) )
        tempLogFile = envPtr;

    Level tempLevel = INFO;
    Level tempTermLevel = mTermLevel;
    Level tempDatabaseLevel = mDatabaseLevel;
    Level tempFileLevel = mFileLevel;
    Level tempSyslogLevel = mSyslogLevel;

    if ( options.mTermLevel != NOOPT )
        tempTermLevel = options.mTermLevel;
    if ( options.mDatabaseLevel != NOOPT )
        tempDatabaseLevel = options.mDatabaseLevel;
    else
        tempDatabaseLevel = config.log_level_database >= DEBUG1 ? DEBUG9 : config.log_level_database;
    if ( options.mFileLevel != NOOPT )
        tempFileLevel = options.mFileLevel;
    else
        tempFileLevel = config.log_level_file >= DEBUG1 ? DEBUG9 : config.log_level_file;
    if ( options.mSyslogLevel != NOOPT )
        tempSyslogLevel = options.mSyslogLevel;
    else
        tempSyslogLevel = config.log_level_syslog >= DEBUG1 ? DEBUG9 : config.log_level_syslog;

    // Legacy
    if ( (envPtr = getenv( "LOG_PRINT" )) )
        tempTermLevel = atoi(envPtr) ? DEBUG9 : NOLOG;

    if ( (envPtr = getTargettedEnv( "LOG_LEVEL" )) )
        tempLevel = atoi(envPtr);

    if ( (envPtr = getTargettedEnv( "LOG_LEVEL_TERM" )) )
        tempTermLevel = atoi(envPtr);
    if ( (envPtr = getTargettedEnv( "LOG_LEVEL_DATABASE" )) )
        tempDatabaseLevel = atoi(envPtr);
    if ( (envPtr = getTargettedEnv( "LOG_LEVEL_FILE" )) )
        tempFileLevel = atoi(envPtr);
    if ( (envPtr = getTargettedEnv( "LOG_LEVEL_SYSLOG" )) )
        tempSyslogLevel = atoi(envPtr);

    if ( config.log_debug )
    {
        StringVector targets = split( config.log_debug_target, "|" );
        for ( unsigned int i = 0; i < targets.size(); i++ )
        {
            const std::string &target = targets[i];
            if ( target == mId || target == "_"+mId || target == "_"+mIdRoot || target == "_"+mIdRoot || target == "" )
            {
                if ( config.log_debug_level > NOLOG )
                {
                    tempLevel = config.log_debug_level;
                    if ( config.log_debug_file[0] )
                    {
                        tempLogFile = config.log_debug_file;
                        tempFileLevel = tempLevel;
                    }
                }
            }
        }
    }

    logFile( tempLogFile );

    termLevel( tempTermLevel );
    databaseLevel( tempDatabaseLevel );
    fileLevel( tempFileLevel );
    syslogLevel( tempSyslogLevel );

    level( tempLevel );

    mFlush = (envPtr = getenv( "LOG_FLUSH")) ? atoi( envPtr ) : false;

    //mRuntime = (envPtr = getenv( "LOG_RUNTIME")) ? atoi( envPtr ) : false;

    {
        struct sigaction action;
        memset( &action, 0, sizeof(action) );
        action.sa_handler = usrHandler;
        action.sa_flags = SA_RESTART;

        if ( sigaction( SIGUSR1, &action, 0 ) < 0 )
        {
            Fatal( "sigaction(), error = %s", strerror(errno) );
        }
        if ( sigaction( SIGUSR2, &action, 0 ) < 0)
        {
            Fatal( "sigaction(), error = %s", strerror(errno) );
        }
    }

    mInitialised = true;

    Debug( 1, "LogOpts: level=%s/%s, screen=%s, database=%s, logfile=%s->%s, syslog=%s", smCodes[mLevel].c_str(), smCodes[mEffectiveLevel].c_str(), smCodes[mTermLevel].c_str(), smCodes[mDatabaseLevel].c_str(), smCodes[mFileLevel].c_str(), mLogFile.c_str(), smCodes[mSyslogLevel].c_str() );
}
Ejemplo n.º 22
0
    //Function to split string based on regex and put in list. Default predicate is just non-emptiness
    void    splitString(std::string& source, std::string splitRegex, std::list<std::string>& stringList, std::function<bool(std::string)> predicate){

        std::regex split(splitRegex);
        copy_if(std::sregex_token_iterator(source.begin(), source.end(), split, -1),
                std::sregex_token_iterator(),back_inserter(stringList), predicate);
    }
int 
setup_ampfactors( Pf *pf )
{
	char	*pga_sitecorr_cutoffs_g;
	char	*arow;
	Tbl	*pga_sitecorr_table;
	Tbl	*cutoffs;
	Tbl	*amps;
	int	icut, ivel;

	pga_sitecorr_cutoffs_g = pfget_string( pf, "pga_sitecorr_cutoffs_g" );
	pga_sitecorr_table = pfget_tbl( pf, "pga_sitecorr_table" );

	if( pga_sitecorr_cutoffs_g == NULL ) {
		elog_complain( 0, "trinetsm_es99: need value for "
			     "pga_sitecorr_cutoffs_g\n" );
		return -1;
	}

	if( pga_sitecorr_table == NULL ) {
		elog_complain( 0, "trinetsm_es99: need value for "
			     "pga_sitecorr_table\n" );
		return -1;
	}

	pga_sitecorr_cutoffs_g = strdup( pga_sitecorr_cutoffs_g );
	cutoffs = split( pga_sitecorr_cutoffs_g, ' ' );

	Ncutoffs = maxtbl( cutoffs );

	if( Ncutoffs < 1 ) {
		elog_complain( 0, "trinetsm_es99: need at least one value in "
			     "pga_sitecorr_cutoffs_g\n" );
		free( pga_sitecorr_cutoffs_g );
		freetbl( cutoffs, 0 );
		return -1;
	}

	allot( double *, Ampfactor_cutoffs_g, Ncutoffs );

	for( icut = 0; icut < Ncutoffs; icut++ ) {

		Ampfactor_cutoffs_g[icut] = atof( gettbl( cutoffs, icut ) );
	}

	free( pga_sitecorr_cutoffs_g );
	freetbl( cutoffs, 0 );

	Nvelocities = maxtbl( pga_sitecorr_table );

	if( Nvelocities < 1 ) {
		elog_complain( 0, "trinetsm_es99: need at least one row in "
			     "pga_sitecorr_table\n" );
		free_ampfactors();
		return -1;
	}

	allot( double **, Ampfactors, Nvelocities );

	for( ivel = 0; ivel < Nvelocities; ivel++ ) {
		
		allot( double *, Ampfactors[ivel], Ncutoffs + 1 );

		arow = gettbl( pga_sitecorr_table, ivel );

		arow = strdup( arow );
		amps = split( arow, ' ' );

		if( maxtbl( amps ) != Ncutoffs + 1 ) {
			elog_complain( 0,
				"trinetsm_es99: wrong number of entries "
				"in pga_sitecorr_table row <%s>: should be "
				"\"minvel ampfactor ampfactor ....\" "
				"(need %d + minvel = %d entries, have %d)\n",
				arow, Ncutoffs, Ncutoffs+1, maxtbl( amps ));
			free( arow );
			freetbl( amps, 0 );
			free_ampfactors();
			return -1;
		} 
			
	   	for( icut = 0; icut < Ncutoffs + 1; icut++ ) {
			Ampfactors[ivel][icut] = atof( gettbl( amps, icut ) );	
	   	}

		free( arow );
		freetbl( amps, 0 );
	}

	freetbl( pga_sitecorr_table, 0 );

	return 0;
}
Ejemplo n.º 24
0
void
ogm_reader_c::handle_stream_comments() {
  std::shared_ptr<std::vector<std::string> > comments;
  std::string title;

  bool charset_warning_printed = false;
  charset_converter_cptr cch   = charset_converter_c::init(m_ti.m_chapter_charset);
  size_t i;

  for (i = 0; i < sdemuxers.size(); i++) {
    ogm_demuxer_cptr &dmx = sdemuxers[i];
    if ((OGM_STREAM_TYPE_A_FLAC == dmx->stype) || (2 > dmx->packet_data.size()))
      continue;

    comments = extract_vorbis_comments(dmx->packet_data[1]);
    if (comments->empty())
      continue;

    std::vector<std::string> chapter_strings;

    size_t j;
    for (j = 0; comments->size() > j; j++) {
      mxverb(2, boost::format("ogm_reader: commment for #%1% for %2%: %3%\n") % j % i % (*comments)[j]);
      std::vector<std::string> comment = split((*comments)[j], "=", 2);
      if (comment.size() != 2)
        continue;

      if (comment[0] == "LANGUAGE") {
        int index;

        index = map_to_iso639_2_code(comment[1].c_str());
        if (-1 != index)
          dmx->language = iso639_languages[index].iso639_2_code;
        else {

          std::string lang = comment[1];
          int pos1         = lang.find("[");
          while (0 <= pos1) {
            int pos2 = lang.find("]", pos1);
            if (-1 == pos2)
              pos2 = lang.length() - 1;
            lang.erase(pos1, pos2 - pos1 + 1);
            pos1 = lang.find("[");
          }

          pos1 = lang.find("(");
          while (0 <= pos1) {
            int pos2 = lang.find(")", pos1);
            if (-1 == pos2)
              pos2 = lang.length() - 1;
            lang.erase(pos1, pos2 - pos1 + 1);
            pos1 = lang.find("(");
          }

          index = map_to_iso639_2_code(lang.c_str());
          if (-1 != index)
            dmx->language = iso639_languages[index].iso639_2_code;
        }

      } else if (comment[0] == "TITLE")
        title = comment[1];

      else if (balg::starts_with(comment[0], "CHAPTER"))
        chapter_strings.push_back((*comments)[j]);
    }

    bool segment_title_set = false;
    if (title != "") {
      title = cch->utf8(title);
      if (!g_segment_title_set && g_segment_title.empty() && (OGM_STREAM_TYPE_V_MSCOMP == dmx->stype)) {
        g_segment_title     = title;
        g_segment_title_set = true;
        segment_title_set   = true;
      }
      dmx->title = title.c_str();
      title      = "";
    }

    bool chapters_set = false;
    if (!chapter_strings.empty() && !m_ti.m_no_chapters) {
      try {
        std::shared_ptr<mm_mem_io_c> out(new mm_mem_io_c(nullptr, 0, 1000));

        out->write_bom("UTF-8");
        for (j = 0; j < chapter_strings.size(); j++)
          out->puts(cch->utf8(chapter_strings[j]) + std::string("\n"));
        out->set_file_name(m_ti.m_fname);

        std::shared_ptr<mm_text_io_c> text_out(new mm_text_io_c(out.get(), false));

        m_chapters   = parse_chapters(text_out.get(), 0, -1, 0, m_ti.m_chapter_language);
        chapters_set = true;

        align_chapter_edition_uids(m_chapters.get());
      } catch (...) {
      }
    }

    if (    (segment_title_set || chapters_set)
         && !charset_warning_printed
         && (m_ti.m_chapter_charset.empty())) {
      mxwarn_fn(m_ti.m_fname,
                Y("This Ogg/OGM file contains chapter or title information. Unfortunately the charset used to store this information in "
                  "the file cannot be identified unambiguously. The program assumes that your system's current charset is appropriate. This can "
                  "be overridden with the '--chapter-charset <charset>' switch.\n"));
      charset_warning_printed = true;
    }
  }
}
Ejemplo n.º 25
0
void functionHookedByCuckoo()
{
	string functions[12][100];
	string res(reinterpret_cast< char const* >(readResource(IDR_TEXT3)));
	vector<string> sep = split(res, '\n');

	for (int i = 0; i < sep.size(); i++)
	{
		replace(sep[i], "\r", "");
		string buf;
		stringstream ss(sep[i]);
		string d_f[2];
		while (ss >> buf)
		{
			if (buf.find(",") != std::string::npos)
			{
				buf.erase(buf.end() - 1);
				d_f[0] = buf + ".dll";
			}
			else
				d_f[1] = buf;
		}
		bool flag = false;
		for (size_t i = 0; i < 12; i++)
		{
			if (d_f[0] == functions[i][0])
			{
				for (size_t j = 0; j < 100; j++)
				{
					if (functions[i][j] == "")
					{
						functions[i][j] = d_f[1];
						break;
					}
				}
				flag = true;
				break;
			}
		}
		if (!flag)
		{
			for (size_t i = 0; i < 12; i++)
			{
				if (functions[i][0] == "")
				{
					functions[i][0] = d_f[0];
					functions[i][1] = d_f[1];
					break;
				}
			}
		}
	}

	/*

	ifstream myfile("dllandFunctions.txt");
	string line;

	if (myfile.is_open())
	{
		while (getline(myfile, line))
		{
			string buf;
			stringstream ss(line);
			string d_f[2];
			while (ss >> buf)
			{
				if (buf.find(",") != std::string::npos)
				{
					buf.erase(buf.end() - 1);
					d_f[0] = buf + ".dll";
				}
				else
					d_f[1] = buf;
			}
			bool flag = false;
			for (size_t i = 0; i < 12; i++)
			{
				if (d_f[0] == functions[i][0])
				{
					for (size_t j = 0; j < 100; j++)
					{
						if (functions[i][j] == "")
						{
							functions[i][j] = d_f[1];
							break;
						}
					}
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				for (size_t i = 0; i < 12; i++)
				{
					if (functions[i][0] == "")
					{
						functions[i][0] = d_f[0];
						functions[i][1] = d_f[1];
						break;
					}
				}
			}
		}
		myfile.close();
	}
	
	*/


	FARPROC addr;
	try
	{
		for (size_t i = 0; i < 12; i++)
		{
			for (size_t j = 0; j < 100; j++)
			{
				if (functions[i][j] != "")
				{
					addr = GetProcAddress(LoadLibraryA(functions[i][0].c_str()), functions[i][j].c_str());
					if (addr == 0x00000000) continue;
					else if (*(BYTE *)addr == 0xE9) {
						createAndWriteFile("functionHookedByCuckoo.txt");
						printf("Cuckoo detected (Function hook)!!\n"); break;
					}
				}
			}
		}
	}
	catch (int e)
	{
		perror("ERROR");
	}
}
Ejemplo n.º 26
0
int main()
{
  int exit_code = EXIT_SUCCESS;
  struct buf_t* buf = buf_new(MAX_SIZE);
  char s[MAX_SIZE + 1];

  if (print_prompt() < 0) {
    QUIT(EXIT_FAILURE);
  }
  ssize_t size;
  while ((size = buf_getline(STDOUT_FILENO,
                             buf,
                             s,
                             MAX_SIZE))) {
    if (size < 0) {
      QUIT(EXIT_FAILURE);
    }

    s[size] = 0;

    char** piped_programs = split(s, '|', 0);
    if (!piped_programs) {
      goto ERROR;
    }
    char** p;
    for (p = piped_programs; *p; p++)
      ;
    int len = p - piped_programs;

    execargs_t** programs = malloc(len * sizeof(execargs_t*));
    if (!programs) {
      for (char** p = piped_programs; *p; p++) {
        free(*p);
      }
      free(piped_programs);
      goto ERROR;
    }

    for (int i = 0; i < len; i++) {
      programs[i] = execargs_parse(piped_programs[i]);
      if (!programs[i]) {
        for (int j = 0; j < i; j++) {
          free(programs[j]);
        }
        for (int j = 0; j < len; j++) {
          free(piped_programs[j]);
        }
        free(programs);
        free(piped_programs);
        goto ERROR;
      }
    }

    if (runpiped(programs, len) < 0) {
      goto ERROR;
    }

    if (print_prompt() < 0) {
      QUIT(EXIT_FAILURE);
    }

    continue;
  ERROR:

    if (print_prompt() < 0) {
      QUIT(EXIT_FAILURE);
    }
  }

 EXIT:
  buf_free(buf);
  return exit_code;
}
Ejemplo n.º 27
0
 std::vector<std::string> split(const std::string& s, char delim) {
     std::vector<std::string> elems;
     split(s, delim, elems);
     return elems;
 }
Ejemplo n.º 28
0
void replace_ver_info(const wstring& pe_path, const SfxVersionInfo& ver_info) {
    // numeric version
    list<wstring> ver_parts = split(ver_info.version, L'.');
    DWORD ver_hi = 0, ver_lo = 0;
    list<wstring>::const_iterator ver_part = ver_parts.cbegin();
    if (ver_part != ver_parts.end()) {
        ver_hi |= (str_to_int(*ver_part) & 0xFFFF) << 16;
        ver_part++;
    }
    if (ver_part != ver_parts.end()) {
        ver_hi |= str_to_int(*ver_part) & 0xFFFF;
        ver_part++;
    }
    if (ver_part != ver_parts.end()) {
        ver_lo |= (str_to_int(*ver_part) & 0xFFFF) << 16;
        ver_part++;
    }
    if (ver_part != ver_parts.end()) {
        ver_lo |= str_to_int(*ver_part) & 0xFFFF;
        ver_part++;
    }

    // existing version info list
    list<IdLang> vi_list;
    RsrcModule module(pe_path);
    list<RsrcId> ids = enum_rsrc_names(module.handle(), RT_VERSION);
    for_each(ids.begin(), ids.end(), [&] (const RsrcId& id) {
        list<WORD> lang_ids = enum_rsrc_langs(module.handle(), RT_VERSION, id);
        for_each(lang_ids.begin(), lang_ids.end(), [&] (WORD lang_id) {
            IdLang id_lang;
            id_lang.id = id;
            id_lang.lang_id = lang_id;
            vi_list.push_back(id_lang);
        });
    });
    module.close();

    WORD lang_id;
    RsrcId ver_id;
    if (vi_list.empty()) {
        ver_id = MAKEINTRESOURCE(1);
        lang_id = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL);
    }
    else {
        ver_id = vi_list.front().id;
        lang_id = vi_list.front().lang_id;
    }

    // encode version info
    VersionEncoder e;
    e.reserve(4096);

    size_t vs_versioninfo_pos = e.size();
    e.encode_WORD(0); // VS_VERSIONINFO
    e.encode_WORD(sizeof(VS_FIXEDFILEINFO));
    e.encode_WORD(0);
    e.encode_string(L"VS_VERSION_INFO");
    e.pad();

    e.encode_DWORD(0xFEEF04BD); // VS_FIXEDFILEINFO
    e.encode_DWORD(0x00010000);
    e.encode_DWORD(ver_hi);
    e.encode_DWORD(ver_lo);
    e.encode_DWORD(ver_hi);
    e.encode_DWORD(ver_lo);
    e.encode_DWORD(0x3F);
    e.encode_DWORD(0);
    e.encode_DWORD(VOS_NT_WINDOWS32);
    e.encode_DWORD(VFT_APP);
    e.encode_DWORD(0);
    e.encode_DWORD(0);
    e.encode_DWORD(0);
    e.pad();

    size_t string_file_info_pos = e.size();
    e.encode_WORD(0); // StringFileInfo
    e.encode_WORD(0);
    e.encode_WORD(1);
    e.encode_string(L"StringFileInfo");
    e.pad();

    size_t string_table_pos = e.size();
    e.encode_WORD(0); // StringTable
    e.encode_WORD(0);
    e.encode_WORD(1);
    wostringstream st;
    st << hex << setw(4) << setfill(L'0') << lang_id << L"04b0";
    e.encode_string(st.str());
    e.pad();

    map<wstring, wstring> strings;
    strings[L"Comments"] = ver_info.comments;
    strings[L"CompanyName"] = ver_info.company_name;
    strings[L"FileDescription"] = ver_info.file_description;
    strings[L"FileVersion"] = ver_info.version;
    strings[L"LegalCopyright"] = ver_info.legal_copyright;
    strings[L"ProductName"] = ver_info.product_name;
    strings[L"ProductVersion"] = ver_info.version;

    for_each(strings.cbegin(), strings.cend(), [&] (const pair<wstring, wstring>& str) {
        size_t string_pos = e.size();
        e.encode_WORD(0); // String
        e.encode_WORD(str.second.size() + 1);
        e.encode_WORD(1);
        e.encode_string(str.first);
        e.pad();
        e.encode_string(str.second);
        e.pad();
        e.update_length(string_pos);
    });

    e.update_length(string_table_pos);

    e.update_length(string_file_info_pos);

    size_t var_file_info_pos = e.size();
    e.encode_WORD(0); // VarFileInfo
    e.encode_WORD(0);
    e.encode_WORD(1);
    e.encode_string(L"VarFileInfo");
    e.pad();

    size_t var_pos = e.size();
    e.encode_WORD(0); // Var
    e.encode_WORD(4);
    e.encode_WORD(0);
    e.encode_string(L"Translation");
    e.pad();
    e.encode_WORD(lang_id);
    e.encode_WORD(0x04B0);
    e.update_length(var_pos);

    e.update_length(var_file_info_pos);

    e.update_length(vs_versioninfo_pos);

    // wrire resource
    ResourceUpdate rupdate(pe_path);
    for_each(vi_list.cbegin(), vi_list.cend(), [&] (const IdLang& id_lang) {
        rupdate.update(RT_VERSION, id_lang.id, id_lang.lang_id, nullptr, 0);
    });
    rupdate.update(RT_VERSION, ver_id, lang_id, e.data(), e.size());
    rupdate.finalize();
}
Ejemplo n.º 29
0
    TEST(StringUtilsTest, split) {
        StringList result;
        
        result = split("", ' ');
        ASSERT_TRUE(result.empty());
        
        result = split(" ", ' ');
        ASSERT_TRUE(result.empty());
        
        result = split("asdf", ' ');
        ASSERT_EQ(1u, result.size());
        ASSERT_EQ(String("asdf"), result[0]);
        
        result = split("d asdf", ' ');
        ASSERT_EQ(2u, result.size());
        ASSERT_EQ(String("d"), result[0]);
        ASSERT_EQ(String("asdf"), result[1]);
        
        result = split("asdf d", ' ');
        ASSERT_EQ(2u, result.size());
        ASSERT_EQ(String("asdf"), result[0]);
        ASSERT_EQ(String("d"), result[1]);
        
        result = split("The quick brown fox", ' ');
        ASSERT_EQ(4u, result.size());
        ASSERT_EQ(String("The"), result[0]);
        ASSERT_EQ(String("quick"), result[1]);
        ASSERT_EQ(String("brown"), result[2]);
        ASSERT_EQ(String("fox"), result[3]);

        result = split(" The quick brown fox", ' ');
        ASSERT_EQ(4u, result.size());
        ASSERT_EQ(String("The"), result[0]);
        ASSERT_EQ(String("quick"), result[1]);
        ASSERT_EQ(String("brown"), result[2]);
        ASSERT_EQ(String("fox"), result[3]);

        result = split("  The quick brown fox", ' ');
        ASSERT_EQ(4u, result.size());
        ASSERT_EQ(String("The"), result[0]);
        ASSERT_EQ(String("quick"), result[1]);
        ASSERT_EQ(String("brown"), result[2]);
        ASSERT_EQ(String("fox"), result[3]);
        
        result = split("The quick brown fox ", ' ');
        ASSERT_EQ(String("The"), result[0]);
        ASSERT_EQ(String("quick"), result[1]);
        ASSERT_EQ(String("brown"), result[2]);
        ASSERT_EQ(String("fox"), result[3]);

        result = split("The quick brown fox  ", ' ');
        ASSERT_EQ(String("The"), result[0]);
        ASSERT_EQ(String("quick"), result[1]);
        ASSERT_EQ(String("brown"), result[2]);
        ASSERT_EQ(String("fox"), result[3]);
        
        result = split("The quick  brown fox", ' ');
        ASSERT_EQ(5u, result.size());
        ASSERT_EQ(String("The"), result[0]);
        ASSERT_EQ(String("quick"), result[1]);
        ASSERT_EQ(String(""), result[2]);
        ASSERT_EQ(String("brown"), result[3]);
        ASSERT_EQ(String("fox"), result[4]);
    }
Ejemplo n.º 30
0
int get_link (int v) {
	if (t[v].link != -1)  return t[v].link;
	if (t[v].par == -1)  return 0;
	int to = get_link (t[v].par);
	return t[v].link = split (go (state(to,t[to].len()), t[v].l + (t[v].par==0), t[v].r));
}