bcf_directory_entry* CompoundFileDirectoryEntry(FILE* file)
{
    bcf_directory_entry* dir = (bcf_directory_entry*)malloc(sizeof(bcf_directory_entry));
    if(!dir) { embLog_error("compound-file-directory.c CompoundFileDirectoryEntry(), cannot allocate memory for dir\n"); } /* TODO: avoid crashing. null pointer will be accessed */
    memset(dir->directoryEntryName, 0, 32);
    parseDirectoryEntryName(file, dir);
    dir->next = 0;
    dir->directoryEntryNameLength = binaryReadUInt16(file);
    dir->objectType = (unsigned char)binaryReadByte(file);
    if( (dir->objectType != ObjectTypeStorage) &&
        (dir->objectType != ObjectTypeStream) &&
        (dir->objectType != ObjectTypeRootEntry))
    {
        embLog_error("compound-file-directory.c CompoundFileDirectoryEntry(), unexpected object type: %d\n", dir->objectType);
        return 0;
    }
    dir->colorFlag = (unsigned char)binaryReadByte(file);
    dir->leftSiblingId = binaryReadUInt32(file);
    dir->rightSiblingId = binaryReadUInt32(file);
    dir->childId = binaryReadUInt32(file);
    readCLSID(file, dir);
    dir->stateBits = binaryReadUInt32(file);
    dir->creationTime = parseTime(file);
    dir->modifiedTime = parseTime(file);
    dir->startingSectorLocation = binaryReadUInt32(file);
    dir->streamSize = binaryReadUInt32(file); /* This should really be __int64 or long long, but for our uses we should never run into an issue */
    dir->streamSizeHigh = binaryReadUInt32(file); /* top portion of int64 */
    return dir;
}
Exemple #2
0
static const char *
parseRule(register char *buf, register const char *p)
{
	long time;
	register const char *q;

	if (!(p = parseDate(buf, p, &dststart))) return NULL;
	buf += strlen(buf);
	if (*p == '/') {
		q = ++p;
		if (!(p = parseTime(&time, p, &dststart))) return NULL;
		while( p != q) *buf++ = *q++;
	}
	if (*p != ',') return NULL;
	p++;
	if (!(p = parseDate(buf, p, &dstend))) return NULL;
	buf += strlen(buf);
	if (*p == '/') {
		q = ++p;
		if (!(p = parseTime(&time, p, &dstend))) return NULL;
		while(*buf++ = *q++);
	}
	if (*p) return NULL;
	return p;
}
Exemple #3
0
/* The following routine parses timezone information in POSIX-format. For
 * the requirements, see IEEE Std 1003.1-1988 section 8.1.1.
 * The function returns as soon as it spots an error.
 */
static void
parseTZ(const char *p)
{
	long tz, dst = 60 * 60, sign = 1;
	static char lastTZ[2 * RULE_LEN];
	static char buffer[RULE_LEN];

	if (!p) return;

	if (*p == ':') {
		/*
		 * According to POSIX, this is implementation defined.
		 * Since it depends on the particular operating system, we
		 * can do nothing.
		 */
		return;
	}

	if (!strcmp(lastTZ, p)) return;		/* nothing changed */

	*_tzname[0] = '\0';
	*_tzname[1] = '\0';
	dststart.ds_type = 'U';
	dststart.ds_sec = 2 * 60 * 60;
	dstend.ds_type = 'U';
	dstend.ds_sec = 2 * 60 * 60;

	if (strlen(p) > 2 * RULE_LEN) return;
	strcpy(lastTZ, p);

	if (!(p = parseZoneName(buffer, p))) return;

	if (*p == '-') {
		sign = -1;
		p++;
	} else if (*p == '+') p++;

	if (!(p = parseTime(&tz, p, NULL))) return;
	tz *= sign;
	_timezone = tz;
	strncpy(_tzname[0], buffer, TZ_LEN);

	if (!(_daylight = (*p != '\0'))) return;

	buffer[0] = '\0';
	if (!(p = parseZoneName(buffer, p))) return;
	strncpy(_tzname[1], buffer, TZ_LEN);

	buffer[0] = '\0';
	if (*p && (*p != ','))
		if (!(p = parseTime(&dst, p, NULL))) return;
	_dst_off = dst;			/* dst was initialized to 1 hour */
	if (*p) {
		if (*p != ',') return;
		p++;
		if (strlen(p) > RULE_LEN) return;
		if (!(p = parseRule(buffer, p))) return;
	}
}
QString WeatherPlugin::replace(const QString &text)
{
    QString res = text;
    QString sun_set, sun_raise, updated;
#if COMPAT_QT_VERSION >= 0x030000
    QTime tmp_time;
    QDateTime dt;
    int h,m;

    parseTime(getSun_set(),h,m);
    tmp_time.setHMS(h,m,0,0);
    sun_set = tmp_time.toString(Qt::LocalDate);
    sun_set = sun_set.left(sun_set.length() - 3);

    parseTime(getSun_raise(),h,m);
    tmp_time.setHMS(h,m,0,0);
    sun_raise = tmp_time.toString(Qt::LocalDate);
    sun_raise = sun_raise.left(sun_raise.length() - 3);

    parseDateTime(getUpdated(),dt);
    updated = dt.toString(Qt::LocalDate);
    updated = updated.left(updated.length() - 3);
#else
    sun_set = getSun_set();
    sun_raise = getSun_raise();
    updated = getUpdated();
#endif
    /* double Expressions *before* single or better RegExp ! */
    res = res.replace(QRegExp("\\%mp"), i18n("moonphase", getMoonPhase()));
    res = res.replace(QRegExp("\\%mi"), number(getMoonIcon()));
    res = res.replace(QRegExp("\\%pp"), number(getPrecipitation()));
	res = res.replace(QRegExp("\\%ut"), i18n("weather", getUV_Description()));
	res = res.replace(QRegExp("\\%ui"), number(getUV_Intensity()));
    res = res.replace(QRegExp("\\%t"), QString::number((int)getTemperature()) + QChar((unsigned short)176) + getUT());
    res = res.replace(QRegExp("\\%f"), QString::number((int)getFeelsLike()) + QChar((unsigned short)176) + getUT());
    res = res.replace(QRegExp("\\%d"), QString::number((int)getDewPoint()) + QChar((unsigned short)176) + getUT());
    res = res.replace(QRegExp("\\%h"), number(getHumidity()) + "%");
    res = res.replace(QRegExp("\\%w"), number(getWind_speed()) + " " + i18n(getUS()));
    res = res.replace(QRegExp("\\%x"), QString::number(getWind_speed() * 10 / 36) + " " + i18n("m/s"));
    res = res.replace(QRegExp("\\%g"), getWindGust() ? QString("(") + i18n("gust ") + number(getWindGust()) + i18n(getUS()) + QString(")") : QString(""));
    res = res.replace(QRegExp("\\%y"), getWindGust() ? QString("(") + i18n("gust ") + number(getWindGust() * 10 / 36) + QString(" ") + i18n("m/s") + QString(")") : QString(""));
    res = res.replace(QRegExp("\\%p"), number(getPressure()) + " " + i18n(getUP()));
    res = res.replace(QRegExp("\\%a"), number(getPressure() * 75 / 100));
    res = res.replace(QRegExp("\\%q"), i18n("weather", getPressureD()));
    res = res.replace(QRegExp("\\%l"), getLocation());
    res = res.replace(QRegExp("\\%b"), i18n("weather", getWind()));
    res = res.replace(QRegExp("\\%u"), updated);
    res = res.replace(QRegExp("\\%r"), sun_raise);
    res = res.replace(QRegExp("\\%s"), sun_set);
    res = res.replace(QRegExp("\\%c"), i18n_conditions(getConditions()));
    res = res.replace(QRegExp("\\%v"), i18n("weather", getVisibility()) + (atol(getVisibility()) ? QString(" ") + i18n(getUD()) : QString("")));
    res = res.replace(QRegExp("\\%i"), number(getIcon()));
    return res;
}
Exemple #5
0
struct tm *
gmtime(const time_t *gmt)
{
	
	parseTime(gmt, FALSE, &system_time);
	return (&system_time);
}
Exemple #6
0
/**	The gmtime_r() function converts the time in seconds since the Epoch pointed
	to by 'time' into a broken-down time, expressed as Coordinated Universal Time
	(UTC) (formerly called Greenwich Mean Time (GMT)).
	
	This function is similar to gmtime(), except that it parses the time into a
	tm structure pointed to by the argument, 'resultp.' The gmtime_r() function
	is thread-safe and returns values in a user-supplied buffer instead of
	possibly using a static data area that may be overwritten by each call.
	
	If the conversion is successful the function returns a pointer to the object the
	result was written into, i.e., it returns resultp.
	
	\brief Parse a time into struct tm and return pointer to it.
	\param const time_t *time - pointer to local or system (UNIX) time
	\param struct tm *resultp - pointer to a tm structure to receive the result
 */
struct tm *
gmtime_r(const time_t *utc, struct tm *resultp)
{
	
	parseTime(utc, FALSE, resultp);
	return (resultp);
}
Exemple #7
0
	StructTime::StructTime(sp<MagicString>& mStr):
		hour(0), 
		minute(0), 
		second(0), 
		mSecond(0){
		parseTime(mStr);
	}
Exemple #8
0
int Params::evalAdjust(const std::string& optarg)
{
    int rc = 0;
    switch (action_) {
    case Action::none:
        action_ = Action::adjust;
        adjust_ = parseTime(optarg, adjustment_);
        if (!adjust_) {
            std::cerr << progname() << ": " << _("Error parsing -a option argument") << " `"
                      << optarg << "'\n";
            rc = 1;
        }
        break;
    case Action::adjust:
        std::cerr << progname()
                  << ": " << _("Ignoring surplus option -a")  << " " << optarg << "\n";
        break;
    default:
        std::cerr << progname()
                  << ": " << _("Option -a is not compatible with a previous option\n");
        rc = 1;
        break;
    }
    return rc;
} // Params::evalAdjust
Exemple #9
0
	/* Read fields into Mod */
	void ModFrame::dump(Mod * mod)
	{
		int n = 1;
		// mode
		mod->mod.mode = getChecked(modeRadios, MOVIESOAP_MOD_MODE_COUNT);
		// times
		mod->mod.start = parseTime(startText);
		mod->mod.stop = parseTime(stopText);
		mod->mod.title = parseInt(titleText);
		// severity
		mod->mod.severity = getChecked(severityRadios, MOVIESOAP_TOLERANCE_COUNT-1) + 1;
		// category
		mod->mod.category = categoryBox->currentIndex();
		// description
		mod->description = descText->text().toAscii().data();
	}
bool WeatherPlugin::isDay()
{
    int raise_h, raise_m;
    int set_h, set_m;
    if (!parseTime(getSun_raise(), raise_h, raise_m) || !parseTime(getSun_set(), set_h, set_m))
        return false;
    time_t now = time(NULL);
    struct tm *tm = localtime(&now);
    if ((tm->tm_hour > raise_h) && (tm->tm_hour < set_h))
        return true;
    if ((tm->tm_hour == raise_h) && (tm->tm_min >= raise_m))
        return true;
    if ((tm->tm_hour == set_h) && (tm->tm_min <= set_m))
        return true;
    return false;
}
Exemple #11
0
boost::posix_time::ptime parseTimeNoThrow(const word * data)
{
	try
	{
		return parseTime(data);
	}
	catch(std::exception &) {}
    return boost::posix_time::ptime();
}
bool ubloxNMEA::parsePUBX_04( char chr )
{
  #ifdef NMEAGPS_PARSE_PUBX_04
    switch (fieldIndex) {
        case 2: return parseTime( chr );
        case 3: return parseDDMMYY( chr );
    }
  #endif

  return true;

} // parsePUBX_04
Exemple #13
0
bool getTimestamp(string dir_timestamp, unsigned int entry_number, ros::Time &stamp)
{
	string str_support = (fs::path(dir_timestamp) / fs::path("timestamps.txt")).string();
	ifstream timestamps(str_support.c_str());
	if (!timestamps.is_open())
	{
	    ROS_ERROR_STREAM("Fail to open " << timestamps);
	    return true;
	}
	timestamps.seekg(30*entry_number);
	getline(timestamps,str_support);
	stamp = parseTime(str_support);
	return false;
}
void JourneySearchParser::parseDateAndTime( const QString& sDateTime,
                                            QDateTime* dateTime, QDate* alreadyParsedDate )
{
    QDate date;
    QTime time;
    bool callParseDate = alreadyParsedDate->isNull();

    // Parse date and/or time from sDateTime
    QStringList timeValues = sDateTime.split( QRegExp( "\\s|," ), QString::SkipEmptyParts );
    if ( timeValues.count() >= 2 ) {
        if ( callParseDate && !parseDate(timeValues[0], &date)
                    && !parseDate(timeValues[1], &date) ) {
            date = QDate::currentDate();
        } else {
            date = *alreadyParsedDate;
        }

        if ( !parseTime(timeValues[1], &time) && !parseTime(timeValues[0], &time) ) {
            time = QTime::currentTime();
        }
    } else {
        if ( !parseTime(sDateTime, &time) ) {
            time = QTime::currentTime();
            if ( callParseDate && !parseDate(sDateTime, &date) ) {
                date = QDate::currentDate();
            } else {
                date = *alreadyParsedDate;
            }
        } else if ( callParseDate ) {
            date = QDate::currentDate();
        } else {
            date = *alreadyParsedDate;
        }
    }

    *dateTime = QDateTime( date, time );
}
void getAnalyzerRunInfo(void) {
	AnalyzerRunInfo *prunInfo = &analyzerInfo;
	get_analyzer_version(prunInfo->version,19);

  char *s;
	char *start;
	char startTimeStr[64];
	char tmp[1024];
	memset(startTimeStr, 0, sizeof(startTimeStr));
	prunInfo->isRunning = FALSE;
	//ps -eo pid,cmd,lstart
	FILE *file = popen("ps -eo lstart,cmd", "r");
	if (file == NULL) {
		return;
	}
	//Mon Mar 28 17:26:56 2011 /ptswitch/analyzer-linux_64 -d
	//Tue May  4 03:31:33 2010
	char *token;
	while ((s = fgets(tmp, sizeof(tmp), file))) {
		token = strtok(tmp, "\n");
		while (token != NULL) {
			start = strstr(token, "analyzer");
			if (start) {
				strncpy(startTimeStr, token, start - tmp);
				prunInfo->isRunning = TRUE;
				break;
			}
			token = strtok(NULL, "\n");
		}
	}
	pclose(file);
	sprintf(prunInfo->startTime, trim(startTimeStr));
//	printf("hxzon debug,start time=%s\n",prunInfo->startTime);
	struct tm startTimeInfo;
	parseTime(prunInfo->startTime, &startTimeInfo);
	long startTime = mktime(&startTimeInfo);
	time_t t;
	time(&t);
	long span = t - startTime;
	//	printf("span time = %d\n",span);
	span = span / (3600);
//	printf("span time = %ld hour \n",span);
	prunInfo->dayDuration = span / 24;
	prunInfo->hourDuration = span % 24;
	strftime(prunInfo->startTime, 50, "%Y-%m-%d  %H:%M:%S\n", &startTimeInfo);
}
bool DateComponents::parseDateTimeLocal(const String& src, unsigned start, unsigned& end)
{
    unsigned index;
    if (!parseDate(src, start, index))
        return false;
    if (index >= src.length())
        return false;
    if (src[index] != 'T')
        return false;
    ++index;
    if (!parseTime(src, index, end))
        return false;
    if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, m_hour, m_minute, m_second, m_millisecond))
        return false;
    m_type = DateTimeLocal;
    return true;
}
Exemple #17
0
/*------------------------------------------------------------------------
 *  ascdate  -  print a given date in ascii including hours:mins:secs
 *------------------------------------------------------------------------
 */
int ascdate(long time, char * str)
{
	long	tmp;
	int	year, month, day, hour, minute, second;
	long	days;

	parseTime(time,
			  &month,
			  &day,
			  &year,
			  &hour,
			  &minute,
			  &second);
	sprintf(str, "%3s %d %4d %2d:%02d:%02d", Dat.dt_mnam[month],
		day, year, hour, minute, second);
	return(OK);
}
Exemple #18
0
void
Factory::reg(const std::string & label,
             const std::string & obj_name,
             const buildPtr & build_ptr,
             const paramsPtr & params_ptr,
             const std::string & deprecated_time,
             const std::string & replacement_name,
             const std::string & file,
             int line)
{
  // do nothing if we have already added this exact object before
  auto key = std::make_pair(label, obj_name);
  if (_objects_by_label.find(key) != _objects_by_label.end())
    return;

  /*
   * If _registerable_objects has been set the user has requested that we only register some
   * subset
   * of the objects for a dynamically loaded application. The objects listed in *this*
   * application's
   * registerObjects() method will have already been registered before that member was set.
   *
   * If _registerable_objects is empty, the factory is unrestricted
   */
  if (_registerable_objects.empty() ||
      _registerable_objects.find(obj_name) != _registerable_objects.end())
  {
    if (_name_to_build_pointer.find(obj_name) != _name_to_build_pointer.end())
      mooseError("Object '" + obj_name + "' registered from multiple files: ",
                 file,
                 " and ",
                 _name_to_line.getInfo(obj_name).file());
    _name_to_build_pointer[obj_name] = build_ptr;
    _name_to_params_pointer[obj_name] = params_ptr;
    _objects_by_label.insert(key);
  }
  _name_to_line.addInfo(obj_name, file, line);

  if (!replacement_name.empty())
    _deprecated_name[obj_name] = replacement_name;
  if (!deprecated_time.empty())
    _deprecated_time[obj_name] = parseTime(deprecated_time);

  // TODO: Possibly store and print information about objects that are skipped here?
}
Exemple #19
0
bool DateComponents::parseDateTime(const UChar* src, unsigned length, unsigned start, unsigned& end)
{
    ASSERT(src);
    unsigned index;
    if (!parseDate(src, length, start, index))
        return false;
    if (index >= length)
        return false;
    if (src[index] != 'T')
        return false;
    ++index;
    if (!parseTime(src, length, index, index))
        return false;
    if (!parseTimeZone(src, length, index, end))
        return false;
    if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, m_hour, m_minute, m_second, m_millisecond))
        return false;
    m_type = DateTime;
    return true;
}
bool ubloxNMEA::parsePUBX_00( char chr )
{
  bool ok = true;

  switch (fieldIndex) {
    case 1:
      // The first field is actually a message subtype
      if (chrCount == 0)
        ok = (chr == '0');

      else if (chrCount == 1) {
        switch (chr) {
          #if defined(NMEAGPS_PARSE_PUBX_00) | defined(NMEAGPS_RECOGNIZE_ALL)
            case '0': break;
          #endif
          #if defined(NMEAGPS_PARSE_PUBX_04) | defined(NMEAGPS_RECOGNIZE_ALL)
            case '4': nmeaMessage = (nmea_msg_t) PUBX_04; break;
          #endif
          default : ok = false;
        }

      } else // chrCount > 1
        ok = (chr == ',');
      break;

    #ifdef NMEAGPS_PARSE_PUBX_00
      case  2: return parseTime( chr );
      PARSE_LOC(3);
      case  7: return parseAlt( chr );
      case  8: return parseFix( chr );
      case 11: return parseSpeed( chr ); // kph!
      case 12: return parseHeading( chr );
      case 15: return parseHDOP( chr );
      case 16: return parseVDOP( chr );
      case 18: return parseSatellites( chr );
    #endif
  }

  return ok;

} // parsePUBX_00
void ProgrammeTableParser::contentParsed(const QString &content)
{
    if (m_x == 3) {
        QString s = content.trimmed();

        if (!s.isEmpty()) {
            parseTime(s);
        }
    }
    else if (m_x == 4) {
        if (m_currentProgramme.title.isEmpty()) {
            m_currentProgramme.title = content.trimmed();
        }
    }
    else if (m_x == 5) {
        QString s = content.trimmed();

        if (!s.isEmpty() && m_currentProgramme.description.isEmpty()) {
            m_currentProgramme.description = s;
            m_parseContent = false;
        }
    }
    else if (m_x == 6) {
        QString s = content.trimmed();
        QRegExp regex("(\\d{1,2})\\.(\\d{1,2})");
//        qDebug() << s;

        if (regex.indexIn(s) >= 0) {
            int day = regex.cap(1).toInt();
            int month = regex.cap(2).toInt();

            if (day != m_requestedDate.day() || month != m_requestedDate.month()) {
                m_validResults = false;
            }
        }
    }
}
Exemple #22
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    if(argc < 3)
    {
        qDebug() << "To few arguments!";
        qDebug() << "Usage: cmdtimeout [00h][00m]00[s] command [argumentlist]";
    }

    int msec = parseTime(QString(argv[1]));

    QStringList lst;
    for(int idx=0; idx < argc-3; idx++)
    {
        QString tmpString(argv[idx+3]);
        lst += tmpString;
    }

    QString cmd(argv[2]);
    Application app(cmd,lst,msec);

    return a.exec();
}
Exemple #23
0
void Time::elapse(std::string time_string){
  this->elapsed_time += parseTime(time_string);
}
Exemple #24
0
int parseArgs(int argc, char **argv)
{
	int c;

	sensord_args.isDaemon = (argv[0][strlen (argv[0]) - 1] == 'd');
	if (!sensord_args.isDaemon) {
		fprintf(stderr, "Sensord no longer runs as an commandline"
			" application.\n");
		return -1;
  	}

	while ((c = getopt_long(argc, argv, shortOptions, longOptions, NULL))
	       != EOF) {
		switch(c) {
		case 'i':
			if ((sensord_args.scanTime = parseTime(optarg)) < 0)
				return -1;
			break;
		case 'l':
			if ((sensord_args.logTime = parseTime(optarg)) < 0)
				return -1;
			break;
		case 't':
			if ((sensord_args.rrdTime = parseTime(optarg)) < 0)
				return -1;
			break;
		case 'T':
			sensord_args.rrdNoAverage = 1;
			break;
		case 'f':
			sensord_args.syslogFacility = parseFacility(optarg);
			if (sensord_args.syslogFacility < 0)
				return -1;
			break;
		case 'a':
			sensord_args.doLoad = 1;
			break;
		case 'c':
			sensord_args.cfgFile = optarg;
			break;
		case 'p':
			sensord_args.pidFile = optarg;
			break;
		case 'r':
			sensord_args.rrdFile = optarg;
			break;
		case 'd':
			sensord_args.debug = 1;
			break;
		case 'g':
			sensord_args.doCGI = 1;
			sensord_args.cgiDir = optarg;
			break;
		case 'v':
			printf("sensord version %s\n", LM_VERSION);
			exit(EXIT_SUCCESS);
		case 'h':
			printf("Syntax: %s {options} {chips}\n%s", argv[0],
			       daemonSyntax);
			exit(EXIT_SUCCESS);
		case ':':
		case '?':
			printf("Try `%s --help' for more information.\n",
			       argv[0]);
			return -1;
		default:
			fprintf(stderr,
				"Internal error while parsing options.\n");
			return -1;
		}
	}

	if (sensord_args.doCGI && !sensord_args.rrdFile) {
		fprintf(stderr,
			"Error: Incompatible --rrd-cgi without --rrd-file.\n");
		return -1;
	}

	if (sensord_args.rrdFile && !sensord_args.rrdTime) {
		fprintf(stderr,
			"Error: Incompatible --rrd-file without --rrd-interval.\n");
		return -1;
	}

	if (!sensord_args.logTime && !sensord_args.scanTime &&
	    !sensord_args.rrdFile) {
		fprintf(stderr,
			"Error: No logging, alarm or RRD scanning.\n");
		return -1;
	}

	return 0;
}
Exemple #25
0
Time::Time(std::string time_string){
  this->init_time = parseTime(time_string);
  this->elapsed_time = 0;
}
bool ubloxNMEA::parsePUBX_00( char chr )
{
  bool ok = true;

  switch (fieldIndex) {
    case 1:
      // The first field is actually a message subtype
      if (chrCount == 0)
        ok = (chr == '0');

      else if (chrCount == 1) {
        switch (chr) {
          #if defined(NMEAGPS_PARSE_PUBX_00) | defined(NMEAGPS_RECOGNIZE_ALL)
            case '0': break;
          #endif
          #if defined(NMEAGPS_PARSE_PUBX_04) | defined(NMEAGPS_RECOGNIZE_ALL)
            case '4': nmeaMessage = (nmea_msg_t) PUBX_04; break;
          #endif
          default : ok = false;
        }

      } else // chrCount > 1
        ok = (chr == ',');
      break;

    #ifdef NMEAGPS_PARSE_PUBX_00
      case  2: return parseTime( chr );
      PARSE_LOC(3);
      case  7: return parseAlt( chr );
      case  8: return parseFix( chr );
      case  9: // use Horizontal accuracy for both lat and lon errors
        #if defined(GPS_FIX_LAT_ERR)
          ok = parse_lat_err( chr );
          #if defined(GPS_FIX_LON_ERR)
            // When the lat_err field is finished,
            //   copy it to the lon_err field.
            if (chr == ',') {
              m_fix.valid.lon_err = m_fix.valid.lat_err;
              if (m_fix.valid.lon_err)
                m_fix.lon_err_cm = m_fix.lat_err_cm;
            }
          #endif

        #elif defined(GPS_FIX_LON_ERR)
          ok = parse_lon_err( chr );
        #endif
        break;
      case 10: return parse_alt_err( chr ); // vertical accuracy
      case 11:
        #ifdef GPS_FIX_SPEED
          ok = parseSpeed( chr ); // PUBX,00 provides speed in km/h!

          if ((chr == ',') && m_fix.valid.speed) {
            uint32_t kph    = m_fix.spd.int32_000();
            uint32_t nmiph  = (kph * 1000) / gps_fix::M_PER_NMI;
            m_fix.spd.whole = nmiph / 1000;
            m_fix.spd.frac  = (nmiph - m_fix.spd.whole*1000);
            // Convert to Nautical Miles/Hour
          }
        #endif
        break;
      case 12: return parseHeading( chr );
      case 13: return parseVelocityDown( chr );
      case 15: return parseHDOP( chr );
      case 16: return parseVDOP( chr );
      case 18: return parseSatellites( chr );
    #endif
  }

  return ok;

} // parsePUBX_00
// Find last logged line in gestalt of all matching existing output files
static log_time lastLogTime(char *outputFileName) {
    log_time retval(log_time::EPOCH);
    if (!outputFileName) {
        return retval;
    }

    log_time now(CLOCK_REALTIME);

    std::string directory;
    char *file = strrchr(outputFileName, '/');
    if (!file) {
        directory = ".";
        file = outputFileName;
    } else {
        *file = '\0';
        directory = outputFileName;
        *file = '/';
        ++file;
    }
    size_t len = strlen(file);
    log_time modulo(0, NS_PER_SEC);
    std::unique_ptr<DIR, int(*)(DIR*)>dir(opendir(directory.c_str()), closedir);
    struct dirent *dp;
    while ((dp = readdir(dir.get())) != NULL) {
        if ((dp->d_type != DT_REG)
                || strncmp(dp->d_name, file, len)
                || (dp->d_name[len]
                    && ((dp->d_name[len] != '.')
                        || !isdigit(dp->d_name[len+1])))) {
            continue;
        }

        std::string file_name = directory;
        file_name += "/";
        file_name += dp->d_name;
        std::string file;
        if (!android::base::ReadFileToString(file_name, &file)) {
            continue;
        }

        bool found = false;
        for (const auto& line : android::base::Split(file, "\n")) {
            log_time t(log_time::EPOCH);
            char *ep = parseTime(t, line.c_str());
            if (!ep || (*ep != ' ')) {
                continue;
            }
            // determine the time precision of the logs (eg: msec or usec)
            for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
                if (t.tv_nsec % (mod * 10)) {
                    modulo.tv_nsec = mod;
                    break;
                }
            }
            // We filter any times later than current as we may not have the
            // year stored with each log entry. Also, since it is possible for
            // entries to be recorded out of order (very rare) we select the
            // maximum we find just in case.
            if ((t < now) && (t > retval)) {
                retval = t;
                found = true;
            }
        }
        // We count on the basename file to be the definitive end, so stop here.
        if (!dp->d_name[len] && found) {
            break;
        }
    }
    if (retval == log_time::EPOCH) {
        return retval;
    }
    // tail_time prints matching or higher, round up by the modulo to prevent
    // a replay of the last entry we have just checked.
    retval += modulo;
    return retval;
}
Exemple #28
0
StyleParam::Value StyleParam::parseString(StyleParamKey key, const std::string& _value) {
    switch (key) {
    case StyleParamKey::extrude: {
        return parseExtrudeString(_value);
    }
    case StyleParamKey::text_wrap: {
        int textWrap;
        if (_value == "false") {
            return std::numeric_limits<uint32_t>::max();
        }
        if (_value == "true") {
            return uint32_t(15); // DEFAULT
        }
        if (parseInt(_value, textWrap) > 0 && textWrap > 0) {
             return static_cast<uint32_t>(textWrap);
        }
        return std::numeric_limits<uint32_t>::max();
    }
    case StyleParamKey::text_offset:
    case StyleParamKey::offset: {
        UnitVec<glm::vec2> vec;
        if (!parseVec2(_value, { Unit::pixel }, vec) || std::isnan(vec.value.y)) {
            LOGW("Invalid offset parameter '%s'.", _value.c_str());
        }
        return vec.value;
    }
    case StyleParamKey::size: {
        UnitVec<glm::vec2> vec;
        if (!parseVec2(_value, { Unit::pixel }, vec)) {
            LOGW("Invalid size parameter '%s'.", _value.c_str());
        }
        return vec.value;
    }
    case StyleParamKey::transition_hide_time:
    case StyleParamKey::transition_show_time:
    case StyleParamKey::transition_selected_time:
    case StyleParamKey::text_transition_hide_time:
    case StyleParamKey::text_transition_show_time:
    case StyleParamKey::text_transition_selected_time: {
        float time = 0.0f;
        if (!parseTime(_value, time)) {
            LOGW("Invalid time param '%s'", _value.c_str());
        }
        return time;
    }
    case StyleParamKey::text_font_family:
    case StyleParamKey::text_font_weight:
    case StyleParamKey::text_font_style: {
        std::string normalized = _value;
        std::transform(normalized.begin(), normalized.end(), normalized.begin(), ::tolower);
        return normalized;
    }
    case StyleParamKey::anchor:
    case StyleParamKey::text_anchor: {
        LabelProperty::Anchors anchors;
        for (auto& anchor : splitString(_value, ',')) {
            if (anchors.count == LabelProperty::max_anchors) { break; }

            LabelProperty::Anchor labelAnchor;
            if (LabelProperty::anchor(anchor, labelAnchor)) {
                anchors.anchor[anchors.count++] = labelAnchor;
            } else {
                LOG("Invalid anchor %s", anchor.c_str());
            }
        }
        return anchors;
    }
    case StyleParamKey::placement: {
        LabelProperty::Placement placement = LabelProperty::Placement::vertex;
        if (!LabelProperty::placement(_value, placement)) {
            LOG("Invalid placement parameter, Setting vertex as default.");
        }
        return placement;
    }
    case StyleParamKey::text_align:
    case StyleParamKey::text_source:
    case StyleParamKey::text_transform:
    case StyleParamKey::sprite:
    case StyleParamKey::sprite_default:
    case StyleParamKey::style:
    case StyleParamKey::outline_style:
    case StyleParamKey::repeat_group:
    case StyleParamKey::text_repeat_group:
        return _value;
    case StyleParamKey::text_font_size: {
        float fontSize = 0.f;
        if (!parseFontSize(_value, fontSize)) {
            LOGW("Invalid font-size '%s'.", _value.c_str());
        }
        return fontSize;
    }
    case StyleParamKey::flat:
    case StyleParamKey::interactive:
    case StyleParamKey::text_interactive:
    case StyleParamKey::tile_edges:
    case StyleParamKey::visible:
    case StyleParamKey::text_visible:
    case StyleParamKey::outline_visible:
    case StyleParamKey::collide:
    case StyleParamKey::text_optional:
    case StyleParamKey::text_collide:
        if (_value == "true") { return true; }
        if (_value == "false") { return false; }
        LOGW("Invalid boolean value %s for key %s", _value.c_str(), StyleParam::keyName(key).c_str());
        break;
    case StyleParamKey::text_order:
        LOGW("text:order parameter is ignored.");
        break;
    case StyleParamKey::order:
    case StyleParamKey::outline_order:
    case StyleParamKey::priority:
    case StyleParamKey::text_priority: {
        int num;
        if (parseInt(_value, num) > 0) {
            if (num >= 0) {
                return static_cast<uint32_t>(num);
            }
        }
        LOGW("Invalid '%s' value '%s'", keyName(key).c_str(), _value.c_str());
        break;
    }
    case StyleParamKey::placement_spacing: {
        ValueUnitPair placementSpacing;
        placementSpacing.unit = Unit::pixel;

        int pos = parseValueUnitPair(_value, 0, placementSpacing);
        if (pos < 0) {
            LOGW("Invalid placement spacing value '%s'", _value.c_str());
            placementSpacing.value =  80.0f;
            placementSpacing.unit = Unit::pixel;
        } else {
            if (placementSpacing.unit != Unit::pixel) {
                LOGW("Invalid unit provided for placement spacing");
            }
        }

        return Width(placementSpacing);
    }
    case StyleParamKey::repeat_distance:
    case StyleParamKey::text_repeat_distance: {
        ValueUnitPair repeatDistance;
        repeatDistance.unit = Unit::pixel;

        int pos = parseValueUnitPair(_value, 0, repeatDistance);
        if (pos < 0) {
            LOGW("Invalid repeat distance value '%s'", _value.c_str());
            repeatDistance.value =  256.0f;
            repeatDistance.unit = Unit::pixel;
        } else {
            if (repeatDistance.unit != Unit::pixel) {
                LOGW("Invalid unit provided for repeat distance");
            }
        }

        return Width(repeatDistance);
    }
    case StyleParamKey::width:
    case StyleParamKey::outline_width: {
        ValueUnitPair width;
        width.unit = Unit::meter;

        int pos = parseValueUnitPair(_value, 0, width);
        if (pos < 0) {
            LOGW("Invalid width value '%s'", _value.c_str());
            width.value =  2.0f;
            width.unit = Unit::pixel;
        }

        return Width(width);
    }
    case StyleParamKey::angle: {
        double num;
        if (_value == "auto") {
            return std::nanf("1");
        } else if (parseFloat(_value, num) > 0) {
            return static_cast<float>(num);
        }
        break;
    }
    case StyleParamKey::miter_limit:
    case StyleParamKey::outline_miter_limit:
    case StyleParamKey::placement_min_length_ratio:
    case StyleParamKey::text_font_stroke_width: {
        double num;
        if (parseFloat(_value, num) > 0) {
             return static_cast<float>(num);
        }
        break;
    }

    case StyleParamKey::color:
    case StyleParamKey::outline_color:
    case StyleParamKey::text_font_fill:
    case StyleParamKey::text_font_stroke_color:
        return parseColor(_value);

    case StyleParamKey::cap:
    case StyleParamKey::outline_cap:
        return static_cast<uint32_t>(CapTypeFromString(_value));

    case StyleParamKey::join:
    case StyleParamKey::outline_join:
        return static_cast<uint32_t>(JoinTypeFromString(_value));

    default:
        break;
    }

    return none_type{};
}
Exemple #29
0
StyleParam::Value StyleParam::parseString(StyleParamKey key, const std::string& _value) {
    switch (key) {
    case StyleParamKey::extrude: {
        return parseExtrudeString(_value);
    }
    case StyleParamKey::text_wrap: {
        int textWrap;
        if (_value == "false") {
            return std::numeric_limits<uint32_t>::max();
        }
        if (_value == "true") {
            return 15; // DEFAULT
        }
        if (parseInt(_value, textWrap) > 0 && textWrap > 0) {
             return static_cast<uint32_t>(textWrap);
        }
        return std::numeric_limits<uint32_t>::max();
    }
    case StyleParamKey::text_offset:
    case StyleParamKey::offset: {
        UnitVec<glm::vec2> vec;
        if (!parseVec2(_value, { Unit::pixel }, vec) || std::isnan(vec.value.y)) {
            LOGW("Invalid offset parameter '%s'.", _value.c_str());
        }
        return vec.value;
    }
    case StyleParamKey::size: {
        UnitVec<glm::vec2> vec;
        if (!parseVec2(_value, { Unit::pixel }, vec)) {
            LOGW("Invalid size parameter '%s'.", _value.c_str());
        }
        return vec.value;
    }
    case StyleParamKey::transition_hide_time:
    case StyleParamKey::transition_show_time:
    case StyleParamKey::transition_selected_time:
    case StyleParamKey::text_transition_hide_time:
    case StyleParamKey::text_transition_show_time:
    case StyleParamKey::text_transition_selected_time: {
        float time = 0.0f;
        if (!parseTime(_value, time)) {
            LOGW("Invalid time param '%s'", _value.c_str());
        }
        return time;
    }
    case StyleParamKey::text_font_family:
    case StyleParamKey::text_font_weight:
    case StyleParamKey::text_font_style: {
        std::string normalized = _value;
        std::transform(normalized.begin(), normalized.end(), normalized.begin(), ::tolower);
        return normalized;
    }
    case StyleParamKey::text_align:
    case StyleParamKey::anchor:
    case StyleParamKey::text_anchor:
    case StyleParamKey::text_source:
    case StyleParamKey::text_transform:
    case StyleParamKey::sprite:
    case StyleParamKey::sprite_default:
    case StyleParamKey::style:
    case StyleParamKey::outline_style:
    case StyleParamKey::text_repeat_group:
        return _value;
    case StyleParamKey::text_font_size: {
        float fontSize = 0.f;
        if (!parseFontSize(_value, fontSize)) {
            LOGW("Invalid font-size '%s'.", _value.c_str());
        }
        return fontSize;
    }
    case StyleParamKey::centroid:
    case StyleParamKey::interactive:
    case StyleParamKey::text_interactive:
    case StyleParamKey::tile_edges:
    case StyleParamKey::visible:
    case StyleParamKey::collide:
    case StyleParamKey::text_collide:
        if (_value == "true") { return true; }
        if (_value == "false") { return false; }
        LOGW("Bool value required for capitalized/visible. Using Default.");
        break;
    case StyleParamKey::order:
    case StyleParamKey::outline_order:
    case StyleParamKey::priority:
    case StyleParamKey::text_priority: {
        int num;
        if (parseInt(_value, num) > 0) {
            if (num >= 0) {
                return static_cast<uint32_t>(num);
            }
        }
        LOGW("Invalid '%s' value '%s'", keyName(key).c_str(), _value.c_str());
        break;
    }
    case StyleParamKey::text_repeat_distance: {
        ValueUnitPair repeatDistance;
        repeatDistance.unit = Unit::pixel;

        int pos = parseValueUnitPair(_value, 0, repeatDistance);
        if (pos < 0) {
            LOGW("Invalid repeat distance value '%s'", _value.c_str());
            repeatDistance.value =  256.0f;
            repeatDistance.unit = Unit::pixel;
        } else {
            if (repeatDistance.unit != Unit::pixel) {
                LOGW("Invalid unit provided for repeat distance");
            }
        }

        return Width(repeatDistance);
    }
    case StyleParamKey::width:
    case StyleParamKey::outline_width: {
        ValueUnitPair width;
        width.unit = Unit::meter;

        int pos = parseValueUnitPair(_value, 0, width);
        if (pos < 0) {
            LOGW("Invalid width value '%s'", _value.c_str());
            width.value =  2.0f;
            width.unit = Unit::pixel;
        }

        return Width(width);
    }
    case StyleParamKey::miter_limit:
    case StyleParamKey::outline_miter_limit:
    case StyleParamKey::text_font_stroke_width: {
        double num;
        if (parseFloat(_value, num) > 0) {
             return static_cast<float>(num);
        }
        break;
    }

    case StyleParamKey::color:
    case StyleParamKey::outline_color:
    case StyleParamKey::text_font_fill:
    case StyleParamKey::text_font_stroke_color:
        return parseColor(_value);

    case StyleParamKey::cap:
    case StyleParamKey::outline_cap:
        return static_cast<uint32_t>(CapTypeFromString(_value));

    case StyleParamKey::join:
    case StyleParamKey::outline_join:
        return static_cast<uint32_t>(JoinTypeFromString(_value));

    default:
        break;
    }

    return none_type{};
}
Exemple #30
0
      // this function parses a single header record
   void Rinex3ClockHeader::ParseHeaderRecord(string& line)
      throw(FFStreamError)
   {

      string label(line, 60, 20);

         // RINEX VERSION / TYPE
      if ( label == versionString )
      {

         version  =  asDouble(line.substr(0,9));
         fileType =  strip(line.substr(20, 20));

            // check version
         if ( version <= 0.0 ||
              version > 3.0 )
         {
            FFStreamError e( "This isn't an anticipated version number." +
                              asString(version) );
            GPSTK_THROW(e);
         }

            // check type
         if ( (fileType[0] != 'C') &&
              (fileType[0] != 'c'))
         {
            FFStreamError e( "This isn't a Rinex3 Clock file type." );
            GPSTK_THROW(e);
         }

            // get satellite system
         string system_str = strip(line.substr(40, 20));
         try
         {
            system.fromString(system_str);
         }
         catch (Exception& e)
         {
            FFStreamError ffse( "Input satellite system is unsupported: "
                                 + system_str + e.getText() );
            GPSTK_THROW(ffse);
         }

         valid |= versionValid;

      }
         // PGM / RUN BY / DATE
      else if ( label == runByString )
      {

         fileProgram =  strip(line.substr( 0, 20));
         fileAgency  =  strip(line.substr(20, 20));
         date        =  strip(line.substr(40, 20));
         isPGM = true;

         valid |= runByValid;

      }
         // COMMENT
      else if ( label == commentString )
      {

         string s = strip(line.substr(0, 60));
         commentList.push_back(s);

         valid |= commentValid;

      }
         // SYS / # / OBS TYPES
      else if ( label == numObsString )
      {

         numObsTyp   =  asInt( line.substr(3,3) );

         // TODO: more work needed

         valid |= numObsValid;

      }
         // TIME SYSTEM ID
      else if ( label == timeSystemString )
      {

         timeSystem = line.substr(3,3);
         valid |= timeSystemValid;

      }
         // LEAP SECONDS
      else if ( label == leapSecondsString )
      {

         leapSeconds = asInt(line.substr(0,6));

         valid |= leapSecondsValid;

      }
         // DCBS APPLIED
      else if ( label == sysDCBString )
      {

         valid |= sysDCBsValid;

      }
         // PCVS APPLIED
      else if ( label == sysPCVString )
      {

         valid |= sysPCVsValid;

      }
         // # / TYPES OF DATA
      else if ( label == dataTypesString )
      {

            // number of clock data types
         int nTyp = asInt(line.substr(0,6));
            // allocate memory
         dataTypeList.resize(nTyp);
            // add clock data types
         for( int iTyp = 0; iTyp < nTyp; iTyp++ )
         {
            dataTypeList[iTyp] = strip( line.substr(6*(iTyp+1),6) );
         }

         valid |= dataTypesValid;

      }
         // STATION NAME / NUM
      else if ( label == stationNameString )
      {

         clk0Name = line.substr(0,4);

         valid |= stationNameValid;

      }
         // STATION CLK REF
      else if ( label == calibrationClkString )
      {
         calName = strip( line.substr(0,60) );

         valid |= calibrationClkValid;

      }
         // ANALYSIS CENTER
      else if ( label == acNameString )
      {

         ac       =  line.substr(0, 3);
         acName   =  strip(line.substr(5,55));
         isAC     =  true;

         valid |= acNameValid;

      }
         // # OF CLK REF
      else if ( label == numRefClkString )
      {

            // new reference clock record
         RefClkRecord ref;
            // get the number of reference clocks for this record
         ref.nRef = asInt( line.substr(0,6) );
            // epoch
         if( asInt(line.substr(7,4)) )
         {
            CommonTime T0 = parseTime( line.substr(7,26) );
               // only one time
            if( timeFirst == CommonTime::BEGINNING_OF_TIME )
            {
               timeFirst = T0;
            }
               // left boundary
            ref.refWin[0] = T0 - timeFirst;
               // right boundary
            T0 = parseTime( line.substr(34,26) );
            ref.refWin[1] = T0 - timeFirst;

               // time inconsistency
            if (T0 < timeFirst)
            {
               FFStreamError e( "Wrong epoch of file, expected epoch: " +
                                 timeFirst.asString() + " detected epoch: " +
                                 T0.asString() );
               GPSTK_THROW(e);
            }
         }

            // add the ref clk record to the list
         refClkList.push_back(ref);

         valid |= numRefClkValid;

      }
         /// ANALYSIS CLK REF
      else if ( label == analysisClkRefString )
      {

            // get the previous reference clock record
         std::list<RefClkRecord>::iterator iRef = refClkList.end();
         --iRef;

            // how many ref clk have been stored
         size_t nClks = iRef->clk.size();

            // is there any inconsistency?
         if ( nClks < iRef->nRef )
         {

            RefClk refclk;
               // reference clock info
            refclk.name    =  line.substr(0,4);
            refclk.sigma   =  asDouble( strip( line.substr(40,20) ) );
            refclk.sigma   *= 1e6; // ms^2
               // add into the list
            iRef->clk.push_back(refclk);

         }
         else
         {
            FFStreamError e( string("Number of items found in header ") +
                             "is inconsitent to the entry in header" );
            GPSTK_THROW(e);
         }

         valid |= analysisClkRefValid;

      }
         /// # OF SOLN STA / TRF
      else if ( label == numStationsString )
      {

         numSta   =  asInt(line.substr( 0,  6));
         trfName  =  strip(line.substr(10, 50));

         valid |= numStationsValid;

      }
         /// SOLN STA NAME / NUM
      else if ( label == solnStaNameString )
      {

            // get 4-character station name
         string name = line.substr(0,4);
            // add it into the list
         clkNameList.push_back( name );

            // get integer & decimal part of the coordinates
         int X    =  asInt( strip(line.substr(25,8)) );
         int Xf   =  asInt( strip(line.substr(33,3)) );

         int Y    =  asInt( strip(line.substr(37,8)) );
         int Yf   =  asInt( strip(line.substr(45,3)) );

         int Z    =  asInt( strip(line.substr(49,8)) );
         int Zf   =  asInt( strip(line.substr(57,3)) );

            // geocentric coordinates (be careful to the sign)
         double x = X>0 ? X*1.0+Xf*1e-3 : X*1.0-Xf*1e-3;
         double y = Y>0 ? Y*1.0+Yf*1e-3 : Y*1.0-Yf*1e-3;
         double z = Z>0 ? Z*1.0+Zf*1e-3 : Z*1.0-Zf*1e-3;

            // check the coordinates
         double radius = std::sqrt(x*x+y*y+z*z);
            // add them into the map
         if (radius >= 5000.0e3 && radius < 12000.0e3)
         {
            staCoordList.push_back( Triple(X,Y,Z) );
         }
         else
         {
            staCoordList.push_back( Triple(0.0,0.0,0.0) );
         }

         valid |= solnStaNameValid;

      }
         // # OF SOLN SATS
      else if ( label == numSatsString )
      {

         numSVs = asInt(line.substr(0,6));

         valid |= numSatsValid;

      }
         // PRN LIST
      else if ( label == prnListString )
      {

         string s    =  line.substr(0,60);
         string word =  stripFirstWord(s);

         while ( !word.empty() )
         {
            clkNameList.push_back( word.append(" ") );
            word = stripFirstWord(s);
         }

         valid |= prnListValid;

      }
         // END OF HEADER
      else if ( label == endOfHeader )
      {

         valid |= endValid;

      }
      else
      {

         FFStreamError e("Unidentified label: " + label);
         GPSTK_THROW(e);

      }

      return;

   }   // End of method 'Rinex3ClockHeader::ParseHeaderRecord(string& line)'