Пример #1
0
static bool findUserScalableValue(const String& keyString, const String& valueString, Document* document)
{
    // yes and no are used as keywords.
    // Numbers >= 1, numbers <= -1, device-width and device-height are mapped to yes.
    // Numbers in the range <-1, 1>, and unknown values, are mapped to no.

    if (equalIgnoringCase(valueString, "yes"))
        return true;
    if (equalIgnoringCase(valueString, "no"))
        return false;
    if (equalIgnoringCase(valueString, "desktop-width"))
        return true;
    if (equalIgnoringCase(valueString, "device-width"))
        return true;
    if (equalIgnoringCase(valueString, "device-height"))
        return true;

    bool ok;
    float value = valueString.toFloat(&ok);
    if (!ok) {
        reportViewportWarning(document, UnrecognizedViewportArgumentError, keyString);
        return false;
    }

    if (fabs(value) < 1)
        return false;

    return true;
}
Пример #2
0
void LocalHC12::verify(Ubidots client){
	String stream;
	while(p->available()){
		char c = p->read();
		stream += (char) c;
		if(c == '\n'){
			break;
		}
	}

	String type;
	type = stream.substring(0, stream.indexOf(" "));
	stream = stream.substring(stream.indexOf(" ")+1);
	String pin;
	pin = stream.substring(0, stream.indexOf(" "));
	String value;
	value = stream.substring(stream.indexOf(" ")+1);

	if(type == "1"){
		client.add(pin.c_str(),0);
		client.sendAll();
	}else if(type == "2"){
		client.add(chave.c_str(), value.toFloat());
		client.sendAll();
	}else if(type == "3"){
		float leitura = client.getValue(chave.c_str());
		p->write(leitura);
	}
}
static bool parseKeyTimes(const String& string, Vector<float>& result, bool verifyOrder)
{
    result.clear();
    Vector<String> parseList;
    string.split(';', true, parseList);
    for (unsigned n = 0; n < parseList.size(); ++n) {
        String timeString = parseList[n].stripWhiteSpace();
        bool ok;
        float time = timeString.toFloat(&ok);
        if (!ok || time < 0 || time > 1)
            goto fail;
        if (verifyOrder) {
            if (!n) {
                if (time)
                    goto fail;
            } else if (time < result.last()) {
                goto fail;
            }
        }
        result.append(time);
    }
    return true;
fail:
    result.clear();
    return false;
}
Пример #4
0
// For areas with DST - 2 DST rules, example: 10112-7.00,20032-6.00
// For areas without DST - one float for offset, example -7.00
bool c_timezones::f_setConfig(const String s_dstRules) {

  uint8_t s_start = 0;
  int8_t n_end = s_dstRules.indexOf(',');

  if (n_end == -1) {
    a_dstRuleOff.n_offset = (int)(s_dstRules.toFloat() * 60);
    a_dstRuleOff.n_month = 0;
    f_updateTimezone();
    return true;
  }
  String s_dtsRule = s_dstRules.substring(0, n_end);
  if (!f_parseRule(s_dtsRule, &a_dstRuleOff))
    return false;

  s_start = n_end + 1;
  n_end = s_dstRules.indexOf(',', s_start);
  s_dtsRule = n_end == -1
    ? s_dstRules.substring(s_start)
    : s_dstRules.substring(s_start, n_end);
  if (!f_parseRule(s_dtsRule, &a_dstRuleOn))
    return false;

  f_updateTimezone();
  return true;
}
Пример #5
0
static void parseKeyTimes(const String &parse, Vector<float> &result, bool verifyOrder)
{
    result.clear();
    Vector<String> parseList;
    parse.split(';', parseList);
    for (unsigned n = 0; n < parseList.size(); ++n) {
        String timeString = parseList[n];
        bool ok;
        float time = timeString.toFloat(&ok);
        if (!ok || time < 0 || time > 1.f) {
            goto fail;
        }
        if (verifyOrder) {
            if (!n) {
                if (time != 0) {
                    goto fail;
                }
            } else if (time < result.last()) {
                goto fail;
            }
        }
        result.append(time);
    }
    return;
fail:
    result.clear();
}
Пример #6
0
bool CaptureDeviceManager::sessionSupportsConstraint(const CaptureSessionInfo*, RealtimeMediaSource::Type type, const String& name, const String& value)
{
    const RealtimeMediaSourceSupportedConstraints& supportedConstraints = RealtimeMediaSourceCenter::singleton().supportedConstraints();
    MediaConstraintType constraint = supportedConstraints.constraintFromName(name);
    if (!supportedConstraints.supportsConstraint(constraint))
        return false;

    switch (constraint) {
    case MediaConstraintType::Width:
        return type == RealtimeMediaSource::Video;

    case MediaConstraintType::Height:
        return type == RealtimeMediaSource::Video;

    case MediaConstraintType::FrameRate: {
        if (type == RealtimeMediaSource::Audio)
            return false;

        return isSupportedFrameRate(value.toFloat());
    }
    case MediaConstraintType::FacingMode: {
        if (type == RealtimeMediaSource::Audio)
            return false;

        return bestDeviceForFacingMode(facingModeFromString(value));
    }
    default:
        return false;
    }
}
Пример #7
0
static float findTargetDensityDPIValue(const String& keyString, const String& valueString, Document* document)
{
    if (equalIgnoringCase(valueString, "device-dpi"))
        return ViewportArguments::ValueDeviceDPI;
    if (equalIgnoringCase(valueString, "low-dpi"))
        return ViewportArguments::ValueLowDPI;
    if (equalIgnoringCase(valueString, "medium-dpi"))
        return ViewportArguments::ValueMediumDPI;
    if (equalIgnoringCase(valueString, "high-dpi"))
        return ViewportArguments::ValueHighDPI;

    bool ok;
    float value = valueString.toFloat(&ok);
    if (!ok) {
        reportViewportWarning(document, UnrecognizedViewportArgumentError, keyString);
        return ViewportArguments::ValueAuto;
    }

     if (value < 70 || value > 400) {
        reportViewportWarning(document, TargetDensityDpiTooSmallOrLargeError, keyString);
        return ViewportArguments::ValueAuto;
    }

    return value;
}
Пример #8
0
static float findScaleValue(const String& keyString, const String& valueString, Document* document)
{
    // 1) Non-negative number values are translated to <number> values.
    // 2) Negative number values are translated to auto.
    // 3) yes is translated to 1.0.
    // 4) device-width and device-height are translated to 10.0.
    // 5) no and unknown values are translated to 0.0

    if (equalIgnoringCase(valueString, "yes"))
        return float(1.0);
    if (equalIgnoringCase(valueString, "no"))
        return float(0.0);
    if (equalIgnoringCase(valueString, "desktop-width"))
        return float(10.0);
    if (equalIgnoringCase(valueString, "device-width"))
        return float(10.0);
    if (equalIgnoringCase(valueString, "device-height"))
        return float(10.0);

    bool ok;
    float value = valueString.toFloat(&ok);
    if (!ok) {
        reportViewportWarning(document, UnrecognizedViewportArgumentError, keyString);
        return float(0.0);
    }

    if (value < 0)
        return ViewportArguments::ValueAuto;

    if (value > 10.0)
        reportViewportWarning(document, MaximumScaleTooLargeError, keyString);

    return value;
}
Пример #9
0
static float findSizeValue(const String& keyString, const String& valueString, Document* document)
{
    // 1) Non-negative number values are translated to px lengths.
    // 2) Negative number values are translated to auto.
    // 3) device-width and device-height are used as keywords.
    // 4) Other keywords and unknown values translate to 0.0.

    if (equalIgnoringCase(valueString, "desktop-width"))
        return ViewportArguments::ValueDesktopWidth;
    if (equalIgnoringCase(valueString, "device-width"))
        return ViewportArguments::ValueDeviceWidth;
    if (equalIgnoringCase(valueString, "device-height"))
        return ViewportArguments::ValueDeviceHeight;

    bool ok;
    float value = valueString.toFloat(&ok);
    if (!ok) {
        reportViewportWarning(document, UnrecognizedViewportArgumentError, keyString);
        return float(0.0);
    }

    if (value < 0)
        return ViewportArguments::ValueAuto;

    if (keyString == "width")
        reportViewportWarning(document, DeviceWidthShouldBeUsedWarning, keyString);
    else if (keyString == "height")
        reportViewportWarning(document, DeviceHeightShouldBeUsedWarning, keyString);

    return value;
}
Пример #10
0
int setCoolingSetpoint(String setPoint)
{
    if( setPoint.length() > 0 )
    {
        double setPointAsDouble = setPoint.toFloat();
        
        Serial.println("===> Cooling");
        Serial.print("\t");Serial.println(setPointAsDouble);
        
        if (setPointAsDouble == 0)
        {
            fermentationController->stop();
        }
        else
        {
            fermentationController->start(COOLING, setPointAsDouble);
        }
        
        return 1;
    }
    else
    {
        return -1;
    }
}
Пример #11
0
void TCoordinate::setMinutes(String parser)
{
	holder = parser.toFloat();
	decimal += holder / 60.00;
	minutes = (int_fast8_t)parser.substring(0,2).toInt();
	seconds = (int_fast8_t)parser.substring(2).toFloat()*60.00;
}
Пример #12
0
/**
 * Valid Pitch Lines

	81/64
	408.0
	408.
	5
	-5.0
	10/20
	100.0 cents
	100.0 C#
	5/4   E\

	Note : They can also have comments placed after them.
 */
float Tuning::processRatio(String* ratioText) {
	float ratio = 0.0;

	if(ratioText->indexOf(".") > 0) {
		int spacePos = ratioText->indexOf(" ");
		float cents = 0.0;
		if(spacePos > 0) {
			String centsSubstring = ratioText->substring(0,spacePos);

#ifdef DEBUG_TUNING
			Serial.print("Cents Substring:");
			Serial.print(centsSubstring);
			Serial.println(":");
#endif

			cents = centsSubstring.toFloat();
		} else {
			cents = ratioText->toFloat();
		}

		ratio = pow(2,(cents/100.0)/12.0);

#ifdef DEBUG_TUNING
		Serial.print("Ratio is cents ");
		Serial.println(cents);
#endif

	} else if(ratioText->indexOf("/") > 0) {
		int slashPos = ratioText->indexOf("/");
		float numerator = ratioText->substring(0,slashPos).toFloat();
		float denominator = ratioText->substring(slashPos+1).toFloat();
		if(numerator != 0 && denominator != 0) {
			ratio = numerator / denominator;
		}

#ifdef DEBUG_TUNING
		Serial.print("Ratio is ratio ");
		Serial.print(numerator);
		Serial.print("/");
		Serial.print(denominator);
		Serial.print(" = ");
		Serial.println(ratio,4);
#endif

	} else {
		ratio = ratioText->toFloat();
//		Serial.println("Ratio is float");
	}
//	Serial.println(ratio);
	return ratio;
}
Пример #13
0
void WeatherListener::value(String val) {
  DEBUG_PRINTLN(val);
  if(_lastKey == "day" && !_temperatureDone) {
    DEBUG_PRINT(F("-temp: "));
    DEBUG_PRINTLN(val);
    
    //_temperature((int8_t)_round_int(val.toFloat()));
    float d = val.toFloat();
    if(d > 0) {
      d = d + 0.5;
    } else {
      d = d - 0.5;
    }
    int8_t x = (int8_t)((d) + ((d) > 0 ? 0.5 : -0.5));
    _temperature((int8_t)d);
    _temperatureDone = true;
  }
  else if (_lastKey == "icon" && !_weatherDone) {
    DEBUG_PRINTLN("-icon: " + val);
    _weatherDone = true;
    if (val == "01d" || val == "01n" ) {
      _weather((int8_t)WEATHER_SONNE);
    }
    else if (val == "02d" || val == "02n") {
      _weather((int8_t)WEATHER_SONNEMITWOLKEN);
    }
    else if (val == "03d" || val == "03n") {
      _weather((int8_t)WEATHER_WOLKEN);
    }
    else if (val == "04d" || val == "04n") {
      _weather((int8_t)WEATHER_WOLKEN);
    }
    else if (val == "09d" || val == "09n") {
      _weather((int8_t)WEATHER_REGEN);
    }
    else if (val == "10d" || val == "10n") {
      _weather((int8_t)WEATHER_REGEN);
    }
    else if (val == "11d" || val == "11n") {
      _weather((int8_t)WEATHER_STURM);
    }
    else if (val == "13d" || val == "13n") {
      _weather((int8_t)WEATHER_SCHNEE);
    }
    else if (val == "50d" || val == "50n") {
      _weather((int8_t)WEATHER_NEBEL);
    }
  }
}
Пример #14
0
float Telemetry::receiveFloat()
{
    String factor = "";
    char c;
    while (Serial1.available() > 0) {
        c = Serial1.read();
        if (c == ';') {
            return factor.toFloat();
        }
        else {
            factor += c;
        }
    }
    return 0.0;
}
Пример #15
0
void ROTankWire::handleCmd(String var, String val) {
    if(var == "tdsoffset") {
        double offset = val.toFloat();
        //TheSensorsMem.TdsOffset = offset;
        TheTDSSensor.Update(offset);
    }
    else if(var == "phoffset") {
        double offset = val.toFloat();
        //ThePHSensor.Update(offset);
    }
    else if(var == "tdsVolts") {
        double volts = val.toFloat();
        TheTDSSensor.UpdateVolts(volts);
    }
    else if(var == "tdsMin") {
        int tdsMin = val.toInt();
        TheTDSSensor.UpdateTdsMin(tdsMin);
    }
    else if(var == "doseDurr") {
        int doseDurr = val.toInt();
        TheTDSSensor.UpdateRunDurration(doseDurr);
    }

}
Пример #16
0
/**********************************************************
 * @brief  readFloatData
 * @param  
 * @retval None
**********************************************************/
static float readFloatData()
{ 
char c=0;        
String readString;

  while (c != '\n')
  {
    if (Serial.available() >0)
    {
      c = Serial.read();  //gets one byte from serial buffer
      if ( c != '$')
        readString += c; //makes the string readString
    } 
  }    

  return readString.toFloat();
}
Пример #17
0
static float numericPrefix(const String& keyString, const String& valueString, Document* document, bool* ok)
{
    // If a prefix of property-value can be converted to a number using strtod,
    // the value will be that number. The remainder of the string is ignored.
    // So when String::toFloat says there is an error, it may be a false positive,
    // and we should check if the valueString prefix was a number.

    bool didReadNumber;
    float value = valueString.toFloat(ok, &didReadNumber);
    if (!*ok) {
        if (!didReadNumber) {
            ASSERT(!value);
            reportViewportWarning(document, UnrecognizedViewportArgumentValueError, valueString, keyString);
            return value;
        }
        *ok = true;
        reportViewportWarning(document, TruncatedViewportArgumentValueError, valueString, keyString);
    }
    return value;
}
void PlayDrillCommandClass::parse()
{
    LOGF("Parsing PlayDrill commmand");
    
    StringArray steps;
    String unparsed(getBuffer()); 
    
    int commaIdx = unparsed.indexOf(',');
    String pausePercentage = unparsed.substring(0, commaIdx);
    unparsed= unparsed.substring(commaIdx + 1);

    m_execData.pauseFactor= pausePercentage.toFloat() / 100.0;

    split(unparsed, EOF_STEP, steps);
    
    int stepIndex= 0;

    parse(*this, steps, stepIndex);

	setBuffer("");
}
Пример #19
0
void Ospom::elementParse(void) {
//############################  WORKING ON THIS SECTION NOW Also ##############################################################
  const int  EEPIDLoc[23] = {9,28,47,66,85,104,123,142,161,180,199,218,237,256,275,294,313,332,351,370};
 char ElementIDIn[9] = "        ";
 String serialReadString = "";
      //Load the Element ID
  for (int i = 8; i < 16; i++) {  
    char InChar = InputString.charAt(i);
    serialReadString += InChar;
  }
      //convert to Char array for comparison
  serialReadString.toCharArray(ElementIDIn, (serialReadString.length()+1));  //+1 to make it work
  serialReadString = ""; 
      //Compare it to the string of stored element id's, and say which # it is
  boolean foundElement = true;
  for (int i = 0; i < 20; i++) {
      char ElementID[9] = "        ";  //A temporary Variable for the ELement ID
      EEPROM.readBlock<char>(EEPIDLoc[i], ElementID, 8);  //Reads the Element ID from EEPROM
      if (strcmp(ElementID, ElementIDIn) == 0) {  //strcmp compares the two char arrays & returns a 0 if they are the same
        ElementNumber = i;
        foundElement = false;
      }
      if ((i == (20 - 1)) && (foundElement)) {
        fail();
      }
  }
  //clear the string
  serialReadString = "";
     //Load the Element Command Character  
  ElementCommandChar = InputString.charAt(16);
     //Load the Element Command Value
  for (int i = 18; i < 26; i++) {  
    char InChar = InputString.charAt(i);
    serialReadString += InChar;
  }
  serialReadString.toCharArray(CommandCharArray, (serialReadString.length()+1));   //+1 to make it work
  ElementCommandFloat = serialReadString.toFloat();
  ElementCommandInt = serialReadString.toInt();
  serialReadString = ""; 
}
void AtlasDo::read_response() {
  Wire.requestFrom(_i2c_address, 20, 1);
  byte response = Wire.read();
  String string = Wire.readStringUntil(0);

  if (response == 255) {
    status_level = ERROR;
    status_code = CODE_NO_RESPONSE;
    status_msg = "No response";
    _waiting_for_response = false;
  }
  else if (response == 254) {
    // Request hasn't been processed yet
    return;
  }
  else if (response == 2) {
    status_level = ERROR;
    status_code = CODE_REQUEST_FAILED;
    status_msg = "Request failed";
    _waiting_for_response = false;
  }
  else if (response == 1) {
    status_level = OK;
    status_code = CODE_OK;
    status_msg = "";
    _water_dissolved_oxygen = string.toFloat();
    _send_water_dissolved_oxygen = true;
    _waiting_for_response = false;
  }
  else {
    status_level = ERROR;
    status_code = CODE_UNKNOWN_ERROR;
    status_msg = "Unknown error";
    _waiting_for_response = false;
  }
}
Пример #21
0
void TCoordinate::setDegrees(String parser)
{
	degree = (uint_fast8_t)parser.toInt();
	decimal = parser.toFloat();
}
Пример #22
0
void Settings::setMetadataSettings(const String& key, const String& value)
{
    if (key == "width") {
        if (value == "device-width") {
            m_viewport_width = 0;
        } else {
            int width = value.toInt();
            if (width <= 10000) {
                if (width <= 320) {
                    // This is a hack to accommodate the pages designed for the
                    // original iPhone. The new version, since 10/2007, is to
                    // use device-width which works for both portrait and
                    // landscape modes.
                    m_viewport_width = 0;
                } else {
                    m_viewport_width = width;
                }
            }
        }
    } else if (key == "height") {
        if (value == "device-height") {
            m_viewport_height = 0;
        } else {
            int height = value.toInt();
            if (height >= 200 && height <= 10000) {
                m_viewport_height = height;
            }
        }
    } else if (key == "initial-scale") {
        int scale = int(value.toFloat() * 100);
        if (scale >= 1 && scale <= 1000) {
            m_viewport_initial_scale = scale;
        }
    } else if (key == "minimum-scale") {
        int scale = int(value.toFloat() * 100);
        if (scale >= 1 && scale <= 1000) {
            m_viewport_minimum_scale = scale;
        }
    } else if (key == "maximum-scale") {
        int scale = int(value.toFloat() * 100);
        if (scale >= 1 && scale <= 1000) {
            m_viewport_maximum_scale = scale;
        }
    } else if (key == "user-scalable") {
        // even Apple doc says using "no", "0" is common in the real world, and
        // some sites, e.g. gomoviesapp.com, use "false".
        if (value == "no" || value == "0" || value == "false") {
            m_viewport_user_scalable = false;
        }
    } else if (key == "target-densitydpi") {
        if (value == "device-dpi") {
            m_viewport_target_densitydpi = 0;
        } else if (value == "low-dpi") {
            m_viewport_target_densitydpi = 120;
        } else if (value == "medium-dpi") {
            m_viewport_target_densitydpi = 160;
        } else if (value == "high-dpi") {
            m_viewport_target_densitydpi = 240;
        } else {
            int dpi = value.toInt();
            if (dpi >= 70 && dpi <= 400) {
                m_viewport_target_densitydpi = dpi;
            }
        }
    } else if (key == "telephone") {
        if (value == "no") {
            m_format_detection_telephone = false;
        }
    } else if (key == "address") {
        if (value == "no") {
            m_format_detection_address = false;
        }
    } else if (key == "email") {
        if (value == "no") {
            m_format_detection_email = false;
        }
    } else if (key == "format-detection") {
        // even Apple doc says "format-detection" should be the name of the
        // <meta> tag. In the real world, e.g. amazon.com, use
        // "format-detection=no" in the "viewport" <meta> tag to disable all
        // format detection.
        if (value == "no") {
            m_format_detection_telephone = false;
            m_format_detection_address = false;
            m_format_detection_email = false;
        }
    }
}
Пример #23
0
	KinesisBodyDefinition KinesisWorldDefinition::ParseBodyDefinition(String content){
		KinesisBodyDefinition def;

		BlockSettings BodySettings = ParseBlockSettings(content);

		//all this block settings are in place, just iterate and store.
		cout<<"Body has "<<BodySettings.Settings.size()<<" properties set."<<endl;

		for(unsigned int i = 0; i < BodySettings.Settings.size(); i++){
			String propertyname = BodySettings.Settings[i].first;
			String propertydef = BodySettings.Settings[i].second;

			propertyname.toLowerCase();
			propertydef.toLowerCase();

			if(propertyname == "spawn"){
				def.Spawn = propertydef.toBoolean();
			}
			else if(propertyname == "position"){
				//def.Origin = propertydef.ToVec2f();
				//pDebug() << def.Origin;
			}
			else if(propertyname == "bodytype"){
				if(propertydef == "dynamic")
					def.BodyType = b2_dynamicBody;
				else if(propertydef == "static")
					def.BodyType = b2_staticBody;
				else if(propertydef == "kinematic")
					def.BodyType = b2_kinematicBody;
				else
					def.BodyType = b2_staticBody;
				
			}
			else{
				cout<<"Unknown property was set: "<<propertyname<<endl;
			}
		}

		//Now process children - for now assume there is only one level depth
		for(unsigned int i = 0; i < BodySettings.ChildSettings.size(); i++){
			String KindOfInnerBlock = BodySettings.ChildSettings[i].first;
			KindOfInnerBlock.toLowerCase();

			if(KindOfInnerBlock == "shape"){
				KinesisShapeDefinition ShapeDef;
			
				for(unsigned int j = 0; j < BodySettings.ChildSettings[i].second.Settings.size(); j++ ){
					String propertyname = BodySettings.ChildSettings[i].second.Settings[j].first;
					String propertydef = BodySettings.ChildSettings[i].second.Settings[j].second;

					propertyname.toLowerCase();
					propertydef.toLowerCase();

					if(propertyname == "shapetype"){
						unsigned int Type;
	
						if(propertydef == "box"){
							Type = KinesisShapeDefinition::BoxShape;
						}
						else if(propertydef == "circle"){
							Type = KinesisShapeDefinition::CircleShape;
						}
						else if(propertydef == "chain"){
							Type = KinesisShapeDefinition::ChainShape;
						}
						else{
							cout<<"Unknown shape type: "<<propertydef<<endl;
						}

						ShapeDef.ShapeType = Type;
					}
					else if(propertyname == "dimensions"){
					//	ShapeDef.Dimensions = propertydef.ToVec2f();
					}
					else if(propertyname == "density"){
						ShapeDef.Density = propertydef.toFloat();
					}
					else if(propertyname == "friction"){
						ShapeDef.Friction = propertydef.toFloat();
					}
					else if(propertyname == "pin"){
						//ShapeDef.Pin = propertydef.ToVec2f();
					}
					else{
						cout<<"Unknown property defined for: "<<KindOfInnerBlock<<"("<<propertyname<<")"<<endl;
					}
				}

				def.Shapes.push_back(ShapeDef);
			}
		}

		return def;
	};
Пример #24
0
 float ConfigFile::valueFromString<float>( const String& strVal ) const
 {
     return strVal.toFloat();
 }
Пример #25
0
  ExitCodes main_(int, const char**)
  {

    //-------------------------------------------------------------
    // parameter handling
    //-------------------------------------------------------------
    //file list
    StringList file_list = getStringList_("in");

    //file type
    FileHandler fh;
    FileTypes::Type force_type;
    if (getStringOption_("in_type").size() > 0)
    {
      force_type = FileTypes::nameToType(getStringOption_("in_type"));
    }
    else
    {
      force_type = fh.getType(file_list[0]);
    }

    //output file names and types
    String out_file = getStringOption_("out");

    //-------------------------------------------------------------
    // calculations
    //-------------------------------------------------------------

    bool annotate_file_origin =  getFlag_("annotate_file_origin");

    if (force_type == FileTypes::FEATUREXML)
    {
      FeatureMap<> out;
      for (Size i = 0; i < file_list.size(); ++i)
      {
        FeatureMap<> map;
        FeatureXMLFile fh;
        fh.load(file_list[i], map);

        if (annotate_file_origin)
        {
          for (FeatureMap<>::iterator it = map.begin(); it != map.end(); ++it)
          {
            it->setMetaValue("file_origin", DataValue(file_list[i]));
          }
        }
        out += map;
      }

      //-------------------------------------------------------------
      // writing output
      //-------------------------------------------------------------

      //annotate output with data processing info
      addDataProcessing_(out, getProcessingInfo_(DataProcessing::FORMAT_CONVERSION));

      FeatureXMLFile f;
      f.store(out_file, out);

    }
    else if (force_type == FileTypes::CONSENSUSXML)
    {
      ConsensusMap out;
      ConsensusXMLFile fh;
      fh.load(file_list[0], out);
      //skip first file
      for (Size i = 1; i < file_list.size(); ++i)
      {
        ConsensusMap map;
        ConsensusXMLFile fh;
        fh.load(file_list[i], map);

        if (annotate_file_origin)
        {
          for (ConsensusMap::iterator it = map.begin(); it != map.end(); ++it)
          {
            it->setMetaValue("file_origin", DataValue(file_list[i]));
          }
        }
        out += map;
      }

      //-------------------------------------------------------------
      // writing output
      //-------------------------------------------------------------

      //annotate output with data processing info
      addDataProcessing_(out, getProcessingInfo_(DataProcessing::FORMAT_CONVERSION));

      ConsensusXMLFile f;
      f.store(out_file, out);
    }
    else if (force_type == FileTypes::TRAML)
    {
      TargetedExperiment out;
      for (Size i = 0; i < file_list.size(); ++i)
      {
        TargetedExperiment map;
        TraMLFile fh;
        fh.load(file_list[i], map);
        out += map;
      }

      //-------------------------------------------------------------
      // writing output
      //-------------------------------------------------------------

      //annotate output with data processing info
      Software software;
      software.setName("FileMerger");
      software.setVersion(VersionInfo::getVersion());
      out.addSoftware(software);

      TraMLFile f;
      f.store(out_file, out);
    }
    else
    {
      // we might want to combine different types, thus we only
      // query in_type (which applies to all files)
      // and not the suffix or content of a single file
      force_type = FileTypes::nameToType(getStringOption_("in_type"));

      //rt
      bool rt_auto_number = getFlag_("raw:rt_auto");
      bool rt_filename = getFlag_("raw:rt_filename");
      bool rt_custom = false;
      DoubleList custom_rts = getDoubleList_("raw:rt_custom");
      if (custom_rts.size() != 0)
      {
        rt_custom = true;
        if (custom_rts.size() != file_list.size())
        {
          writeLog_("Custom retention time list must have as many elements as there are input files!");
          printUsage_();
          return ILLEGAL_PARAMETERS;
        }
      }

      //ms level
      bool user_ms_level = getFlag_("raw:user_ms_level");

      MSExperiment<> out;
      out.reserve(file_list.size());
      UInt rt_auto = 0;
      UInt native_id = 0;
      std::vector<MSChromatogram<ChromatogramPeak> > all_chromatograms;
      for (Size i = 0; i < file_list.size(); ++i)
      {
        String filename = file_list[i];

        //load file
        MSExperiment<> in;
        fh.loadExperiment(filename, in, force_type, log_type_);
        if (in.empty() && in.getChromatograms().empty())
        {
          writeLog_(String("Warning: Empty file '") + filename + "'!");
          continue;
        }
        out.reserve(out.size() + in.size());

        //warn if custom RT and more than one scan in input file
        if (rt_custom && in.size() > 1)
        {
          writeLog_(String("Warning: More than one scan in file '") + filename + "'! All scans will have the same retention time!");
        }

        for (MSExperiment<>::const_iterator it2 = in.begin(); it2 != in.end(); ++it2)
        {
          //handle rt
          Real rt_final = it2->getRT();
          if (rt_auto_number)
          {
            rt_final = ++rt_auto;
          }
          else if (rt_custom)
          {
            rt_final = custom_rts[i];
          }
          else if (rt_filename)
          {
            if (!filename.hasSubstring("rt"))
            {
              writeLog_(String("Warning: cannot guess retention time from filename as it does not contain 'rt'"));
            }
            for (Size i = 0; i < filename.size(); ++i)
            {
              if (filename[i] == 'r' && ++i != filename.size() && filename[i] == 't' && ++i != filename.size() && isdigit(filename[i]))
              {
                String rt;
                while (i != filename.size() && (filename[i] == '.' || isdigit(filename[i])))
                {
                  rt += filename[i++];
                }
                if (rt.size() > 0)
                {
                  // remove dot from rt3892.98.dta
                  //                          ^
                  if (rt[rt.size() - 1] == '.')
                  {
                    // remove last character
                    rt.erase(rt.end() - 1);
                  }
                }
                try
                {
                  float tmp = rt.toFloat();
                  rt_final = tmp;
                }
                catch (Exception::ConversionError)
                {
                  writeLog_(String("Warning: cannot convert the found retention time in a value '" + rt + "'."));
                }
              }
            }
          }

          // none of the rt methods were successful
          if (rt_final == -1)
          {
            writeLog_(String("Warning: No valid retention time for output scan '") + rt_auto + "' from file '" + filename + "'");
          }

          out.addSpectrum(*it2);
          out.getSpectra().back().setRT(rt_final);
          out.getSpectra().back().setNativeID(native_id);

          if (user_ms_level)
          {
            out.getSpectra().back().setMSLevel((int)getIntOption_("raw:ms_level"));
          }
          ++native_id;
        }

        // if we had only one spectrum, we can annotate it directly, for more spectra, we just name the source file leaving the spectra unannotated (to avoid a long and redundant list of sourceFiles)
        if (in.size() == 1)
        {
          out.getSpectra().back().setSourceFile(in.getSourceFiles()[0]);
          in.getSourceFiles().clear();   // delete source file annotated from source file (its in the spectrum anyways)
        }
        // copy experimental settings from first file
        if (i == 0)
        {
          out.ExperimentalSettings::operator=(in);
        }
        else // otherwise append
        {
          out.getSourceFiles().insert(out.getSourceFiles().end(), in.getSourceFiles().begin(), in.getSourceFiles().end()); // could be emtpty if spectrum was annotated above, but that's ok then
        }

        // also add the chromatograms
        for (std::vector<MSChromatogram<ChromatogramPeak> >::const_iterator it2 = in.getChromatograms().begin(); it2 != in.getChromatograms().end(); ++it2)
        {
          all_chromatograms.push_back(*it2);
        }

      }
      // set the chromatograms
      out.setChromatograms(all_chromatograms);

      //-------------------------------------------------------------
      // writing output
      //-------------------------------------------------------------

      //annotate output with data processing info
      addDataProcessing_(out, getProcessingInfo_(DataProcessing::FORMAT_CONVERSION));

      MzMLFile f;
      f.setLogType(log_type_);
      f.store(out_file, out);

    }

    return EXECUTION_OK;
  }
Пример #26
0
 double ConfigFile::valueFromString<double>( const String& strVal ) const
 {
     return strVal.toFloat();
 }
Пример #27
0
// Returns true if sentence parsed
bool MAXM8interface::parseSentence() {
	int sentenceEnd = sentence.length() - 1;
	bool sentenceValid = false;
	int valStart = 0;
	int valEnd = 0;
	int valIndex = 0;
	String value;
	
	valEnd = sentence.indexOf(',', valStart);
	if (valEnd > 0) {
		if (valEnd + 3 <= sentenceEnd) valEnd += 3; // Skip comma and include msgID
		value = sentence.substring(valStart, valEnd);
		if (value == "$PUBX,00") {
			sentenceValid = true;
			valStart = valEnd + 1; // Skip the next comma delimiter
			valIndex += 2;
		}
	}

	if (sentenceValid) {
		while (valEnd < sentenceEnd) {
			valEnd = sentence.indexOf(',', valStart); // index of comma
			if (valEnd < 0) valEnd = sentenceEnd; // indexOf returns -1 if no token found

			value = sentence.substring(valStart, valEnd); // Start inclusive, end exclusive
		
			switch(valIndex) {
				case PUBX00_TIME: // Format: hhmmss.s
					time = value.toFloat() + TIMEZONE;
					if (time < 0) time += 240000;
					else if (time > 240000) time -= 240000;
					if ((time - 10000*int(time/10000.0)) > 6000.0) time -= 4000.0;
					break;
				case PUBX00_LAT:
					latitude = value.toFloat();
					break;
				case PUBX00_NS:
					// Represent southern latitude as negative
					if (value == "S") latitude = -latitude;
					break;
				case PUBX00_LONG:
					longitude = value.toFloat();
					break;
				case PUBX00_EW:
					// Represent eastern latitude as negative
					if (value == "W") longitude = -longitude;
					break;
				case PUBX00_ALT:
					altitude = value.toFloat();
					break;
				case PUBX00_LOCK:
					if (value == "G3" || value == "D3" || value == "RK") gpsLock = true;
					else gpsLock = false;
					break;
				case PUBX00_HACC:
					accuracy = value.toFloat();
					break;
				case PUBX00_VACC: // This comes after PUBX00_HACC
					accuracy = sqrt(pow(accuracy, 2.0) + pow(value.toFloat(), 2.0));
					break;
				case PUBX00_SOG:
					groundSpeed = 0.2777778*value.toFloat(); // km/hr to m/s
					break;
				case PUBX00_COG:
					groundCourse = value.toFloat();
					break;
				case PUBX00_VVEL:
					rateOfClimb = -value.toFloat(); // Need to change sign
					break;
				case PUBX00_NSAT:
					nSats = value.toInt();
					break;
			}

			valStart = valEnd + 1;
			valIndex ++;
		}

		if (gpsLock && maxAlt < altitude - accuracy) {
			maxAlt = altitude - accuracy;
			maxAltIncreased = true;
		}
		else maxAltIncreased = false;

		sentence = "";
		return true;
	}
	else {
		sentence = "";
		return false;
	}
}
Пример #28
0
float WebPreferences::floatValueForKey(String key)
{
    String value = m_privatePrefs.get(key);
    return value.toFloat();
}
Пример #29
0
bool WebServerTask::parse(String key, String value) {

    DSKey newKey;

    if (key.equals("tz")) {
        newKey = DS_TIMEZONE;
    } else if (key.equals("brightness")) {
        newKey = DS_BRIGHTNESS;
    } else if (key.equals("hour_color")) {
        newKey = DS_HOUR_COLOR;
    } else if (key.equals("minute_color")) {
        newKey = DS_MINUTE_COLOR;
    } else if (key.equals("second_color")) {
        newKey = DS_SECOND_COLOR;
    } else if (key.equals("animation")) {
        newKey = DS_CLOCK_ANIMATION;
    } else if (key.equals("night_mode_enable")) {
        newKey = DS_NIGHT_MODE_ENABLE;
    } else if (key.equals("night_mode_brightness")) {
        newKey = DS_NIGHT_MODE_BRIGHTNESS;
    } else if (key.equals("gamma")) {
        newKey = DS_GAMMA;
    } else {
        return false;
    }

    int newVal;
    float f;

    switch(newKey) {

        case DS_TIMEZONE:
        case DS_BRIGHTNESS:
        case DS_CLOCK_ANIMATION:
        case DS_NIGHT_MODE_ENABLE:
        case DS_NIGHT_MODE_BRIGHTNESS:
            newVal = value.toInt();
            break;

        case DS_HOUR_COLOR:
        case DS_MINUTE_COLOR:
        case DS_SECOND_COLOR:
            // Convert the hex string to an int. Offset to remove the preceding # symbol.
            newVal = (int)strtol(&value[1], NULL, 16);
            break;

        case DS_GAMMA:
            // Force the 32-bit float into an int type for storage
            f = value.toFloat();
            newVal = *reinterpret_cast<int*>(&f);
            break;

        default:
            newVal = -1;
            break;
    }

    Serial.println(key + "," + value + " -> " +
                   String(newKey) + "," + String(newVal));

    return DataStore.set(newKey, newVal);
}
Пример #30
0
uint32_t RTCDue::unixtime (String abbreviation)
{
  float adjustment = abbreviation.toFloat() * SECONDS_PER_HOUR;
  
  return unixtime() - (int)adjustment;
}