Exemplo n.º 1
0
/*
 * Bench string insertion
 * @param insType, which insert()-func to call
 */
float StropBencher::insert(int numRuns, int strType, int insType) {

	std::string str("I am a string!");
	std::string inStr("I am a string to be inserted into other strings!");

	float startTime = currTime();
	switch(strType) {

	case MAUTIL_STRING:

		for(int i = 0; i < numRuns; ++i){
			for(int j = 0; j < ALOT; ++j){
				if(insType == 0)
					str.insert(4, "junk");
				else
					str.insert(2, inStr); //this is a lot slower about 5 times in MoRE
			}
		}

		/*case STD_STRING: TODO Will have to wait until STL is implemented

		for(int i = 0; i < numRuns; ++i){
			for(int j = 0; j < ALOT; ++j){
				mStdStr->append("junk");
			}
		}
		return currTime() - startTime;*/

	}
    return currTime() - startTime;

}
Exemplo n.º 2
0
bool EpisodeState::load()
{
    QString file= _episodePath+saveFileName;
    QFile _f(file);
    if(!_f.exists(file)) return false;
    if (_f.open(QIODevice::ReadOnly))
    {
        QString fileRaw;
        QTextStream inStr(&_f);
        GamesaveData FileData;
        inStr.setCodec("UTF-8");
        fileRaw = inStr.readAll();
        FileData = FileFormats::ReadExtendedSaveFile(fileRaw, file);

        if(FileData.ReadFileValid)
        {
            game_state = FileData;
            episodeIsStarted=true;
            return true;
        }
        else
        {
            PGE_MsgBox::error(file+"\n"+FileFormats::errorString);
        }
    }
    return false;
}
Exemplo n.º 3
0
void 
Matlab_Interface::interact()
{
  char s [BUFSIZE] ;

  bool status;

  while(1) 
  {
    // Prompt the user and get a std::string
    printf(">> ");
    if (fgets(s, BUFSIZE, stdin) == NULL) 
    {
      printf("Bye\n");
      break ;
    }
    printf ("command :%s:\n", s) ;

    std::string inStr(s);
    status = doCommand( inStr );

    if( status )
      commandStack.push_back( inStr );
  }

  return;
}
nsresult nsAddbookProtocolHandler::GenerateXMLOutputChannel(
    nsString &aOutput, nsIAddbookUrl *addbookUrl, nsIURI *aURI,
    nsILoadInfo *aLoadInfo, nsIChannel **_retval) {
  nsresult rv;
  nsCOMPtr<nsIStringInputStream> inStr(
      do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ConvertUTF16toUTF8 utf8String(aOutput.get());

  rv = inStr->SetData(utf8String.get(), utf8String.Length());
  NS_ENSURE_SUCCESS(rv, rv);

  if (aLoadInfo) {
    return NS_NewInputStreamChannelInternal(_retval, aURI, inStr.forget(),
                                            NS_LITERAL_CSTRING("text/xml"),
                                            EmptyCString(), aLoadInfo);
  }

  nsCOMPtr<nsIPrincipal> nullPrincipal =
      do_CreateInstance("@mozilla.org/nullprincipal;1", &rv);
  NS_ASSERTION(NS_SUCCEEDED(rv), "CreateInstance of nullprincipalfailed.");
  if (NS_FAILED(rv)) return rv;

  return NS_NewInputStreamChannel(
      _retval, aURI, inStr.forget(), nullPrincipal,
      nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
      nsIContentPolicy::TYPE_OTHER, NS_LITERAL_CSTRING("text/xml"));
}
Exemplo n.º 5
0
int lengthOfLongestSubstring(char *s) {
    int longest = 0;
    int tmp = 0;
    int begin = 0;
    int end = 0;
    
    while (end < (int)strlen(s)) {
        char cur = s[end];
        int isFound = inStr(s, begin, end, cur);
        if (isFound == -1) {
            tmp++;
        } else if (s[begin] == cur) {
            begin++;
        } else {
            tmp = end - begin;
            if (tmp > longest) {
                longest = tmp;
            }
            begin = isFound + 1;
            tmp = end - begin + 1;
        }
        end++;
    }
    if (tmp > longest) {
        longest = tmp;
    }
    return longest;
}
Exemplo n.º 6
0
bool
Gecko_AtomEqualsUTF8IgnoreCase(nsIAtom* aAtom, const char* aString, uint32_t aLength)
{
  // XXXbholley: We should be able to do this without converting, I just can't
  // find the right thing to call.
  nsAutoString atomStr;
  aAtom->ToString(atomStr);
  NS_ConvertUTF8toUTF16 inStr(nsDependentCSubstring(aString, aLength));
  return nsContentUtils::EqualsIgnoreASCIICase(atomStr, inStr);
}
Exemplo n.º 7
0
char *replace(char *text, char *from, char *to){
     //if (DEBUG==1) putlog("replacing");
     char *ret=(char*)calloc( strlen(text)+(strlen(to)-strlen(from)),sizeof(char));
     char *left;
     char *right;
     int pos=inStr(text,strlen(text),from);
     if (pos!=-1){
           left=substring(text,0,pos);
           right=substring(text,pos+strlen(from),strlen(text)-(pos+strlen(from)));          
           ret=str3cat(left,to,right);
           return replace(ret,from,to);
     }
     //if (DEBUG==1) putlog("replaced");
     return text;
}
Exemplo n.º 8
0
/*
 * Tokenize a string into parts separated by 'delim'
 */
char*aj_strtok(char*str, const char*delim)
{
    static char*nextLocation = 0;
    int currentTokenLength;
    int nextTokenLength;
    /* NULL given so set location to the string */
    if (str == NULL) {
        str = nextLocation;
    }
    if (str != NULL) {
        nextLocation = str;
        /* Location is NULL, return 0 */
    } else if (!nextLocation) {
        return 0;
    }
    /*
     * Get the length of the next token and
     * the length of string where there is not a token
     * and move the location and str pointers to those
     * two locations.
     */
    currentTokenLength = inStr(nextLocation, delim);
    nextTokenLength = notInStr(str, delim);
    /* Get current token */
    str = nextLocation + currentTokenLength;
    /* Update for the next token */
    nextLocation = str + nextTokenLength;
    /* location and str are the same so there was no token */
    if (nextLocation == str) {
        //nextLocation = 0;
        return nextLocation = 0;
    }
    /* if next location is valid:
     * set the start to zero (end of str)
     * and increment (to get rid of space)
     */
    if (*nextLocation) {
        *nextLocation = 0;
        nextLocation++;
    } else {
        nextLocation = 0;
    }
    return str;
}
Exemplo n.º 9
0
static char *tagExtract(char *tag, int tagLen, char* info){
//if (DEBUG==1) putlog("extracting tag");
	int pos, len, i;
	pos=inStr(tag,tagLen,info);
//hexchat_printf(ph,"pos=%i",pos);
	if (pos==-1) return "";//NULL;
	//printf("position of %s = %i\n",info,pos);
	len=0;
	//for (i=pos;i<pos+10;i++)printf("tag[%i]=%i \n",i,tag[i]);
	for (i=0;i<4;i++) {
		len+=tag[pos+strlen(info)+i]*iPow(255,3-i);
	}
	//printf("Tag-Length: %i\n",len);
	if (strcmp("COMM",info)!=0) return substring(tag,pos+7+strlen(info),len-1);//11
	return substring(tag,pos+7+strlen(info),len-1);//11
	//char *ct=substring(tag,pos+7+strlen(info),len-1);//11
	//return substring(ct,strlen(ct)+1,len-1-strlen(ct)); //<-- do not understand, what i did here :(
	
}
nsresult
nsAddbookProtocolHandler::GenerateXMLOutputChannel( nsString &aOutput,
        nsIAddbookUrl *addbookUrl,
        nsIURI *aURI,
        nsIChannel **_retval)
{
    nsIChannel                *channel;
    nsresult rv;
    nsCOMPtr<nsIStringInputStream> inStr(do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv));
    NS_ENSURE_SUCCESS(rv, rv);

    NS_ConvertUTF16toUTF8 utf8String(aOutput.get());

    rv = inStr->SetData(utf8String.get(), utf8String.Length());

    rv = NS_NewInputStreamChannel(&channel, aURI, inStr,
                                  NS_LITERAL_CSTRING("text/xml"));
    NS_ENSURE_SUCCESS(rv, rv);

    *_retval = channel;
    return rv;
}
Exemplo n.º 11
0
bool rspfApplanixEOFile::parseStream(std::istream& in)
{
    theRecordIdMap.clear();
    rspfString line;
    int c = '\0';
    if(!parseHeader(in, theHeader))
    {
        return false;
    }

    // now parse parameters
    in>>applanix_skipws;
    line = "";
    while(in.good()&&
            !line.contains("RECORD FORMAT"))
    {
        std::getline(in, line.string());
        line = line.upcase();
        line = line.substitute("\r","\n", true);
        if(line.contains("KAPPA CARDINAL"))
        {
            theKappaCardinal = line;
            theKappaCardinal = theKappaCardinal.substitute("KAPPA CARDINAL ROTATION","");
            theKappaCardinal = theKappaCardinal.substitute(":","");
            theKappaCardinal = theKappaCardinal.substitute("\n","");
        }
        else if(line.contains("LEVER ARM"))
        {
            rspfKeywordlist kwl('=');
            line = line.substitute("LEVER ARM VALUES:",
                                   "");
            line = line.substitute(",",
                                   "\n",
                                   true);
            std::istringstream in(line);

            kwl.parseStream(in);

            theLeverArmLx = kwl.find("LX");
            theLeverArmLy = kwl.find("LY");
            theLeverArmLz = kwl.find("LZ");
        }
        else if(line.contains("BORESIGHT VALUES"))
        {
            rspfKeywordlist kwl('=');
            line = line.substitute("BORESIGHT VALUES:",
                                   "");
            line = line.substitute(",",
                                   "\n",
                                   true);

            std::istringstream in(line);

            kwl.parseStream(in);


            theBoreSightTx = kwl.find("TX");
            theBoreSightTy = kwl.find("TY");
            theBoreSightTz = kwl.find("TZ");
        }
        else if(line.contains("SHIFT VALUES:"))
        {
            rspfKeywordlist kwl('=');
            line = line.substitute("SHIFT VALUES:","");
            line = line.substitute(",",
                                   "\n",
                                   true);

            std::istringstream in(line);
            kwl.parseStream(in);


            theShiftValuesX = kwl.find("X");
            theShiftValuesY = kwl.find("Y");
            theShiftValuesZ = kwl.find("Z");

        }
        else if(line.contains("GRID:"))
        {
            rspfKeywordlist kwl(':');
            line = line.substitute(";",
                                   "\n",
                                   true);
            std::istringstream in(line);
            kwl.parseStream(in);
            theUtmZone = kwl.find("ZONE");

            if(theUtmZone.contains("NORTH"))
            {
                theUtmHemisphere = "North";
            }
            else
            {
                theUtmHemisphere = "South";
            }
            theUtmZone = theUtmZone.replaceAllThatMatch("UTM|\\(.*\\)|NORTH|SOUTH","");
            theUtmZone = theUtmZone.trim();
        }
        else if(line.contains("FRAME DATUM"))
        {
            rspfKeywordlist kwl(':');
            line = line.substitute(";",
                                   "\n",
                                   true);
            std::istringstream in(line);
            kwl.parseStream(in);

            theMappingFrameDatum = kwl.find("MAPPING FRAME DATUM");
            theMappingFrameProjection = kwl.find("MAPPING FRAME PROJECTION");
            theMappingFrameDatum = theMappingFrameDatum.trim();
            theMappingFrameProjection = theMappingFrameProjection.trim();
        }
        else if(line.contains("POSPROC SBET"))
        {
            theSbetField = line.after(":");
            theSbetField = theSbetField.trim();
        }
        else if(line.contains("CENTRAL MERIDIAN"))
        {
            theCentralMeridian = line;
            theCentralMeridian = theCentralMeridian.substitute("CENTRAL MERIDIAN","");
            theCentralMeridian = theCentralMeridian.substitute("=","");
            theCentralMeridian = theCentralMeridian.substitute("DEG","");
            theCentralMeridian = theCentralMeridian.substitute(";","");
        }
        else if(line.contains("LATITUDE OF THE GRID ORIGIN"))
        {
            rspfKeywordlist kwl('=');
            line = line.substitute(";",
                                   "\n",
                                   true);
            std::istringstream in(line);
            kwl.parseStream(in);

            theOriginLatitude  = kwl.find("LATITUDE OF THE GRID ORIGIN");
            theGridScaleFactor = kwl.find("GRID SCALE FACTOR");
        }
        else if(line.contains("FALSE EASTING"))
        {
            rspfKeywordlist kwl('=');
            line = line.substitute(";",
                                   "\n",
                                   true);
            std::istringstream in(line);
            kwl.parseStream(in);

            theFalseEasting  = kwl.find("FALSE EASTING");
            theFalseNorthing = kwl.find("FALSE NORTHING");
        }
    }

    in>>applanix_skipws;

    c = in.get();

    std::vector<rspfString> fieldArray;
    rspfString field;

    while(in.good()&&
            (c!='\n')&&
            (c!='\r'))
    {
        field = "";
        while((c != ',')&&
                (c != '\n')&&
                (c != '\r'))
        {
            field += (char)c;
            c = in.get();
        }
        if((c!='\n')&&
                (c!='\r'))
        {
            c = in.get();
        }
        field = field.trim();
        if(field != "")
        {
            theRecordFormat.push_back(field);
        }
    }
    in>>applanix_skipws;

    if(in.peek() == '(')
    {
        std::getline(in, line.string());
    }
    in>>applanix_skipws;
    rspfRefPtr<rspfApplanixEORecord> record = new rspfApplanixEORecord((rspf_uint32)theRecordFormat.size());
    rspf_int32 latIdx = getFieldIdx("LAT");
    rspf_int32 lonIdx = getFieldIdx("LONG");;
    bool hasLatLon = (latIdx >=0)&&(lonIdx >= 0);


    if(hasLatLon)
    {
        theMinLat = 90.0;
        theMaxLat = -90.0;
        theMinLon = 180.0;
        theMaxLon = -180.0;
    }
    else
    {
        theMinLat = rspf::nan();
        theMaxLat = rspf::nan();
        theMinLon = rspf::nan();
        theMaxLon = rspf::nan();
    }

    while(in.good()&&theRecordFormat.size())
    {
        std::getline(in, line.string());
        line = line.trim();
        if(line != "")
        {
            std::istringstream inStr(line);
            rspf_uint32 idx;
            rspfString value;

            for(idx = 0; idx < theRecordFormat.size(); ++idx)
            {
                inStr >> (*record)[idx];
            }
            if(hasLatLon)
            {
                double lat = (*record)[latIdx].toDouble();
                double lon = (*record)[lonIdx].toDouble();

                if(lat<theMinLat) theMinLat = lat;
                if(lat>theMaxLat) theMaxLat = lat;
                if(lon<theMinLon) theMinLon = lon;
                if(lon>theMaxLon) theMaxLon = lon;

            }
            theApplanixRecordList.push_back(new rspfApplanixEORecord(*record));
        }
    }
Exemplo n.º 12
0
struct tagInfo getOggHeader(char *file){
//if (DEBUG==1) putlog("reading ogg header");
	char header[4096];
	int i, c;
	int h1pos, h3pos, maxBr, nomBr, minBr, pos, count, tagLen;
	char *sub;
	char *name;
	char *val;
	char HEADLOC1[]="_vorbis", HEADLOC3[]="_vorbis", HEADLOC5[]="_vorbis";
	FILE *f;
	struct tagInfo info;

	info.artist=NULL;
	f = fopen(file,"rb");
	if (f==NULL){
       hexchat_print(ph,"file not found while trying to read ogg header");
       //if (DEBUG==1) putlog("file not found while trying to read ogg header");
       return info;
    }

	for (i=0;i<4095;i++) {c=fgetc(f);header[i]=(char)c;}
	fclose(f);
	HEADLOC1[0]=1;
	HEADLOC3[0]=3;
	HEADLOC5[0]=5;
	h1pos=inStr(header,4096,HEADLOC1);
	h3pos=inStr(header,4096,HEADLOC3);
	//int h5pos=inStr(header,4096,HEADLOC5); //not needed
	
	//printf("loc1: %i\n",h1pos);printf("loc3: %i\n",h3pos);printf("loc5: %i\n",h5pos);
	maxBr=getOggInt(header,h1pos+7+9,4);
	nomBr=getOggInt(header,h1pos+7+13,4);
	minBr=getOggInt(header,h1pos+7+17,4);
	info.freq=getOggInt(header,h1pos+7+5,4);
	info.mode=header[h1pos+7+4];
	info.bitrate=nomBr;
	if (((maxBr==nomBr)&&(nomBr=minBr))||((minBr==0)&&(maxBr==0))||((minBr=-1)&&(maxBr=-1)) )info.cbr=1;else info.cbr=0;
	printf("bitrates: %i|%i|%i\n",maxBr,nomBr,minBr);
	printf("freq: %u\n",info.freq);
	pos=h3pos+7;
	pos+=getOggInt(header,pos,4)+4;
	count=getOggInt(header,pos,4);
	//printf("tags: %i\n",count);
	pos+=4;

	info.artist=NULL;info.title=NULL;info.album=NULL;info.comment=NULL;info.genre=NULL;
	for (i=0;i<count;i++){
		tagLen=getOggInt(header,pos,4);
		//printf("taglength: %i\n",tagLen);
		sub=substring(header,pos+4,tagLen);
		name=upperStr(substring(sub,0,inStr(sub,tagLen,"=")));
		val=substring(sub,inStr(sub,tagLen,"=")+1,tagLen-inStr(sub,tagLen,"=")-1);
		//printf("Tag: %s\n",sub);
		//printf("Name: %s\n",name);
		//printf("value: %s\n",val);
		if (strcmp(name,"ARTIST")==0) info.artist=val;
		if (strcmp(name,"TITLE")==0) info.title=val;
		if (strcmp(name,"ALBUM")==0) info.album=val;
		if (strcmp(name,"GENRE")==0) info.genre=val;
		if (strcmp(name,"COMMENT")==0) info.comment=val;
		pos+=4+tagLen;
		free(name);
	}
	if (info.artist==NULL) info.artist="";
	if (info.album==NULL) info.album ="";
	if (info.title==NULL) info.title="";
	if (info.genre==NULL) info.genre="";
	if (info.comment==NULL) info.comment="";
	
	printf("Artist: %s\nTitle: %s\nAlbum: %s\n",info.artist,info.title, info.album);
	printf("Genre: %s\nComment: %s\nMode: %i\nCBR: %i\n",info.genre,info.comment,info.mode,info.cbr);
	//if (DEBUG==1) putlog("ogg header readed");
	return info;
}
Exemplo n.º 13
0
bool rspfApplanixEcefModel::loadState(const rspfKeywordlist& kwl,
                                       const char* prefix)
{
   if(traceDebug())
   {
      std::cout << "rspfApplanixEcefModel::loadState: ......... entered" << std::endl;
   }

   theImageClipRect = rspfDrect(0,0,4076,4091);
   theRefImgPt      = rspfDpt(2046.0, 2038.5);

   rspfSensorModel::loadState(kwl, prefix);
   if(getNumberOfAdjustableParameters() < 1)
   {
      initAdjustableParameters();
   }
   theEcefPlatformPosition    = rspfGpt(0.0,0.0,1000.0);
   theAdjEcefPlatformPosition = rspfGpt(0.0,0.0,1000.0);
   theRoll    = 0.0;
   thePitch   = 0.0;
   theHeading = 0.0;
   // bool computeGsdFlag = false;
   const char* roll              = kwl.find(prefix, "roll");
   const char* pitch             = kwl.find(prefix, "pitch");
   const char* heading           = kwl.find(prefix, "heading");
   const char* principal_point   = kwl.find(prefix, "principal_point");
   const char* pixel_size        = kwl.find(prefix, "pixel_size");
   const char* focal_length      = kwl.find(prefix, "focal_length");
   const char* ecef_platform_position = kwl.find(prefix, "ecef_platform_position");
   const char* latlonh_platform_position = kwl.find(prefix, "latlonh_platform_position");
   const char* compute_gsd_flag  = kwl.find(prefix, "compute_gsd_flag");
   const char* eo_file           = kwl.find(prefix, "eo_file");
   const char* camera_file       = kwl.find(prefix, "camera_file");
   const char* eo_id             = kwl.find(prefix, "eo_id");
   bool result = true;
   if(eo_id)
   {
      theImageID = eo_id;
   }
   if(eo_file)
   {
      rspfApplanixEOFile eoFile;
      if(eoFile.parseFile(rspfFilename(eo_file)))
      {
         rspfRefPtr<rspfApplanixEORecord> record = eoFile.getRecordGivenId(theImageID);
         if(record.valid())
         {
            rspf_int32 rollIdx    = eoFile.getFieldIdx("ROLL");
            rspf_int32 pitchIdx   = eoFile.getFieldIdx("PITCH");
            rspf_int32 headingIdx = eoFile.getFieldIdx("HEADING");
            rspf_int32 xIdx       = eoFile.getFieldIdx("X");
            rspf_int32 yIdx       = eoFile.getFieldIdx("Y");
            rspf_int32 zIdx       = eoFile.getFieldIdx("Z");

            if((rollIdx >= 0)&&
               (pitchIdx >= 0)&&
               (headingIdx >= 0)&&
               (xIdx >= 0)&&
               (yIdx >= 0)&&
               (zIdx >= 0))
            {
               theRoll    = (*record)[rollIdx].toDouble();
               thePitch   = (*record)[pitchIdx].toDouble();
               theHeading = (*record)[headingIdx].toDouble();
               theEcefPlatformPosition = rspfEcefPoint((*record)[xIdx].toDouble(),
                                                        (*record)[yIdx].toDouble(),
                                                        (*record)[zIdx].toDouble());
               theAdjEcefPlatformPosition = theEcefPlatformPosition;
            }
            else
            {
               return false;
            }
         }
         else
         {
            rspfNotify(rspfNotifyLevel_WARN) << "rspfApplanixEcefModel::loadState()  Image id " << theImageID << " not found in eo file " << eo_file << std::endl;
            
            return false;
         }
      }
      else
      {
         return false;
      }
      // computeGsdFlag = true;
   }
   else
   {
      if(roll)
      {
         theRoll = rspfString(roll).toDouble();
      }
      if(pitch)
      {
         thePitch = rspfString(pitch).toDouble();
      }
      if(heading)
      {
         theHeading = rspfString(heading).toDouble();
      }
      if(ecef_platform_position)
      {
         std::vector<rspfString> splitString;
         rspfString tempString(ecef_platform_position);
         tempString.split(splitString, rspfString(" "));
         if(splitString.size() > 2)
         {
            theEcefPlatformPosition  = rspfEcefPoint(splitString[0].toDouble(),
                                                      splitString[1].toDouble(),
                                                      splitString[2].toDouble());
         }
      }
      else if(latlonh_platform_position)
      {
         std::vector<rspfString> splitString;
         rspfString tempString(latlonh_platform_position);
         tempString.split(splitString, rspfString(" "));
         std::string datumString;
         double lat=0.0, lon=0.0, h=0.0;
         if(splitString.size() > 2)
         {
            lat = splitString[0].toDouble();
            lon = splitString[1].toDouble();
            h = splitString[2].toDouble();
         }
         
         theEcefPlatformPosition = rspfGpt(lat,lon,h);
      }
   }

   if(camera_file)
   {
      rspfKeywordlist cameraKwl;
      rspfKeywordlist lensKwl;
      cameraKwl.add(camera_file);
      const char* sensor = cameraKwl.find("sensor");
      const char* image_size      = cameraKwl.find(prefix, "image_size");
      principal_point = cameraKwl.find("principal_point");
      focal_length    = cameraKwl.find("focal_length");
      pixel_size      = cameraKwl.find(prefix, "pixel_size");
      focal_length    = cameraKwl.find(prefix, "focal_length");
      const char* distortion_units = cameraKwl.find(prefix, "distortion_units");
      rspfUnitConversionTool tool;
      rspfUnitType unitType = RSPF_MILLIMETERS;

      if(distortion_units)
      {
         unitType = (rspfUnitType)rspfUnitTypeLut::instance()->getEntryNumber(distortion_units);

         if(unitType == RSPF_UNIT_UNKNOWN)
         {
            unitType = RSPF_MILLIMETERS;
         }
      }
      if(image_size)
      {
         std::vector<rspfString> splitString;
         rspfString tempString(image_size);
         tempString.split(splitString, rspfString(" "));
         double w=1, h=1;
         if(splitString.size() == 2)
         {
            w = splitString[0].toDouble();
            h = splitString[1].toDouble();
         }
         theImageClipRect = rspfDrect(0,0,w-1,h-1);
         theRefImgPt      = rspfDpt(w/2.0, h/2.0);
      }
      if(sensor)
      {
         theSensorID = sensor;
      }
      if(principal_point)
      {
         std::vector<rspfString> splitString;
         rspfString tempString(principal_point);
         tempString.split(splitString, rspfString(" "));
         if(splitString.size() == 2)
         {
            thePrincipalPoint.x = splitString[0].toDouble();
            thePrincipalPoint.y = splitString[1].toDouble();
         }
      }
      if(pixel_size)
      {
         std::vector<rspfString> splitString;
         rspfString tempString(pixel_size);
         tempString.split(splitString, rspfString(" "));
         if(splitString.size() == 1)
         {
            thePixelSize.x = splitString[0].toDouble();
            thePixelSize.y = thePixelSize.x;
         }
         else if(splitString.size() == 2)
         {
            thePixelSize.x = splitString[0].toDouble();
            thePixelSize.y = splitString[1].toDouble();
         }
      }
      if(focal_length)
      {
         theFocalLength = rspfString(focal_length).toDouble();
      }

      cameraKwl.trimAllValues();
      
      
      rspfString regExpression =  rspfString("^(") + "d[0-9]+)";
      vector<rspfString> keys;
      cameraKwl.getSubstringKeyList( keys, regExpression );
      long numberOfDistortions = (long)keys.size();
      int offset = (int)rspfString("d").size();
      rspf_uint32 idx = 0;
      std::vector<int> numberList(numberOfDistortions);
      for(idx = 0; idx < (int)numberList.size();++idx)
      {
         rspfString numberStr(keys[idx].begin() + offset,
                               keys[idx].end());
         numberList[idx] = numberStr.toInt();
      }
      std::sort(numberList.begin(), numberList.end());
      double distance=0.0, distortion=0.0;

      for(idx = 0; idx < numberList.size(); ++idx)
      {
         rspfString value = cameraKwl.find(rspfString("d")+rspfString::toString(numberList[idx]));

         if(!value.empty())
         {
            std::istringstream inStr(value.c_str());
            inStr >> distance;
            rspf::skipws(inStr);
            inStr >> distortion;
#if 0
            std::vector<rspfString> splitString;
            rspfString tempString(value);
            tempString = tempString.trim();
            tempString.split(splitString, " ");
            std::cout << splitString.size() << std::endl;
            if(splitString.size() >= 2)
            {
               distance = splitString[0].toDouble();
               distortion = splitString[1].toDouble();
            }
#endif
            
            tool.setValue(distortion, unitType);
            lensKwl.add(rspfString("distance") + rspfString::toString(idx),
                        distance,
                        true);
            lensKwl.add(rspfString("distortion") + rspfString::toString(idx),
                        tool.getMillimeters(),
                        true);
         }
         lensKwl.add("convergence_threshold",
                     .00001,
                     true);
         if(pixel_size)
         {
            lensKwl.add("dxdy",
                        rspfString(pixel_size) + " " + rspfString(pixel_size),
                        true);
         }
         else
         {
            lensKwl.add("dxdy",
                        ".009 .009",
                        true);
         }
      }
      if(theLensDistortion.valid())
      {
         theLensDistortion->loadState(lensKwl,"");
      }
   }
NS_IMETHODIMP 
sbStringTransformImpl::NormalizeString(const nsAString & aCharset, 
                                       PRUint32 aTransformFlags, 
                                       const nsAString & aInput, 
                                       nsAString & _retval)
{
  nsString finalStr;
  nsString inStr(aInput);

  if(inStr.IsEmpty()) {
    _retval.Truncate();
    return NS_OK;
  }

  nsTArray<WORD> excludeChars[NTYPES];
  nsTArray<WORD> includeChars[NTYPES];
  DWORD dwFlags = MakeFlags(aTransformFlags, 
                            excludeChars,
                            includeChars);

  if(aTransformFlags & sbIStringTransform::TRANSFORM_LOWERCASE ||
     aTransformFlags & sbIStringTransform::TRANSFORM_UPPERCASE) {

    WCHAR *wszJunk = {0};
    int requiredBufferSize = ::LCMapStringW(LOCALE_USER_DEFAULT,
                                            dwFlags,
                                            inStr.BeginReading(),
                                            inStr.Length(),
                                            wszJunk,
                                            0);

    nsString bufferStr;
    int convertedChars = 
      ::LCMapStringW(LOCALE_USER_DEFAULT, 
                     dwFlags, 
                     inStr.BeginReading(), 
                     inStr.Length(), 
                     bufferStr.BeginWriting(requiredBufferSize),
                     requiredBufferSize);

    NS_ENSURE_TRUE(convertedChars == requiredBufferSize, 
                   NS_ERROR_CANNOT_CONVERT_DATA);

    finalStr = bufferStr;
    inStr = bufferStr;
  }

  if(aTransformFlags & sbIStringTransform::TRANSFORM_IGNORE_NONSPACE ||
     aTransformFlags & sbIStringTransform::TRANSFORM_IGNORE_SYMBOLS ||
     aTransformFlags & sbIStringTransform::TRANSFORM_IGNORE_NONALPHANUM ||
     aTransformFlags & sbIStringTransform::TRANSFORM_IGNORE_NONALPHANUM_IGNORE_SPACE) {
    PRBool leadingOnly = aTransformFlags & 
                         sbIStringTransform::TRANSFORM_IGNORE_LEADING;
    PRBool bypassTest = PR_FALSE;
    LPWSTR wszJunk = {0};
    int requiredBufferSize = ::FoldStringW(MAP_COMPOSITE, 
                                           inStr.BeginReading(), 
                                           inStr.Length(), 
                                           wszJunk, 
                                           0);

    nsString bufferStr;
    int convertedChars = 
      ::FoldStringW(MAP_COMPOSITE, 
                    inStr.BeginReading(),
                    inStr.Length(),
                    bufferStr.BeginWriting(requiredBufferSize),
                    requiredBufferSize);

    NS_ENSURE_TRUE(convertedChars == requiredBufferSize,
                   NS_ERROR_CANNOT_CONVERT_DATA);

    LPWORD ct1 = new WORD[requiredBufferSize];
    BOOL success = GetStringTypeW(CT_CTYPE1,
                                  (LPWSTR) bufferStr.BeginReading(), 
                                  bufferStr.Length(), 
                                  &ct1[0]);

    if(!success) {
      delete [] ct1;
      _retval.Truncate();
      return NS_ERROR_CANNOT_CONVERT_DATA;
    }

    LPWORD ct2 = new WORD[requiredBufferSize];
    success = GetStringTypeW(CT_CTYPE2,
                             (LPWSTR) bufferStr.BeginReading(), 
                             bufferStr.Length(), 
                             &ct2[0]);

    if(!success) {
     delete [] ct1;
     delete [] ct2;
     _retval.Truncate();
     return NS_ERROR_CANNOT_CONVERT_DATA;
    }

    LPWORD ct3 = new WORD[requiredBufferSize];
    success = GetStringTypeW(CT_CTYPE3,
                             (LPWSTR) bufferStr.BeginReading(), 
                             bufferStr.Length(), 
                             &ct3[0]);

    if(!success) {
     delete [] ct1;
     delete [] ct2;
     delete [] ct3;
     _retval.Truncate();
     return NS_ERROR_CANNOT_CONVERT_DATA;
    }

    LPWORD charTypes[NTYPES] = {ct1, ct2, ct3};

    for(int current = 0; current < requiredBufferSize; ++current) {
      PRBool validChar = PR_TRUE;
      PRInt32 skipChars = 0;

      if (!bypassTest) {
        if (aTransformFlags & sbIStringTransform::TRANSFORM_IGNORE_KEEPNUMBERSYMBOLS) {
          PRInt32 numberLength;
          SB_ExtractLeadingNumber(bufferStr.BeginReading() + current, NULL, NULL, &numberLength);
          if (numberLength > 0) {
            finalStr.Append(bufferStr.BeginReading() + current, numberLength);
            current += numberLength-1;
            if (leadingOnly) {
              bypassTest = PR_TRUE;
            }
            continue;
          }
        }
        
        // first check if the char is excluded by any of its type flags
        for (int type = FIRSTTYPE; type <= LASTTYPE && validChar; type++) {
          PRUint32 excludeCharsLength = excludeChars[type].Length();
          for(PRUint32 invalid = 0; invalid < excludeCharsLength; ++invalid) {
            if(excludeChars[type][invalid] & charTypes[type][current]) {
              validChar = PR_FALSE;
              break;
            }
          }
        }
        // next, check if the char is in the included chars arrays. if all
        // arrays are empty, allow all chars instead of none
        PRBool found = PR_FALSE;
        PRBool testedAnything = PR_FALSE;
        for (int type = FIRSTTYPE; 
             type <= LASTTYPE && validChar && !found; 
             type++) {
          PRUint32 includeCharsLength = includeChars[type].Length();
          for(PRUint32 valid = 0; valid < includeCharsLength; ++valid) {
            testedAnything = PR_TRUE;
            if (includeChars[type][valid] & charTypes[type][current]) {
              found = PR_TRUE;
              break;
            }
          }
        }
        if (testedAnything && 
            !found) {
          validChar = PR_FALSE;    
        }
      }
            
      if(validChar) {
        if (leadingOnly) {
          bypassTest = PR_TRUE;
        }
        finalStr.Append(bufferStr.CharAt(current));
      }
      current += skipChars;
    }

    delete [] ct1;
    delete [] ct2;
    delete [] ct3;
  }

  _retval = finalStr;

  return NS_OK;
}
Exemplo n.º 15
0
// `Main program' equivalent, creating windows and returning main app frame
bool MyApp::OnInit()
{
  // Use default list of macros defined in tex2any.cc
  DefineDefaultMacros();
  AddMacroDef(ltHARDY, _T("hardy"), 0);

  FileRoot = new wxChar[300];
  ContentsName = new wxChar[300];
  TmpContentsName = new wxChar[300];
  TmpFrameContentsName = new wxChar[300];
  WinHelpContentsFileName = new wxChar[300];
  RefFileName = new wxChar[300];

  WX_CLEAR_LIST(wxList,ColourTable);

  int n = 1;

  // Read input/output files
  if (argc > 1)
  {
      if (argv[1][0] != _T('-'))
      {
          InputFile = argv[1];
          n ++;

          if (argc > 2)
          {
              if (argv[2][0] != _T('-'))
              {
                  OutputFile = argv[2];
                  n ++;
              }
          }
      }
  }

#ifdef NO_GUI
  if (InputFile.empty() || OutputFile.empty())
  {
      wxSTD cout << "Tex2RTF: input or output file is missing.\n";
      ShowOptions();
      exit(1);
  }
#endif

  if (!InputFile.empty())
  {
      TexPathList.EnsureFileAccessible(InputFile);
  }
  if (InputFile.empty() || OutputFile.empty())
      isInteractive = true;

  int i;
  for (i = n; i < argc;)
  {
    if (wxStrcmp(argv[i], _T("-winhelp")) == 0)
    {
      i ++;
      convertMode = TEX_RTF;
      winHelp = true;
    }
#ifndef NO_GUI
    else if (wxStrcmp(argv[i], _T("-interactive")) == 0)
    {
      i ++;
      isInteractive = true;
    }
#endif
    else if (wxStrcmp(argv[i], _T("-sync")) == 0)  // Don't yield
    {
      i ++;
      isSync = true;
    }
    else if (wxStrcmp(argv[i], _T("-rtf")) == 0)
    {
      i ++;
      convertMode = TEX_RTF;
    }
    else if (wxStrcmp(argv[i], _T("-html")) == 0)
    {
      i ++;
      convertMode = TEX_HTML;
    }
    else if (wxStrcmp(argv[i], _T("-xlp")) == 0)
    {
      i ++;
      convertMode = TEX_XLP;
    }
    else if (wxStrcmp(argv[i], _T("-twice")) == 0)
    {
      i ++;
      runTwice = true;
    }
    else if (wxStrcmp(argv[i], _T("-macros")) == 0)
    {
      i ++;
      if (i < argc)
      {
        MacroFile = copystring(argv[i]);
        i ++;
      }
    }
    else if (wxStrcmp(argv[i], _T("-bufsize")) == 0)
    {
      i ++;
      if (i < argc)
      {
        BufSize = wxAtoi(argv[i]);
        i ++;
      }
    }
    else if (wxStrcmp(argv[i], _T("-charset")) == 0)
    {
      i ++;
      if (i < argc)
      {
        wxChar *s = argv[i];
        i ++;
        if (wxStrcmp(s, _T("ansi")) == 0 || wxStrcmp(s, _T("pc")) == 0 || wxStrcmp(s, _T("mac")) == 0 ||
            wxStrcmp(s, _T("pca")) == 0)
          RTFCharset = copystring(s);
        else
        {
          OnError(_T("Incorrect argument for -charset"));
          return false;
        }
      }
    }
    else if (wxStrcmp(argv[i], _T("-checkcurlybraces")) == 0)
    {
      i ++;
      checkCurlyBraces = true;
    }
    else if (wxStrcmp(argv[i], _T("-checkcurleybraces")) == 0)
    {
      // Support the old, incorrectly spelled version of -checkcurlybraces
      // so that old scripts which run tex2rtf -checkcurleybraces still work.
      i ++;
      checkCurlyBraces = true;
    }
    else if (wxStrcmp(argv[i], _T("-checksyntax")) == 0)
    {
      i ++;
      checkSyntax = true;
    }
    else
    {
      wxString buf;
      buf.Printf(_T("Invalid switch %s.\n"), argv[i]);
      OnError((wxChar *)buf.c_str());
#ifdef NO_GUI
      ShowOptions();
      exit(1);
#else
      return false;
#endif
    }
  }

#if defined(__WXMSW__) && !defined(NO_GUI)
  wxDDEInitialize();
  Tex2RTFLastStatus[0] = 0; // DDE connection return value
  TheTex2RTFServer = new Tex2RTFServer;
  TheTex2RTFServer->Create(_T("TEX2RTF"));
#endif

  TexInitialize(BufSize);
  ResetContentsLevels(0);

#ifndef NO_GUI

  if (isInteractive)
  {
    // Create the main frame window
    frame = new MyFrame(NULL, wxID_ANY, _T("Tex2RTF"), wxDefaultPosition, wxSize(400, 300));
#if wxUSE_STATUSBAR
    frame->CreateStatusBar(2);
#endif // wxUSE_STATUSBAR

    // Give it an icon
    // TODO: uncomment this when we have tex2rtf.xpm
    frame->SetIcon(wxICON(tex2rtf));

    if (!InputFile.empty())
    {
        wxString title;
        title.Printf( _T("Tex2RTF [%s]"), wxFileNameFromPath(InputFile).c_str());
        frame->SetTitle(title);
    }

    // Make a menubar
    wxMenu *file_menu = new wxMenu;
    file_menu->Append(TEX_GO, _T("&Go"), _T("Run converter"));
    file_menu->Append(TEX_SET_INPUT, _T("Set &Input File"), _T("Set the LaTeX input file"));
    file_menu->Append(TEX_SET_OUTPUT, _T("Set &Output File"), _T("Set the output file"));
    file_menu->AppendSeparator();
    file_menu->Append(TEX_VIEW_LATEX, _T("View &LaTeX File"), _T("View the LaTeX input file"));
    file_menu->Append(TEX_VIEW_OUTPUT, _T("View Output &File"), _T("View output file"));
    file_menu->Append(TEX_SAVE_FILE, _T("&Save log file"), _T("Save displayed text into file"));
    file_menu->AppendSeparator();
    file_menu->Append(TEX_QUIT, _T("E&xit"), _T("Exit Tex2RTF"));

    wxMenu *macro_menu = new wxMenu;

    macro_menu->Append(TEX_LOAD_CUSTOM_MACROS, _T("&Load Custom Macros"), _T("Load custom LaTeX macro file"));
    macro_menu->Append(TEX_VIEW_CUSTOM_MACROS, _T("View &Custom Macros"), _T("View custom LaTeX macros"));

    wxMenu *mode_menu = new wxMenu;

    mode_menu->Append(TEX_MODE_RTF, _T("Output linear &RTF"), _T("Wordprocessor-compatible RTF"));
    mode_menu->Append(TEX_MODE_WINHELP, _T("Output &WinHelp RTF"), _T("WinHelp-compatible RTF"));
    mode_menu->Append(TEX_MODE_HTML, _T("Output &HTML"), _T("HTML World Wide Web hypertext file"));
    mode_menu->Append(TEX_MODE_XLP, _T("Output &XLP"), _T("wxHelp hypertext help file"));

    wxMenu *options_menu = new wxMenu;

    options_menu->Append(TEX_OPTIONS_CURLY_BRACE, _T("Curly brace matching"), _T("Checks for mismatched curly braces"),true);
    options_menu->Append(TEX_OPTIONS_SYNTAX_CHECKING, _T("Syntax checking"), _T("Syntax checking for common errors"),true);

    options_menu->Check(TEX_OPTIONS_CURLY_BRACE, checkCurlyBraces);
    options_menu->Check(TEX_OPTIONS_SYNTAX_CHECKING, checkSyntax);

    wxMenu *help_menu = new wxMenu;

    help_menu->Append(TEX_HELP, _T("&Help"), _T("Tex2RTF Contents Page"));
    help_menu->Append(TEX_ABOUT, _T("&About Tex2RTF"), _T("About Tex2RTF"));

    menuBar = new wxMenuBar;
    menuBar->Append(file_menu, _T("&File"));
    menuBar->Append(macro_menu, _T("&Macros"));
    menuBar->Append(mode_menu, _T("&Conversion Mode"));
    menuBar->Append(options_menu, _T("&Options"));
    menuBar->Append(help_menu, _T("&Help"));

    frame->SetMenuBar(menuBar);
    frame->textWindow = new wxTextCtrl(frame, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY|wxTE_MULTILINE);

    (*frame->textWindow) << _T("Welcome to Tex2RTF.\n");
//    ShowOptions();

#if wxUSE_HELP
#if wxUSE_MS_HTML_HELP && !defined(__WXUNIVERSAL__)
    HelpInstance = new wxCHMHelpController;
#else
    HelpInstance = new wxHelpController;
#endif
    HelpInstance->Initialize(_T("tex2rtf"));
#endif // wxUSE_HELP

    /*
     * Read macro/initialisation file
     *
     */

    wxString path = TexPathList.FindValidPath(MacroFile);
    if (!path.empty())
        ReadCustomMacros(path);

#if wxUSE_STATUSBAR
    wxString inStr(_T("In "));
    switch (convertMode)
    {
        case TEX_RTF:
            if(winHelp)
                inStr += _T("WinHelp RTF");
            else
                inStr += _T("linear RTF");
            break;

        case TEX_HTML:
            inStr += _T("HTML");
            break;

        case TEX_XLP:
            inStr += _T("XLP");
            break;

        default:
            inStr += _T("unknown");
            break;
    }
    inStr += _T(" mode.");
    frame->SetStatusText(inStr, 1);
#endif // wxUSE_STATUSBAR

    frame->Show(true);
    return true;
  }
  else
#endif // NO_GUI
  {
    /*
     * Read macro/initialisation file
     *
     */

    wxString path = TexPathList.FindValidPath(MacroFile);
    if (!path.empty())
        ReadCustomMacros(path);

    Go();
    if (runTwice)
    {
        Go();
    }
#ifdef NO_GUI
    return true;
#else
    OnExit(); // Do cleanup since OnExit won't be called now
    return false;
#endif
  }
}
Exemplo n.º 16
0
/* throws Exception */
void BlobTest::doRetrieval()
{
  bool passed=false;

  TIMER_START("Blob Retrieval");
  rs.reset(stmt->executeQuery("SELECT blobdata from BLOBTEST LIMIT 1"));

  rs->next();
  TIMER_STOP("Blob Retrieval");

  TIMER_START("getString");
  String s(rs->getString(1));
  TIMER_STOP("getString");

  TIMER_START("Blob Check 1");
  passed=checkBlob(s);
  TIMER_STOP("Blob Check 1");

  ASSERT_MESSAGE(passed,
                 "Inserted BLOB data did not match retrieved BLOB data for getString().");

  s.clear();

  TIMER_START("getBlob");
  boost::scoped_ptr<std::istream> inStr(rs->getBlob(1));
  TIMER_STOP("getBlob");

  TIMER_START("Stream Reading");
  char buff[1048];

  while (!inStr->eof())
  {
    inStr->read(buff, sizeof (buff));
    s.append(buff, inStr->gcount());
  }
  TIMER_STOP("Stream Reading");

  TIMER_START("Blob Check 2");
  passed=checkBlob(s);
  TIMER_STOP("Blob Check 2");

  ASSERT_MESSAGE(passed, "Inserted BLOB data did not match retrieved BLOB data for getBlob().");

  /*
  inStr = rs->getAsciiStream(1);
      bOut = new ByteArrayOutputStream();
      while ((b = inStr.read()) != -1) {
        bOut.write((byte) b);
      }
      retrBytes = bOut.toByteArray();
      passed = checkBlob(retrBytes);
      assertTrue(
          "Inserted BLOB data did not match retrieved BLOB data for getAsciiStream().",
          passed);
      inStr = rs->getUnicodeStream(1);
      bOut = new ByteArrayOutputStream();
      while ((b = inStr.read()) != -1) {
        bOut.write((byte) b);
      }
      retrBytes = bOut.toByteArray();
      passed = checkBlob(retrBytes);
      assertTrue(
          "Inserted BLOB data did not match retrieved BLOB data for getUnicodeStream().",
          passed);*/

}
XbeeConfigurationWindow::XbeeConfigurationWindow(LinkInterface* link, QWidget *parent, Qt::WindowFlags flags): QWidget(parent, flags), 
	userConfigured(false)
{
	XbeeLinkInterface *xbeeLink = dynamic_cast<XbeeLinkInterface*>(link);

	if(xbeeLink != 0)
	{
		this->link = xbeeLink;

		action = new QAction(QIcon(":/files/images/devices/network-wireless.svg"), "", link);

		baudLabel = new QLabel;
		baudLabel->setText(tr("Baut Rate"));
		baudBox = new QComboBox;
		baudLabel->setBuddy(baudBox);
		portLabel = new QLabel;
		portLabel->setText(tr("SerialPort"));
		portBox = new QComboBox;
		portBox->setEditable(true);
		portLabel->setBuddy(portBox);
		highAddrLabel = new QLabel;
		highAddrLabel->setText(tr("Remote hex Address &High"));
		highAddr = new HexSpinBox(this);
		highAddrLabel->setBuddy(highAddr);
		lowAddrLabel = new QLabel;
		lowAddrLabel->setText(tr("Remote hex Address &Low"));
		lowAddr = new HexSpinBox(this);
		lowAddrLabel->setBuddy(lowAddr);
		actionLayout = new QGridLayout;
		actionLayout->addWidget(baudLabel,1,1);
		actionLayout->addWidget(baudBox,1,2);
		actionLayout->addWidget(portLabel,2,1);
		actionLayout->addWidget(portBox,2,2);
		actionLayout->addWidget(highAddrLabel,3,1);
		actionLayout->addWidget(highAddr,3,2);
		actionLayout->addWidget(lowAddrLabel,4,1);
		actionLayout->addWidget(lowAddr,4,2);
		tmpLayout = new QVBoxLayout;
		tmpLayout->addStretch();
		tmpLayout->addLayout(actionLayout);
		xbeeLayout = new QHBoxLayout;
		xbeeLayout->addStretch();
		xbeeLayout->addLayout(tmpLayout);
		this->setLayout(xbeeLayout);

		//connect(portBox,SIGNAL(activated(QString)),this,SLOT(setPortName(QString)));
		//connect(baudBox,SIGNAL(activated(QString)),this,SLOT(setBaudRateString(QString)));
		connect(portBox,SIGNAL(currentIndexChanged(QString)),this,SLOT(setPortName(QString)));
		connect(portBox,SIGNAL(editTextChanged(QString)),this,SLOT(setPortName(QString)));
		connect(baudBox,SIGNAL(currentIndexChanged(QString)),this,SLOT(setBaudRateString(QString)));
		connect(highAddr,SIGNAL(valueChanged(int)),this,SLOT(addrChangedHigh(int)));
		connect(lowAddr,SIGNAL(valueChanged(int)),this,SLOT(addrChangedLow(int)));
		connect(this,SIGNAL(addrHighChanged(quint32)),xbeeLink,SLOT(setRemoteAddressHigh(quint32)));
		connect(this,SIGNAL(addrLowChanged(quint32)),xbeeLink,SLOT(setRemoteAddressLow(quint32)));

		baudBox->addItem("1200",1200);
		baudBox->addItem("2400",2400);
		baudBox->addItem("4800",4800);
		baudBox->addItem("9600",9600);
		baudBox->addItem("19200",19200);
		baudBox->addItem("38400",38400);
		baudBox->addItem("57600",57600);
		baudBox->setCurrentIndex(6);

		// try to open xbeeConf file for last remote address
		QFile in("Xbeeconf.txt");
		if(in.open(QIODevice::ReadOnly))
		{
			QDataStream inStr(&in);
			int tmpaddrHigh;
			int tmpaddrLow;
			inStr >> tmpaddrHigh;
			inStr >> tmpaddrLow;
			highAddr->setValue(tmpaddrHigh);
			lowAddr->setValue(tmpaddrLow);
		}
Exemplo n.º 18
0
bool process_index_file(boost::filesystem::path path, ViolenceModel &model)
{
	if ( !boost::filesystem::exists(path) ) {
		std::cout << "Index file doesn't exist.\n";
		return false;
	}

	std::string line;
	uint lineNumber = 0;
	std::ifstream inFile(path.generic_string());

	// Check whether the string is compatible with our istream expectations.
	const boost::regex e("^\\s*(([01][\\s.]*)|(#)).*$");

	while ( std::getline(inFile, line) )
	{
		lineNumber++;
		line = boost::trim_copy(line);

		// If not, print an error message and move to the next line.
		if ( !boost::regex_match(line, e) ) {
			// TODO: It would be nice to give a more self explanatory error here.  If there were time.
			std::cout << "input file -> line " << lineNumber << " is malformed.  Ignoring: " << line << "\n";
			continue;
		}

		// Only process the line if it's not a comment.
		if ( !boost::starts_with(line, "#") ) {

			// Parse the line using an input stringstream.
			std::istringstream inStr(line);

			bool isViolent = false;
			inStr >> isViolent;

			std::string videoPathStr;
			inStr >> videoPathStr;

			// Good programmers always have doubt.
			std::cout << "input file -> " << " isViolent: " << isViolent << " path: " << videoPathStr << "\n";

			// Wrap a path object around the string.
			boost::filesystem::path videoPath = boost::filesystem::absolute(videoPathStr);
			std::vector<std::string> pathsToIndex;

			// If we've been given a path to a directory, then get load all files for indexing.
			if ( boost::filesystem::is_directory(videoPath) ) {

				std::cout << "input file -> path at line " << lineNumber << " is a directory. Adding children. \n";
				// Only accept files.  Don't recurse child directories.  Perhaps in v2.
				boost::filesystem::directory_iterator endIter;
				for ( boost::filesystem::directory_iterator iter(videoPath); iter != endIter; iter++ ) {

					if ( !boost::filesystem::is_directory( iter->path().string() ) ) {
						//std::cout<< "child: " << iter->path().string() << "\n";
						pathsToIndex.push_back(iter->path().string());
					} else {
						std::cout << "input file -> child path is a directory.  Skipping it.\n";
					}
				}

			} else {
				pathsToIndex.push_back(videoPathStr);
			}

			BOOST_FOREACH(std::string pathStr, pathsToIndex)
            {
				cv::VideoCapture vc;
				// TODO: Many "videos" used in computer vision research are actually a shorthand format string given to opencv
				//       that specifies the file name format (eg. img_%02d.jpg -> img_00.jpg, img_01.jpg, img_02.jpg, ...).
				//       Since these strings are more difficult to parse, we can simply attempt a file open first.
				//       That way the file path can be compatible with this feature as well.  Hopefully this isn't too expensive.
				if ( model.isIndexed(/*target,*/ pathStr) ) {
					//std::cout << "process_index_file -> skipping indexed path: " << pathStr << "\n";
                } else if ( vc.open(pathStr) ) {
                    // Woohoo!!
                    model.index(pathStr, isViolent);
                    model.persistStore();
                } else {
                    std::cout << "couldn't open file for indexing.\n";
                }
            }
		}
Exemplo n.º 19
0
int grep(char *l, char *pattern)
{
    return inStr(pattern, l);
}