Parse a string with units and try to make a bitmath object out of
it.

String inputs may include whitespace characters between the value and
the unit.
767037
def parse_string(s):
    
    # Strings only please
    if not isinstance(s, (str, unicode)):
        raise ValueError("parse_string only accepts string inputs but a %s was given" %
                         type(s))

    # get the index of the first alphabetic character
    try:
        index = list([i.isalpha() for i in s]).index(True)
    except ValueError:
        # If there's no alphabetic characters we won't be able to .index(True)
        raise ValueError("No unit detected, can not parse string '%s' into a bitmath object" % s)

    # split the string into the value and the unit
    val, unit = s[:index], s[index:]

    # see if the unit exists as a type in our namespace

    if unit == "b":
        unit_class = Bit
    elif unit == "B":
        unit_class = Byte
    else:
        if not (hasattr(sys.modules[__name__], unit) and isinstance(getattr(sys.modules[__name__], unit), type)):
            raise ValueError("The unit %s is not a valid bitmath unit" % unit)
        unit_class = globals()[unit]

    try:
        val = float(val)
    except ValueError:
        raise
    try:
        return unit_class(val)
    except:  # pragma: no cover
        raise ValueError("Can't parse string %s into a bitmath object" % s)
764092
def parse_utuple(s,urx,length=2):
    ''''''
    if type(urx) != str:
        urx=urx.pattern;
    if length is not None and length < 1:
        raise ValueError("invalid length: {}".format(length));
    if length == 1:
        rx = r"^ *\( *{urx} *,? *\) *$".format(urx=urx);
    elif length is None:
        rx = r"^ *\( *(?:{urx} *, *)*{urx} *,? *\) *$".format(urx=urx);
    else:
        rx = r"^ *\( *(?:{urx} *, *){{{rep1}}}{urx} *,? *\) *$".format(
            rep1=length-1,
            urx=urx);
    return re.match(rx,s);
1196117
function parseNum (string) {
	let unit;
	const num = parseFloat(string.replace(/(\D+)$/, (s) => {
		unit = s;
		return "";
	}));
	if (!isNaN(num)) {
		return {
			num: num,
			unit: unit || "",
		};
	}
}
681696
def from_string(cls, string):
        
        cls.TYPE.setParseAction(cls.make)
        try:
            return cls.TYPE.parseString(string, parseAll=True)[0]
        except ParseException:
            log.error("Failed to parse '{0}'".format(string))
            raise
133017
def parse_value(self, stream):
        
        if self.has_sequence(stream):
            value = self.parse_sequence(stream)
        elif self.has_set(stream):
            value = self.parse_set(stream)
        else:
            value = self.parse_simple_value(stream)

        self.skip_whitespace_or_comment(stream)

        if self.has_units(stream):
            return Units(value, self.parse_units(stream))

        return value
1268416
def _string_parser(strip_whitespace):
    """"""
    def _parse_string_value(element_text, _state):
        if element_text is None:
            value = ''
        elif strip_whitespace:
            value = element_text.strip()
        else:
            value = element_text

        return value

    return _parse_string_value
868727
def from_string(cls, string):
    """"""
    # Note: There is some ambiguity as to whether the string passed is intended
    # to become a unit looked up by name or suffix, or a Dimension descriptor.
    if string in units.UNITS_BY_ALL:
      return cls(description=string, unit=units.Unit(string))
    else:
      return cls(description=string)
638110
def _parse_unit(unit, placement_str):
    
    if not unit:
        return None
    try:
        return int(unit)
    except (TypeError, ValueError):
        msg = 'unit in placement {} must be digit'.format(placement_str)
        raise ValueError(msg.encode('utf-8'))
73940
def from_string(cls, value):
        """"""
        match = cls.pattern.search(value)
        if match is None:
            raise ValueError('"%s" is not a valid media type' % value)
        try:
            return cls(match.group('mime_type'), float(match.group('weight') or 1))
        except ValueError:
            return cls(value)
1310747
public static long parseSize(String s) {
        Matcher m = p_mem.matcher(s);
        if (m.find()) {
            long i = Long.parseLong(m.group(1));
            char multiplier = 'B';
            if (m.group(2) != null && m.group(2).length() == 1) {
                multiplier = m.group(2).charAt(0);
            }
            if (multiplier == 'B') {
                return (long) i;
            }
            if (multiplier == 'K') {
                return (long) i * 1024l;
            }
            if (multiplier == 'M') {
                return (long) i * 1024l * 1024l;
            }
            if (multiplier == 'G') {
                return (long) i * 1024l * 1024l * 1024l;
            }
        }
        return -1;
    }
151987
def parse_string_value_from_substring(substring) -> str:
    '''
    
    '''
    try:
        value = substring.split(':')[1]
        return str(value)
    except (ValueError, IndexError, TypeError, AttributeError):
        log.exception('Unexpected arg to parse_string_value_from_substring:')
        raise ParseError(
            'Unexpected arg to parse_string_value_from_substring: {}'.format(
                substring))
1117528
def sizes_from_string(string = "0x0")
      string = "0x0" if string.nil? || string.empty?

      raise ArgumentError unless string =~ /(\d*x\d*)/

      width, height = string.scan(/(\d*)x(\d*)/)[0].map(&:to_i)

      width = 0 if width.nil?
      height = 0 if height.nil?
      {
        width: width,
        height: height
      }
    end
1311459
def from_string(self, value):
        """"""
        # Remove optional []
        if value.startswith('[') and value.endswith(']'):
            text = value[1:-1].strip()
        else:
            text = value.strip()
        # Result is a list
        result = []
        # If value starts with '(' assume a list of pairs
        if text.startswith('('):
            tokens = text.split(',')
            if len(tokens) % 2 != 0:
                raise ValueError('not a valid list of pairs')
            pos = 0
            while (pos < len(tokens)):
                val1 = float(tokens[pos].strip()[1:].strip())
                val2 = float(tokens[pos + 1].strip()[:-1])
                result.append((val1, val2))
                pos += 2
        else:
            for val in text.split(','):
                result.append(float(val))
        # Ensure that the result contains at least two elements
        if len(result) < 2:
            raise ValueError('invalid number of elements in list: ' + str(len(result)))
        return result
625818
def from_string(cls, hash, **context):
        """"""
        salt, checksum = parse_mc2(hash, cls.ident, handler=cls)

        return cls(salt=salt, checksum=checksum)
163676
def __try_parse_number(self, string):
        """"""
        try:
            return int(string)
        except ValueError:
            try:
                return float(string)
            except ValueError:
                return False
1108551
def parse(cls, string):
        
        match = re.match(r'^(?P<name>[A-Za-z0-9\.\-_]+)\s+' +
                         '(?P<value>[0-9\.]+)\s+' +
                         '(?P<timestamp>[0-9\.]+)(\n?)$',
                         string)
        try:
            groups = match.groupdict()
            # TODO: get precision from value string
            return Metric(groups['name'],
                          groups['value'],
                          float(groups['timestamp']))
        except:
            raise DiamondException(
                "Metric could not be parsed from string: %s." % string)
1223240
function fromString(string) {
    var parsed = string.match(matrixRegex);
    if (parsed === null || parsed.length < 7) throw new Error('\'' + string + '\' is not a matrix');
    return {
        a: parseFloat(parsed[1]),
        b: parseFloat(parsed[2]),
        c: parseFloat(parsed[3]),
        d: parseFloat(parsed[4]),
        e: parseFloat(parsed[5]),
        f: parseFloat(parsed[6])
    };
}