Resolve ambiguity.

    Distinguish between units that have same names, symbols or abbreviations.
485465
def disambiguate_unit(unit, text):
    
    new_unit = l.UNITS[unit]
    if not new_unit:
        new_unit = l.LOWER_UNITS[unit.lower()]
        if not new_unit:
            raise KeyError('Could not find unit "%s"' % unit)

    if len(new_unit) > 1:
        transformed = TFIDF_MODEL.transform([clean_text(text)])
        scores = CLF.predict_proba(transformed).tolist()[0]
        scores = sorted(zip(scores, TARGET_NAMES), key=lambda x: x[0],
                        reverse=True)
        names = [i.name for i in new_unit]
        scores = [i for i in scores if i[1] in names]
        try:
            final = l.UNITS[scores[0][1]][0]
            logging.debug('\tAmbiguity resolved for "%s" (%s)', unit, scores)
        except IndexError:
            logging.debug('\tAmbiguity not resolved for "%s"', unit)
            final = new_unit[0]
    else:
        final = new_unit[0]

    return final
195171
def resolve(self, other: Type) -> Optional[Type]:
        """"""
        if not isinstance(other, NltkComplexType):
            return None
        if not isinstance(other.second, NltkComplexType):
            return None
        other_first = other.first.resolve(other.second.first)
        if other_first is None:
            return None
        other_first = other_first.resolve(other.second.second)
        if not other_first:
            return None
        other_second = other.second.resolve(ComplexType(other_first, other_first))
        if not other_second:
            return None
        return BinaryOpType(other_first, self._allowed_substitutions, self._signature)
1214169
protected function resolveIfDefines()
    {
        $ifdefinePatt = Regex::make('~@if(?:set|define) \s+ (?<negate>not \s+)? (?<name>{{ ident }}) \s* {{ parens }}? \s* \{~ixS');

        $matches = $this->string->matchAll($ifdefinePatt);

        while ($match = array_pop($matches)) {

            $curlyMatch = new BalancedMatch($this->string, $match[0][1]);

            if (! $curlyMatch->match) {
                continue;
            }

            $negate = $match['negate'][1] != -1;
            $nameDefined = isset($this->vars[$match['name'][0]]);

            $valueDefined = isset($match['parens_content'][0]);
            $valueMatch = false;
            if ($nameDefined && $valueDefined) {
                $testValue = Util::rawValue(trim($match['parens_content'][0]));
                $varValue = Util::rawValue($this->vars[$match['name'][0]]);
                $valueMatch = $varValue == $testValue;
            }

            if (
                ( $valueDefined && !$negate && $valueMatch )
                || ( $valueDefined && $negate && !$valueMatch )
                || ( !$valueDefined && !$negate && $nameDefined )
                || ( !$valueDefined && $negate && !$nameDefined )
            ) {
                $curlyMatch->unWrap();
            }
            else {
                $curlyMatch->replace('');
            }
        }
    }
1102509
def as(unit)
      unit = UOM::Unit.for(unit.to_sym) if String === unit or Symbol === unit
      return self if @unit == unit
      Measurement.new(unit, @unit.as(quantity, unit))
    end
619706
def convert(values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation):
    

    source_dimension = get_dimension_by_unit_measure_or_abbreviation(source_measure_or_unit_abbreviation)
    target_dimension = get_dimension_by_unit_measure_or_abbreviation(target_measure_or_unit_abbreviation)

    if source_dimension == target_dimension:
        source=JSONObject({})
        target=JSONObject({})
        source.unit_abbreviation, source.factor = _parse_unit(source_measure_or_unit_abbreviation)
        target.unit_abbreviation, target.factor = _parse_unit(target_measure_or_unit_abbreviation)

        source.unit_data = get_unit_by_abbreviation(source.unit_abbreviation)
        target.unit_data = get_unit_by_abbreviation(target.unit_abbreviation)

        source.conv_factor = JSONObject({'lf': source.unit_data.lf, 'cf': source.unit_data.cf})
        target.conv_factor = JSONObject({'lf': target.unit_data.lf, 'cf': target.unit_data.cf})

        if isinstance(values, float):
            # If values is a float => returns a float
            return (source.conv_factor.lf / target.conv_factor.lf * (source.factor * values)
                    + (source.conv_factor.cf - target.conv_factor.cf)
                    / target.conv_factor.lf) / target.factor
        elif isinstance(values, list):
            # If values is a list of floats => returns a list of floats
            return [(source.conv_factor.lf / target.conv_factor.lf * (source.factor * value)
                    + (source.conv_factor.cf - target.conv_factor.cf)
                    / target.conv_factor.lf) / target.factor for value in values]
    else:
        raise HydraError("Unit conversion: dimensions are not consistent.")
172117
private Symbol resolveType(String name, SearchSuperTypes searchSuperTypes) {
    Symbol type = null;
    if (searchSuperTypes == SearchSuperTypes.YES) {
      type = getSuperType(enclosingClass, name);
    }
    if (enclosingClass.getSimpleName().contentEquals(name)) {
      type = enclosingClass;
    }
    if (type == null) {
      type = getLexicallyEnclosing(enclosingClass, name);
    }
    if (type == null) {
      type = attribIdent(name);
    }
    checkGuardedBy(
        !(type instanceof Symbol.PackageSymbol),
        "All we could find for '%s' was a package symbol.",
        name);
    return type;
  }
79650
def unit_key_from_name(name):
  """"""
  result = name

  for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS):
    result = result.replace(old, new)

  # Collapse redundant underscores and convert to uppercase.
  result = re.sub(r'_+', '_', result.upper())

  return result
236549
def could_be(self, other):
        """"""
        # TODO: Some suffix and title differences should be allowed
        if type(other) is not type(self):
            return NotImplemented
        if self == other:
            return True
        for attr in ['title', 'firstname', 'middlename', 'nickname', 'prefix', 'lastname', 'suffix']:
            if attr not in self or attr not in other:
                continue
            puncmap = dict((ord(char), None) for char in string.punctuation)
            s = self[attr].lower().translate(puncmap)
            o = other[attr].lower().translate(puncmap)
            if s == o:
                continue
            if attr in {'firstname', 'middlename', 'lastname'}:
                if (({len(comp) for comp in s.split()} == {1} and [el[0] for el in o.split()] == s.split()) or
                        ({len(comp) for comp in o.split()} == {1} and [el[0] for el in s.split()] == o.split())):
                    continue
            return False
        return True
104023
def is_unit(q):
    '''
    
    '''
    if isinstance(q, six.string_types):
        try: return hasattr(units, q)
        except: return False
    else:
        cls = type(q)
        return cls.__module__.startswith('pint.') and cls.__name__ == 'Unit'
96849
function parseUnits (header) {
  if(isObject(header)) return header
  var m = /^(.+)\s+\(([^\)]+)\)$/.exec(header.trim())
  if(!m) return {name: header.trim()}
  return {name: m[1].trim(), units: m[2]}
}
458284
def like_units(a, b):
    '''
    
    '''
    a = quant(0.0, a) if is_unit(a) else a if is_quantity(a) else quant(a, units.dimensionless)
    b = quant(0.0, b) if is_unit(b) else b if is_quantity(b) else quant(b, units.dimensionless)
    if a == b: return True
    try:
        c = a.to(b.u)
        return True
    except:
        return False
820307
def register_or_check(klass, finish, mean, between, refresh_presision, configuration):
		""""""
		m, created = klass.objects.get_or_create(finish=finish, configuration=configuration)
		if created:
			m.mean=mean
			m.between=between
			m.refresh_presision=refresh_presision
			m.save()
		else:
			diff = abs(float(m.mean) - mean)
			if not(diff < 0.006 and m.between == between and m.refresh_presision == refresh_presision):
				raise InvalidMeasurementError("There are diferents values for the same measurement.")
		return m
675392
function normalizeUnit(unit) {
    unit = toStr(unit);

    if (unitShorthandMap[unit]) return unitShorthandMap[unit];

    return unit.toLowerCase().replace(regEndS, '');
}
373141
def _check_unit(new_unit, old_unit):
    

    try:

        new_unit.physical_type

    except AttributeError:

        raise UnitMismatch("The provided unit (%s) has no physical type. Was expecting a unit for %s"
                           % (new_unit, old_unit.physical_type))

    if new_unit.physical_type != old_unit.physical_type:

        raise UnitMismatch("Physical type mismatch: you provided a unit for %s instead of a unit for %s"
                           % (new_unit.physical_type, old_unit.physical_type))
1307816
def resolve(self, other: Type) -> Type:
        """"""
        if not isinstance(other, NltkComplexType):
            return None
        resolved_second = NUMBER_TYPE.resolve(other.second)
        if not resolved_second:
            return None
        return CountType(other.first)
164041
def _symbol_in(self, symbol, name):
        """"""
        lsymbol = symbol.lower()
        lname = name.lower()
        return lsymbol == lname[:len(symbol)] or "_" + lsymbol in lname
1282733
def program_unit_name(line:str) -> str:
   """"""
   match = RE_PGM_UNIT_START.match(line)
   assert match != None
   return match.group(2)