Convert a string of the form DD or DD|MM or DD|MM|SS to decimal degrees
483651
def depipe(s):
    """"""
    n = 0
    for i in reversed(s.split('|')):
        n = n / 60.0 + float(i)
    return n
846404
def dmsStrToDeg(dec):
    """"""
    sign_deg, min, sec = dec.split(':')
    sign = sign_deg[0:1]
    if sign not in ('+', '-'):
        sign = '+'
        deg = sign_deg
    else:
        deg = sign_deg[1:]
    dec_deg = decTimeToDeg(sign, int(deg), int(min), float(sec))
    return dec_deg
597457
function convertUnit(str) {
  const reg = /\.\d*/;
  const result = reg.exec(str);
  if (result && result[0]) {
    return {
      precision: result[0].length - 1,
      unit: str.substring(result[0].length + 1),
    };
  }
  return {
    unit: str,
  };
}
322666
def parse(cls, s):
        
        try:
            numbers = map(int, s.split("-"))
        except (ValueError, AttributeError):
            raise ValueError("Date string must be in format YYYY-MM-DD")
        else:
            numbers = list(numbers)
            if len(numbers) == 3:
                return cls(*numbers)
            raise ValueError("Date string must be in format YYYY-MM-DD")
653833
def to_ts(s):
        

        # Strip TZ portion if present
        m = Nginx.DATE_FMT.match(s)
        if m:
            s = m.group(1)
            delta = timedelta(seconds=int(m.group(3)) * (-1 if m.group(2) == '-' else 1)) # Offset from GMT
        else:
            delta = timedelta(seconds=0)
        dt = datetime.strptime(s, "%d/%b/%Y:%H:%M:%S")
        dt += delta
        return dt.strftime('%Y-%m-%dT%H:%M:%SZ')
673333
def dm_to_sd(dm):
    '''
    
    '''
    # '12319.943281'
    if not dm or dm == '0':
        return 0.
    d, m = re.match(r'^(\d+)(\d\d\.\d+)$', dm).groups()
    return float(d) + float(m) / 60
822222
private String formatNumStr(int bits, String str) {

        String ret;
        String[] inputStr = str.split("\\.");
        if (str.trim().equals("")) {
            ret = String.format("%" + bits + "s", "");
        } else if (str.length() <= bits) {
            ret = String.format("%1$" + bits + "s", str);
        } else if (inputStr[0].length() > bits) {
            ret = String.format("%" + bits + "s", str);
        } else {
            int decimalLength = bits - inputStr[0].length() - 1;
            decimalLength = decimalLength < 0 ? 0 : decimalLength;
            ret = org.agmip.common.Functions.round(str, decimalLength);
        }

        return ret;
    }
983585
def date_from_string(string, format_string=None):
    """"""

    if isinstance(format_string, str):
        return datetime.datetime.strptime(string, format_string).date()

    elif format_string is None:
        format_string = [
            "%Y-%m-%d",
            "%m-%d-%Y",
            "%m/%d/%Y",
            "%d/%m/%Y",
        ]

    for format in format_string:
        try:
            return datetime.datetime.strptime(string, format).date()
        except ValueError:
            continue

    raise ValueError("Could not produce date from string: {}".format(string))
1317976
def trim_decimals(s, precision=-3):
        
        encoded = s.encode('ascii', 'ignore')
        str_val = ""
        if six.PY3:
            str_val = str(encoded, encoding='ascii', errors='ignore')[:precision]
        else:
            # If precision is 0, this must be handled seperately
            if precision == 0:
                str_val = str(encoded)
            else:
                str_val = str(encoded)[:precision]
        if len(str_val) > 0:
            return float(str_val)
        else:
            return 0
974907
function toTechTimeFormat(
  dt,
  {
    suppressSeconds = false,
    suppressMilliseconds = false,
    includeOffset,
    includeZone = false,
    spaceZone = false
  }
) {
  let fmt = "HH:mm";

  if (!suppressSeconds || dt.second !== 0 || dt.millisecond !== 0) {
    fmt += ":ss";
    if (!suppressMilliseconds || dt.millisecond !== 0) {
      fmt += ".SSS";
    }
  }

  if ((includeZone || includeOffset) && spaceZone) {
    fmt += " ";
  }

  if (includeZone) {
    fmt += "z";
  } else if (includeOffset) {
    fmt += "ZZ";
  }

  return toTechFormat(dt, fmt);
}
806723
def string2dt(self, s, lower_bound=None):
        """"""
        original_s = s

        result = {}
        dt = None

        # if s is completely empty, return start or end,
        # depending on what parameter is evaluated
        if s == '':
            return self.end if lower_bound else self.start

        # first try to match the defined regexes
        for idx in self.dtRegexes:
            regex = self.dtRegexes[idx]
            mo = regex.search(s)
            # if match was found, cut it out of original string and
            # store in result
            if mo:
                result[idx] = mo
                s = s[:mo.start(0)] + s[mo.end(0):]

        # handle constants
        if 'constant' in result:
            constant = result['constant'].group(0).strip()
            if constant == 'end':
                dt = self.end
            elif constant == 'start':
                dt = self.start
            elif constant == 'today':
                dt = datetime.now().replace(hour=0, minute=0, second=0,
                                            microsecond=0)
            elif constant == 'yesterday':
                dt = datetime.now().replace(hour=0, minute=0, second=0,
                                            microsecond=0) - timedelta(days=1)
            elif constant == 'now':
                dt = datetime.now()

        elif 'weekday' in result:
                weekday = result['weekday'].group(0).strip()
                # assume most-recently occured weekday in logfile
                most_recent_date = self.end.replace(hour=0, minute=0, second=0,
                                                    microsecond=0)
                offset = (most_recent_date.weekday() -
                          self.weekdays.index(weekday)) % 7
                dt = most_recent_date - timedelta(days=offset)

        # if anything remains unmatched, try parsing it with dateutil's parser
        if s.strip() != '':
            try:
                if dt:
                    dt = default_tzinfo(parser.parse(s, default=dt), tzutc)
                else:
                    # check if it's only time, then use the start dt as
                    # default, else just use the current year
                    if re.match('(?P<hour>\d{1,2}):(?P<minute>\d{2,2})'
                                '(?::(?P<second>\d{2,2})'
                                '(?:.(?P<microsecond>\d{3,3}))?)?'
                                '(?P<timezone>[0-9Z:\+\-]+)?$', s):
                        default = self.end if lower_bound else self.start
                    else:
                        default = datetime(self.end.year, 1, 1, 0, 0, 0)
                    default = default.replace(second=0, microsecond=0)

                    dt = parser.parse(s, default=default)

            except ValueError:
                raise ValueError("Error in DateTimeBoundaries: "
                                 "can't parse datetime from %s" % s)

        if not dt:
            dt = lower_bound or self.end

        # if no timezone specified, use the one from the logfile
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=self.start.tzinfo)

        # time is applied separately (not through the parser) so that string
        # containing only time don't use today as default date
        # (parser behavior)
        # if 'time' in result:
        #     dct = dict((k, int(v))
        #                for k,v in six.iteritems(result['time'].groupdict(0)))
        #     dct['microsecond'] *= 1000
        #     dt = dt.replace(**dct)

        # apply offset
        if 'offset' in result:

            # separate in operator, value, unit
            dct = result['offset'].groupdict()

            mult = 1
            if dct['unit'] in ['s', 'sec', 'secs']:
                dct['unit'] = 'seconds'
            elif dct['unit'] in ['m', 'min', 'mins']:
                dct['unit'] = 'minutes'
            elif dct['unit'] in ['h', 'hour', 'hours']:
                dct['unit'] = 'hours'
            elif dct['unit'] in ['d', 'day', 'days']:
                dct['unit'] = 'days'
            elif dct['unit'] in ['w', 'week', 'weeks']:
                dct['unit'] = 'days'
                mult = 7
            elif dct['unit'] in ['mo', 'month', 'months']:
                dct['unit'] = 'days'
                mult = 30.43
            elif dct['unit'] in ['y', 'year', 'years']:
                dct['unit'] = 'days'
                mult = 365.24

            if dct['operator'] == '-':
                mult *= -1

            dt = dt + eval('timedelta(%s=%i)' % (dct['unit'],
                                                 mult * int(dct['value'])))

        # if parsed datetime is out of bounds and no year specified,
        # try to adjust year
        year_present = re.search('\d{4,4}', original_s)

        if not year_present and 'constant' not in result:
            if (dt < self.start and
                    dt.replace(year=dt.year + 1) >= self.start and
                    dt.replace(year=dt.year + 1) <= self.end):
                dt = dt.replace(year=dt.year + 1)
            elif (dt > self.end and
                    dt.replace(year=dt.year - 1) >= self.start and
                    dt.replace(year=dt.year - 1) <= self.end):
                dt = dt.replace(year=dt.year - 1)

        return dt
1360870
def todegdec(origin):
    

    # if the input is already a float (or can be converted to float)
    try:
        return float(origin)
    except ValueError:
        pass

    # DMS format
    m = dms_re.search(origin)
    if m:
        degrees = int(m.group('degrees'))
        minutes = float(m.group('minutes'))
        seconds = float(m.group('seconds'))

        return degrees + minutes / 60 + seconds / 3600

    # Degree + Minutes format
    m = mindec_re.search(origin)
    if m:
        degrees = int(m.group('degrees'))
        minutes = float(m.group('minutes'))

        return degrees + minutes / 60
291549
function minutesToOffsetString(minutes) {
  var t = String(Math.abs(minutes / 60)).split('.');
  var H = pad(t[0]);
  var m = t[1] ? parseInt(t[1], 10) * 0.6 : 0;
  var sign = minutes < 0 ? '-' : '+';

  return '' + sign + H + ':' + pad(m);
}
691431
def to_decimal(number, strip='- '):
    '''
    
    '''
    if isinstance(number, six.integer_types):
        return str(number)

    number = str(number)
    number = re.sub(r'[%s]' % re.escape(strip), '', number)

    # hexadecimal
    if number.startswith('0x'):
        return to_decimal(int(number[2:], 16))

    # octal
    elif number.startswith('o'):
        return to_decimal(int(number[1:], 8))

    # binary
    elif number.startswith('b'):
        return to_decimal(int(number[1:], 2))

    else:
        return str(int(number))
107860
def decimal_format(value, TWOPLACES=Decimal(100) ** -2):
    ''
    if not isinstance(value, Decimal):
        value = Decimal(str(value))
    return value.quantize(TWOPLACES)
643641
def ddtodms(self, dd):
        """"""
        negative = dd < 0
        dd = abs(dd)
        minutes,seconds = divmod(dd*3600,60)
        degrees,minutes = divmod(minutes,60)
        if negative:
            if degrees > 0:
                degrees = -degrees
            elif minutes > 0:
                minutes = -minutes
            else:
                seconds = -seconds
        return (degrees,minutes,seconds)
939372
def strptime(string, timezone=0):
    """"""
    year = int(string[0:4])
    month = int(string[5:7])
    day = int(string[8:10])
    hour = int(string[-5:-3])
    minute = int(string[-2:])
    ts = datetime.datetime(year, month, day) + \
        datetime.timedelta(hours=hour, minutes=minute) - \
        datetime.timedelta(hours=timezone)
    return ts