Build a Quantity object out of extracted information.
198867
def build_quantity(orig_text, text, item, values, unit, surface, span, uncert):
    """"""
    # Discard irrelevant txt2float extractions, cardinal numbers, codes etc.
    if surface.lower() in ['a', 'an', 'one'] or \
            re.search(r'1st|2nd|3rd|[04-9]th', surface) or \
            re.search(r'\d+[A-Z]+\d+', surface) or \
            re.search(r'\ba second\b', surface, re.IGNORECASE):
        logging.debug(u'\tMeaningless quantity ("%s"), discard', surface)
        return

    # Usually "$3T" does not stand for "dollar tesla"
    elif unit.entity.dimensions and \
            unit.entity.dimensions[0]['base'] == 'currency':
        if len(unit.dimensions) > 1:
            try:
                suffix = re.findall(r'\d(K|M|B|T)\b(.*?)$', surface)[0]
                values = [i * r.SUFFIXES[suffix[0]] for i in values]
                unit = l.UNITS[unit.dimensions[0]['base']][0]
                if suffix[1]:
                    surface = surface[:surface.find(suffix[1])]
                    span = (span[0], span[1] - len(suffix[1]))
                logging.debug(u'\tCorrect for "$3T" pattern')
            except IndexError:
                pass
        else:
            try:
                suffix = re.findall(r'%s(K|M|B|T)\b' % re.escape(surface),
                                    orig_text)[0]
                surface += suffix
                span = (span[0], span[1] + 1)
                values = [i * r.SUFFIXES[suffix] for i in values]
                logging.debug(u'\tCorrect for "$3T" pattern')
            except IndexError:
                pass

    # Usually "1990s" stands for the decade, not the amount of seconds
    elif re.match(r'[1-2]\d\d0s', surface):
        unit = l.NAMES['dimensionless']
        surface = surface[:-1]
        span = (span[0], span[1] - 1)
        logging.debug(u'\tCorrect for decade pattern')

    # Usually "in" stands for the preposition, not inches
    elif unit.dimensions[-1]['base'] == 'inch' and \
            re.search(r' in$', surface) and '/' not in surface:
        if len(unit.dimensions) > 1:
            unit = get_unit_from_dimensions(unit.dimensions[:-1], orig_text)
        else:
            unit = l.NAMES['dimensionless']
        surface = surface[:-3]
        span = (span[0], span[1] - 3)
        logging.debug(u'\tCorrect for "in" pattern')

    elif is_quote_artifact(text, item.span()):
        if len(unit.dimensions) > 1:
            unit = get_unit_from_dimensions(unit.dimensions[:-1], orig_text)
        else:
            unit = l.NAMES['dimensionless']
        surface = surface[:-1]
        span = (span[0], span[1] - 1)
        logging.debug(u'\tCorrect for quotes')

    elif re.search(r' time$', surface) and len(unit.dimensions) > 1 and \
            unit.dimensions[-1]['base'] == 'count':
        unit = get_unit_from_dimensions(unit.dimensions[:-1], orig_text)
        surface = surface[:-5]
        span = (span[0], span[1] - 5)
        logging.debug(u'\tCorrect for "time"')

    objs = []
    for value in values:
        obj = c.Quantity(value=value,
                         unit=unit,
                         surface=surface,
                         span=span,
                         uncertainty=uncert)
        objs.append(obj)

    return objs
563163
def construct(self):
        
        if self.handle is None:
            if self.reference is not None:
                if self.used_indices is None:
                    # create valid
                    self._lazy_init(self.data, label=self.label, reference=self.reference,
                                    weight=self.weight, group=self.group,
                                    init_score=self.init_score, predictor=self._predictor,
                                    silent=self.silent, feature_name=self.feature_name, params=self.params)
                else:
                    # construct subset
                    used_indices = list_to_1d_numpy(self.used_indices, np.int32, name='used_indices')
                    assert used_indices.flags.c_contiguous
                    if self.reference.group is not None:
                        group_info = np.array(self.reference.group).astype(int)
                        _, self.group = np.unique(np.repeat(range_(len(group_info)), repeats=group_info)[self.used_indices],
                                                  return_counts=True)
                    self.handle = ctypes.c_void_p()
                    params_str = param_dict_to_str(self.params)
                    _safe_call(_LIB.LGBM_DatasetGetSubset(
                        self.reference.construct().handle,
                        used_indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
                        ctypes.c_int(used_indices.shape[0]),
                        c_str(params_str),
                        ctypes.byref(self.handle)))
                    self.data = self.reference.data
                    self.get_data()
                    if self.group is not None:
                        self.set_group(self.group)
                    if self.get_label() is None:
                        raise ValueError("Label should not be None.")
            else:
                # create train
                self._lazy_init(self.data, label=self.label,
                                weight=self.weight, group=self.group,
                                init_score=self.init_score, predictor=self._predictor,
                                silent=self.silent, feature_name=self.feature_name,
                                categorical_feature=self.categorical_feature, params=self.params)
            if self.free_raw_data:
                self.data = None
        return self
1329407
def from_description(cls, description, attrs):
        
        hash_key = None
        range_key = None
        index_type = description["Projection"]["ProjectionType"]
        includes = description["Projection"].get("NonKeyAttributes")
        for data in description["KeySchema"]:
            name = data["AttributeName"]
            if name not in attrs:
                continue
            key_type = data["KeyType"]
            if key_type == "HASH":
                hash_key = TableField(name, attrs[name].data_type, key_type)
            elif key_type == "RANGE":
                range_key = TableField(name, attrs[name].data_type, key_type)
        throughput = description["ProvisionedThroughput"]
        return cls(
            description["IndexName"],
            index_type,
            description["IndexStatus"],
            hash_key,
            range_key,
            throughput["ReadCapacityUnits"],
            throughput["WriteCapacityUnits"],
            description.get("IndexSizeBytes", 0),
            includes,
            description,
        )
1182257
def from_blob(cls, s):
        """"""
        atom_str, edge_str = s.split()
        numbers = np.array([int(s) for s in atom_str.split(",")])
        edges = []
        orders = []
        for s in edge_str.split(","):
            i, j, o = (int(w) for w in s.split("_"))
            edges.append((i, j))
            orders.append(o)
        return cls(edges, numbers, np.array(orders))
1013294
def from_info(cls, container, info_obj):
        """"""
        create_fn = cls.from_subdir if 'subdir' in info_obj \
            else cls.from_file_info
        return create_fn(container, info_obj)
298567
def _clean_quantity(self, quantity):
        """"""
        value = quantity.get(QUANTITY.VALUE, '').strip()
        error = quantity.get(QUANTITY.E_VALUE, '').strip()
        unit = quantity.get(QUANTITY.U_VALUE, '').strip()
        kind = quantity.get(QUANTITY.KIND, '')

        if isinstance(kind, list) and not isinstance(kind, string_types):
            kind = [x.strip() for x in kind]
        else:
            kind = kind.strip()

        if not value:
            return False

        if is_number(value):
            value = '%g' % Decimal(value)
        if error:
            error = '%g' % Decimal(error)

        if value:
            quantity[QUANTITY.VALUE] = value
        if error:
            quantity[QUANTITY.E_VALUE] = error
        if unit:
            quantity[QUANTITY.U_VALUE] = unit
        if kind:
            quantity[QUANTITY.KIND] = kind

        return True
651628
def from_dict(raw_data):
        """"""
        try:
            definition = raw_data['definition']
            term_id = raw_data['id']
            image = Image.from_dict(raw_data['image'])
            rank = raw_data['rank']
            term = raw_data['term']
            return Term(definition, term_id, image, rank, term)
        except KeyError:
            raise ValueError('Unexpected term json structure')
304142
def quantity_update(self, num_iid, quantity, session, sku_id=None, outer_id=None, aType=None):
        ''''''
        request = TOPRequest('taobao.item.quantity.update')
        request['num_iid'] = num_iid
        request['quantity'] = quantity
        if sku_id!=None:
            request['sku_id'] = sku_id
        if outer_id!=None:
            request['outer_id'] = outer_id
        if aType!=None:
            request['type'] = aType
        self.create(self.execute(request, session)['item'])
        return self
414936
def gather(params, indices, dtype=tf.float32):
  """"""
  if not is_xla_compiled():
    return tf.gather(params, indices)
  vocab_size = params.get_shape().as_list()[0]
  indices_flat = tf.reshape(indices, [-1])
  out = tf.matmul(tf.one_hot(indices_flat, vocab_size, dtype=dtype), params)
  out = reshape_like(out, tf.expand_dims(indices, -1))
  return out
735838
def create_from(value):
        
        """
        def convert(val):
            if isinstance(val, tuple):
                return tuple(convert(v) for v in val)
            elif isinstance(val, list):
                return [convert(v) for v in val]
            elif isinstance(val, (dict, ElasticDict)):
                return ElasticDict({k: convert(v) for k, v in val.iteritems()})
            else:
                return val

        return convert(value)
421144
def from_data(cls, data):
        
        frequencies = collections.Counter(data)
        return cls.from_frequencies(frequencies, concat=_guess_concat(data))
1297148
def sub(self, quantity):
        
        newvalue = self._value - quantity
        self.set(newvalue.deg)
221149
def from_string(cls, id, format, raw_content, compressed=False,
                    encoded=False):
        """"""
        content = cls(id, format, compressed, encoded)
        content._raw_content = raw_content
        return content
651904
def from_dict(cls, raw_data, **kwargs):
        
        instance = cls()
        instance.populate(raw_data, **kwargs)
        instance.validate(**kwargs)
        return instance
900228
def parse(text, verbose=False):
    """"""
    log_format = ('%(asctime)s --- %(message)s')
    logging.basicConfig(format=log_format)
    root = logging.getLogger()

    if verbose:
        level = root.level
        root.setLevel(logging.DEBUG)
        logging.debug(u'Verbose mode')

    if isinstance(text, str):
        text = text.decode('utf-8')
        logging.debug(u'Converted string to unicode (assume utf-8 encoding)')

    orig_text = text
    logging.debug(u'Original text: "%s"', orig_text)

    text = clean_text(text)
    values = extract_spellout_values(text)
    text, shifts = substitute_values(text, values)

    quantities = []
    for item in r.REG_DIM.finditer(text):

        groups = dict([i for i in item.groupdict().items() if i[1] and
                       i[1].strip()])
        logging.debug(u'Quantity found: %s', groups)

        try:
            uncert, values = get_values(item)
        except ValueError as err:
            logging.debug(u'Could not parse quantity: %s', err)

        unit = get_unit(item, text)
        surface, span = get_surface(shifts, orig_text, item, text)
        objs = build_quantity(orig_text, text, item, values, unit, surface,
                              span, uncert)
        if objs is not None:
            quantities += objs

    if verbose:
        root.level = level

    return quantities
1005983
def add_quantity(self,
                     quantities,
                     value,
                     source,
                     check_for_dupes=True,
                     compare_to_existing=True,
                     **kwargs):
        """"""
        success = True
        for quantity in listify(quantities):
            kwargs.update({QUANTITY.VALUE: value, QUANTITY.SOURCE: source})
            cat_dict = self._add_cat_dict(
                Quantity,
                quantity,
                compare_to_existing=compare_to_existing,
                check_for_dupes=check_for_dupes,
                **kwargs)
            if isinstance(cat_dict, CatDict):
                self._append_additional_tags(quantity, source, cat_dict)
                success = False

        return success
494482
def p_information_constructor(self, p):
        ''
        logger.debug('information = number %s, information unit %s', p[1], p[2])
        p[0] = Information.from_quantity_unit(p[1], p[2])