Example #1
0
 TEST_F(TestString, testLastIndexOf) {
     String s = "foobar";
     ASSERT_NO_THROW({
     EXPECT_EQ(3,s.lastIndexOf("b"));
     EXPECT_EQ(2,s.lastIndexOf("ob"));
     EXPECT_EQ(-1,s.lastIndexOf("zaz"));
     EXPECT_EQ(-1,s.lastIndexOf("z"));
     });
Example #2
0
String SceneExportUtil::getPath( const String& str )
{
	int i1 = str.lastIndexOf("/");
	int i2 = str.lastIndexOf("\\");

	int i = i1;
	if ( i < i2 )
		i = i2;

	return str.substring( 0, i );
}
Example #3
0
static String stripPath( const String& name )
{
	String str;
	int end = name.lastIndexOf('/');
	int end2 = name.lastIndexOf('\\');
	if ( end2 > end )
		end = end2;
	if ( end >= 0 && end+1 < name.length() )
		str = name.substring( end+1 );
	else
		str = name;
	return str;
}
Example #4
0
String MyFunctionRequestHandler::parseFileName(String& path) {
  String filename;
  int lastIndex = path.lastIndexOf('\\');
  if (lastIndex < 0) {
    lastIndex = path.lastIndexOf('/');
  }
  if (lastIndex > 0) {
    filename = path.substring(lastIndex + 1);
  } else {
    filename = path;
  }

  filename.toLowerCase();
  return filename;
}
String FTPServerConnection::makeFileName(String name, bool shortIt)
{
	if (name.startsWith("/"))
		name = name.substring(1);

	if (shortIt && name.length() > 20)
	{
		String ext = "";
		if (name.lastIndexOf('.') != -1)
			ext = name.substring(name.lastIndexOf('.'));

		return name.substring(0, 16) + ext;
	}
	return directoryPrefix + name;
}
Example #6
0
void init_ObjCBridge(int argc, char*argv[])
{
	executable_directory = argv[0];
	executable_directory = executable_directory.substring(0, executable_directory.lastIndexOf('/'));
	
	ProjLoad_createDefaultFolders();
}
Example #7
0
String GM862::getCommand(String s){
    int location = s.lastIndexOf("OK");
//    Serial.println("location: " + location);
    s = s.substring(0,location - 2).trim();
//    Serial.println("extracted command as: '" + s + "'");
    return s;
}
boolean OTAUpdateClass::parseUpdateMD5(String* vxp_name, String* vxp_digest) {
    LFlash.begin();
    LFile update_md5 = LFlash.open(UPDATE_MD5);
    if(!update_md5) {
        DEBUG_UPDATE("OTAUpdate::parseUpdateMD5 - could not open %s\r\n", UPDATE_MD5);
        return false;
    }

    String line = "";
    while(update_md5.available()) {
        line += (char) update_md5.read();
    }
    update_md5.close();
    line.trim();

    // Warning : buffer line contain HTTP header !
    // should look for vxp name and md5 from the end of buffer

    // look for index of last word (md5 name file)
    int idx = line.lastIndexOf(" ");
    // get md4 name file from index until end of buffer
    *vxp_name = line.substring(idx);
    // get md5 from index and index - 32 bytes (lenght of md5 is constant)
    *vxp_digest = line.substring(idx - 33, idx - 1);

    vxp_name->trim();
    vxp_digest->trim();

    DEBUG_UPDATE("OTAUpdate::parseUpdateMD5 - %s [%s]\r\n", vxp_name->c_str(), vxp_digest->c_str());
    return true;
}
Example #9
0
bool loadFromSdCard(String path){
  String dataType = "text/plain";
  if(path.endsWith("/")) path += "index.htm";

  if(path.endsWith(".src")) path = path.substring(0, path.lastIndexOf("."));
  else if(path.endsWith(".htm")) dataType = "text/html";
  else if(path.endsWith(".css")) dataType = "text/css";
  else if(path.endsWith(".js")) dataType = "application/javascript";
  else if(path.endsWith(".png")) dataType = "image/png";
  else if(path.endsWith(".gif")) dataType = "image/gif";
  else if(path.endsWith(".jpg")) dataType = "image/jpeg";
  else if(path.endsWith(".ico")) dataType = "image/x-icon";
  else if(path.endsWith(".xml")) dataType = "text/xml";
  else if(path.endsWith(".pdf")) dataType = "application/pdf";
  else if(path.endsWith(".zip")) dataType = "application/zip";

  File dataFile = SD.open(path.c_str());
  if(dataFile.isDirectory()){
    path += "/index.htm";
    dataType = "text/html";
    dataFile = SD.open(path.c_str());
  }

  if (!dataFile)
    return false;

  if (server.hasArg("download")) dataType = "application/octet-stream";

  if (server.streamFile(dataFile, dataType) != dataFile.size()) {
    DBG_OUTPUT_PORT.println("Sent less data than expected!");
  }

  dataFile.close();
  return true;
}
Example #10
0
static int test_String1()
{
	const char* xa = "Hello, world!";
	const char* xa2 = " \n Hello, world! \n ";
	String x = xa;
	String xs = x.substring(7,12);
	assert( xs.length() == 12-7 );
	assert( xs == "world" );
	assert( String(xa+7,5) == xs );
	assert( x.endsWith("world!") );
	assert( !x.endsWith("world") );
	assert( x.startsWith("Hello") );
	assert( !x.startsWith("ello") );
	assert( x.hashCode() != 0 );
	assert( 7 == x.indexOf('w') );
	assert( 8 == x.indexOf("orld") );
	assert( 8 == x.lastIndexOf('o') );
	assert( 8 == x.lastIndexOf("o") );
	assert( x.replace('l','m') == "Hemmo, wormd!" );
	assert( String(xa2).trim() == xa );
	assert( String("greenblob #f").indexOf("#f") == 10 );
	assert( String("x.lua").getBytes(0,0,"ASCII-7") == 5 );
	char buf[256]; String("x.lua").getBytes(buf,sizeof(buf),"ASCII-7"); 
	assert( !strcmp(buf,"x.lua") );
	int len = Format("1,2,{0}",3).format().getBytes( buf, sizeof(buf), "ASCII-7" );
	assert( len == 5 );
	assert( !strcmp(buf,"1,2,3") );
	return 0;
}
Example #11
0
bool Sim900::getSignalQuality(int &strength, int &error_rate)
{
    if(lock())
    {
        _serial->write("AT+CSQ\r\n");
        _serial->flush();
        delay(100);
        String d;
        if(waitFor("OK", true, &d))
        {
            int _start = d.lastIndexOf("+CSQ");
            _start = d.indexOf(" ", _start) + 1;
            int split = d.indexOf(",", _start);
            int _end = d.indexOf("\r", _start);
            strength = d.substring(_start, split).toInt();
            error_rate = d.substring(split+1, _end).toInt();
            unlock();
            return true;
        } else
        {
            unlock();
        }
    }
    return false;
}
Example #12
0
bool AppManager_clean()
{
	String execPath = FileTools_getExecutableDirectory();
	int slashIndex = execPath.lastIndexOf('/');
	String appFolder;
	if(slashIndex==-1)
	{
		appFolder = execPath.substring(0, slashIndex);
	}
	else
	{
		appFolder = execPath;
	}
	
	String miniCodeInstallerPath = appFolder + "/installer";
	
	system(miniCodeInstallerPath + " -c");
	
	bool continuing = false;
	
	int counter = 0;
	while(FileTools_fileExists(AppManager_resultFile) && !continuing)
	{
		Thread::sleep(3);
		if(counter>=3000)
		{
			continuing = true;
		}
	}
	
	return true;
}
void Device::mqttData(void* response) {
  RESPONSE res(response);

  LOG("Received: topic=");
  String topic = res.popString();
  LOG(topic.c_str());

  LOG("data=");
  String data = res.popString();
  LOG(data.c_str());

  uint8_t start = topic.indexOf("asset/") + 6;
  uint8_t end = topic.lastIndexOf("/command");

  String name = topic.substring(start, end);

  Command cmd(name, data);

  // echo back command to platform to confirm the receipt
  if (_autoEcho)
    send(name.c_str(), data.c_str());

  // invoke user callback, if set
  invokeCommand(cmd);
}
Example #14
0
/*	Extracts substring from str starting with start char and ending with end char.
*	Returns extracted string (excluding start and end char),
*	or empty string if start or end char not found.
*/
String ArduEsp8266::getSubString(String str, char start, char end){
	int vIndexStart = str.indexOf( start );
	int vIndexEnd = str.lastIndexOf(end);
	if( vIndexStart >=0 && vIndexEnd > 0 )
		return str.substring( vIndexStart+1 , vIndexEnd );
	return "";
}
int MSearchClass::parseControlUrl(String *locationURL, IPAddress igdIp, uint16_t &igdPort)
{
    String locationUrlString = *locationURL;
    int lastColon = locationUrlString.lastIndexOf(':');
    int firstSlash = locationUrlString.indexOf('/', lastColon);
    locationUrlString = locationUrlString.substring(firstSlash);

    char locationUrlArray[locationUrlString.length()+1];
    locationUrlString.toCharArray(locationUrlArray, locationUrlString.length()+1);
    
    if (_igdClient.connect(igdIp, igdPort)) {
        
        char * buffer = (char *) malloc (32);
        memset(buffer, 0, 32);
        // Make a HTTP request:
        strcpy_P(buffer, IGD_RQST_LINE1A);
        _igdClient.print(buffer);
        memset(buffer, 0, 32);

        _igdClient.write((uint8_t *)locationUrlArray, locationUrlString.length());

        strcpy_P(buffer, IGD_RQST_LINE1B);
        _igdClient.print(buffer);

        free(buffer);        
        return parseXmlResponse();
    } 
    else {
        // if you didn't get a connection to the server:
        _igdClient.stop();
        return 0;
    }
}
Example #16
0
    void split (const String &path, String &parentDir, String &fileName, char chSep)
    {
        int iPathLen = path.length();
        if (iPathLen <= 0) {
            parentDir = "";
            fileName = "";
            return;
        }

        char buf[PATH_MAX];
        strcpy (buf, path);

        // Remove separator if it's the last character
        if (buf[iPathLen-1] == chSep) {
            buf[iPathLen-1] = '\0';
            iPathLen--;
        }

        int i = path.lastIndexOf (chSep);
        if (i < 0) {
            parentDir = "";
            fileName = buf;
            return;
        }

        buf[i] = '\0';
        parentDir = buf;
        fileName = &(buf[i+1]);
    }
Example #17
0
bool AppManager_runCommand(const String& srcFile, const ArrayList<String>& args)
{
	String resultFile = AppManager_resultFile;
	AppManager_clean();
	
	String execPath = FileTools_getExecutableDirectory();
	int slashIndex = execPath.lastIndexOf('/');
	String appFolder;
	if(slashIndex==-1)
	{
		appFolder = execPath.substring(0, slashIndex);
	}
	else
	{
		appFolder = execPath;
	}
	
	String miniCodeInstallerPath = appFolder + "/installer";
	String commandString = miniCodeInstallerPath + ' ';
	for(int i=0; i<args.size(); i++)
	{
		commandString += args.get(i) + ' ';
	}
	commandString += (String)"\"" + srcFile + "\"";
	system(commandString);
	
	while(!FileTools_fileExists(resultFile))
	{
		Thread::sleep(3);
	}
	
	String contents;
	bool success = FileTools::loadFileIntoString(resultFile, contents);
	AppManager_clean();
	if(!success)
	{
		showSimpleMessageBox("Error", "Error reading results from result file. Assuming failure.");
		return false;
	}
	
	for(int i=0; i<contents.length(); i++)
	{
		char c = contents.charAt(i);
		if(!(c>='0' && c<='9'))
		{
			showSimpleMessageBox("Error", "Invalid result string");
			return false;
		}
	}
	
	int result = String::asInt(contents);
	if(result==0)
	{
		return true;
	}
	Console::WriteLine((String)"Installer failed with exit code " + result);
	return false;
}
Example #18
0
String CompilerThread_getExtensionForFilename(const String& fileName)
{
	int index = fileName.lastIndexOf(".");
	if(index==-1 || index==(fileName.length()-1))
	{
		return "";
	}
	return fileName.substring(index+1).toLowerCase();
}
Example #19
0
MusInputStream(CodecMus MusInputStream::codecmus, URL url, InputStream inputstream) 
{
        codec = codecmus;
        buffer = new byte[1];
        inputStream = inputstream;
        String s = url.getPath();
        s = s.substring(s.lastIndexOf("/") + 1);
        hash_00 = s.hashCode();
}
int NameManager::validateLastName(const String& name, int species) {
	if (name.isEmpty())
		return NameManagerResult::ACCEPTED;

	//Wookiees are not allowed to have last names.
	if (species == CreatureObject::WOOKIE)
		return NameManagerResult::DECLINED_RACE_INAPP;

	if (name.length() > 20)
		return NameManagerResult::DECLINED_RACE_INAPP;

	if (isProfane(name))
		return NameManagerResult::DECLINED_PROFANE;

	if (isDeveloper(name))
		return NameManagerResult::DECLINED_DEVELOPER;

	if (isFiction(name))
		return NameManagerResult::DECLINED_FICT_RESERVED;

	if (isReserved(name))
		return NameManagerResult::DECLINED_RESERVED;

	//Make sure that only valid characters are allowed in the name.
	if (strspn(name.toCharArray(), "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'-") != name.length())
		return NameManagerResult::DECLINED_SYNTAX;

	//If the name has a hyphen or apostrophe, make sure they are the proper species.
	if (name.indexOf("'") != -1 || name.indexOf("-") != -1) {
		//Must be a human, twilek, moncal, or zabrak to have a hyphen or apostrophe.
		if (species != CreatureObjectImplementation::HUMAN && species != CreatureObjectImplementation::TWILEK && species != CreatureObjectImplementation::MONCAL && species != CreatureObjectImplementation::ZABRAK)
			return NameManagerResult::DECLINED_RACE_INAPP;

		//Moncal's aren't allowed to have apostrophes.
		if (species == CreatureObjectImplementation::MONCAL && name.indexOf("'") != -1)
			return NameManagerResult::DECLINED_RACE_INAPP;

		//Make sure they only have one hyphen and apostrophe in lastname.
		if (name.indexOf('\'') != name.lastIndexOf('\'') || name.indexOf('-') != name.lastIndexOf('-'))
			return NameManagerResult::DECLINED_RACE_INAPP;
	}

	return NameManagerResult::ACCEPTED;
}
Example #21
0
bool ImageDesignManager::validatePalette(PaletteColorCustomizationVariable* palette, int value, int skillLevel) {
	String paletteFileName = palette->getPaletteFileName();
	int idx = paletteFileName.lastIndexOf("/");

	if (idx != -1) {
		String paletteName = paletteFileName.subString(idx + 1);
		paletteName = paletteName.subString(0, paletteName.indexOf("."));

		//info("palette name = " + paletteName, true);

		PaletteData* data = CustomizationIdManager::instance()->getPaletteData(paletteName);

		if (data == NULL) {
			//error("could not find palette data for " + paletteName);
		} else {
			int maxIndex;

			switch (skillLevel) {
			case -1:
				maxIndex = data->getCreationIndexes();
				break;
			case 0:
				maxIndex = data->getIdNoviceIndexes();
				break;
			case 1:
				maxIndex = data->getIdLevel1Indexes();
				break;
			case 2:
				maxIndex = data->getIdLevel2Indexes();
				break;
			case 3:
				maxIndex = data->getIdLevel3Indexes();
				break;
			case 4:
				maxIndex = data->getIdLevel4Indexes();
				break;
			case 5:
				maxIndex = data->getIdMasterIndexes();
				break;
			default:
				maxIndex = -1;
				break;
			}

			if (value >= maxIndex || value < 0) {
				instance()->error("value for " + paletteFileName + " value " + value + " outside bound " + String::valueOf(maxIndex));

				return false;
			} else {
				//info(name + " value " + String::valueOf(val) + " inside bound " + String::valueOf(maxIndex) + " for " + name , true);
			}
		}
	}

	return true;
}
Example #22
0
	void testLastIndexOf() {
		const String source("Hello, World! Good bye, World - and again!");
		const String world("World");

        CPPUNIT_ASSERT_EQUAL(static_cast<String::size_type>(24), source.lastIndexOf(world).get());
        CPPUNIT_ASSERT_EQUAL(static_cast<String::size_type>(41), source.lastIndexOf('!').get());
        CPPUNIT_ASSERT_EQUAL(static_cast<String::size_type>(24), source.lastIndexOf(world, 12).get());
        CPPUNIT_ASSERT_EQUAL(static_cast<String::size_type>(19), source.lastIndexOf("bye", 12).get());

		// Fail case:
        CPPUNIT_ASSERT(source.lastIndexOf('!', source.length()).isNone());
        CPPUNIT_ASSERT(source.lastIndexOf('!', source.length() + 25).isNone());
        CPPUNIT_ASSERT(world.lastIndexOf(source).isNone());
        CPPUNIT_ASSERT(world.lastIndexOf("Some very long and obscure string??").isNone());
        CPPUNIT_ASSERT(world.lastIndexOf(source, world.size() + 3).isNone());
        CPPUNIT_ASSERT(world.lastIndexOf("Some very long and obscure string??", world.size() + 3).isNone());

        CPPUNIT_ASSERT(world.lastIndexOf('/').isNone());
	}
Example #23
0
String Nimbits::getContent(String response) {
     String str;
     int contentBodyIndex = response.lastIndexOf('\n\n');
            if (contentBodyIndex > 0) {
              str = response.substring(contentBodyIndex);

            }
     return str;

}
Example #24
0
int Nimbits::getResponseCode(String response) {


String sub = response.substring(9, 12);
int code = sub.toInt();

   if (_statusDelegate != NULL) {
        _statusDelegate(code, response.substring(12, response.lastIndexOf("\n")));
   }

   return code;
}
Example #25
0
/*	Returns received wifi data, or empty string if no data received.
*/
String ArduEsp8266::readData(){
	String vResponse = read();
	int vIndex = vResponse.indexOf( _EPS8266_DATA );
	int vIndexStart = vResponse.indexOf( ':' );
	int vIndexEnd = vResponse.lastIndexOf( '\r' );
	
	if( vIndex >= 0 && vIndexStart >= 0 && vIndexEnd > 0 ){
		return vResponse.substring( vIndexStart+1, vIndexEnd );
	}
	
	return "";
}
int allOn(String args) {
  int firstCommaPosition = args.indexOf(",");
  int lastCommaPosition = args.lastIndexOf(",");

  int r = atoi(args.substring(0,firstCommaPosition));
  int g = atoi(args.substring(
                      firstCommaPosition+1,lastCommaPosition));
  int b = atoi(args.substring(lastCommaPosition+1));
  
  button.allLedsOn(r,g,b);
  return 1;
}
Example #27
0
void TemplateManager::addTemplate(uint32 key, const String& fullName, LuaObject* templateData) {
	uint32 templateType = templateData->getIntField("templateType");
	String clientTemplateFile = templateData->getStringField("clientTemplateFileName");

	SharedObjectTemplate* templateObject = templateFactory.createObject(templateType);

	if (templateObject == NULL) {
		error("error creating template from lua with templateType 0x" + String::hexvalueOf((int)templateType));

		return;
	}

	//info("loading " + fullName, true);

	String fileName = fullName.subString(fullName.lastIndexOf('/') + 1, fullName.lastIndexOf('.'));

	templateObject->setFullTemplateString(fullName);
	templateObject->setTemplateFileName(fileName);

	if (!clientTemplateFile.isEmpty()) {
		IffStream* iffStream = openIffFile(clientTemplateFile);

		if (iffStream != NULL) {
			templateObject->readObject(iffStream);

			delete iffStream;
		}
	}

	templateObject->readObject(templateData);

	if (!clientTemplateFile.isEmpty())
		templateObject->addDerivedFile(clientTemplateFile);

	info("loaded " + fullName);

	if (templateCRCMap->put(key, templateObject) != NULL) {
		//error("duplicate template for " + fullName);
	}
}
void GenericCodeEditorComponent::findNext (bool forwards, bool skipCurrentSelection)
{
	const Range<int> highlight (getHighlightedRegion());
	const CodeDocument::Position startPos (getDocument(), skipCurrentSelection ? highlight.getEnd()
		: highlight.getStart());
	int lineNum = startPos.getLineNumber();
	int linePos = startPos.getIndexInLine();

	const int totalLines = getDocument().getNumLines();
	const String searchText (getSearchString());
	const bool caseSensitive = isCaseSensitiveSearch();

	for (int linesToSearch = totalLines; --linesToSearch >= 0;)
	{
		String line (getDocument().getLine (lineNum));
		int index;

		if (forwards)
		{
			index = caseSensitive ? line.indexOf (linePos, searchText)
				: line.indexOfIgnoreCase (linePos, searchText);
		}
		else
		{
			if (linePos >= 0)
				line = line.substring (0, linePos);

			index = caseSensitive ? line.lastIndexOf (searchText)
				: line.lastIndexOfIgnoreCase (searchText);
		}

		if (index >= 0)
		{
			const CodeDocument::Position p (getDocument(), lineNum, index);
			selectRegion (p, p.movedBy (searchText.length()));
			break;
		}

		if (forwards)
		{
			linePos = 0;
			lineNum = (lineNum + 1) % totalLines;
		}
		else
		{
			if (--lineNum < 0)
				lineNum = totalLines - 1;

			linePos = -1;
		}
	}
}
Example #29
0
void FontButton::activated(GdkEvent *event, GtkMenuItem *menuitem, GtkToolButton *toolbutton) {
	XOJ_CHECK_TYPE(FontButton);

	GtkFontButton * button = GTK_FONT_BUTTON(fontButton);

	String name = gtk_font_button_get_font_name(button);

	int pos = name.lastIndexOf(" ");
	this->font.setName(name.substring(0, pos));
	this->font.setSize(atof(name.substring(pos + 1).c_str()));

	handler->actionPerformed(ACTION_FONT_BUTTON_CHANGED, GROUP_NOGROUP, event, menuitem, NULL, true);
}
Example #30
0
 int runInt(CppiaCtx *ctx)
 {
    String val = strVal->runString(ctx);
    BCR_CHECK;
    String s = sought->runString(ctx);
    BCR_CHECK;
    hx::Object *first = start->runObject(ctx);
    BCR_CHECK;
    if (LAST)
       return val.lastIndexOf(s,first);
    else
       return val.indexOf(s,first);
 }