Check for uniqueness of MultiIndex level names in all given
    variables.

    Not public API. Used for checking consistency of DataArray and Dataset
    objects.
14385
def assert_unique_multiindex_level_names(variables):
    
    level_names = defaultdict(list)
    all_level_names = set()
    for var_name, var in variables.items():
        if isinstance(var._data, PandasIndexAdapter):
            idx_level_names = var.to_index_variable().level_names
            if idx_level_names is not None:
                for n in idx_level_names:
                    level_names[n].append('%r (%s)' % (n, var_name))
            if idx_level_names:
                all_level_names.update(idx_level_names)

    for k, v in level_names.items():
        if k in variables:
            v.append('(%s)' % k)

    duplicate_names = [v for v in level_names.values() if len(v) > 1]
    if duplicate_names:
        conflict_str = '\n'.join([', '.join(v) for v in duplicate_names])
        raise ValueError('conflicting MultiIndex level name(s):\n%s'
                         % conflict_str)
    # Check confliction between level names and dimensions GH:2299
    for k, v in variables.items():
        for d in v.dims:
            if d in all_level_names:
                raise ValueError('conflicting level / dimension names. {} '
                                 'already exists as a level name.'.format(d))
248832
def _check_valid_udunits(self, ds, variable_name):
        '''
        
        '''
        variable = ds.variables[variable_name]

        units = getattr(variable, 'units', None)
        standard_name = getattr(variable, 'standard_name', None)
        standard_name, standard_name_modifier = self._split_standard_name(standard_name)
        std_name_units_dimensionless = cfutil.is_dimensionless_standard_name(self._std_names._root,
                                                               standard_name)

        # If the variable is supposed to be dimensionless, it automatically passes
        should_be_dimensionless = (variable.dtype.char == 'S' or
                                   std_name_units_dimensionless)

        valid_udunits = TestCtx(BaseCheck.HIGH, self.section_titles["3.1"])
        are_udunits = (units is not None and util.units_known(units))
        valid_udunits.assert_true(should_be_dimensionless or are_udunits,
                                  'units for {}, "{}" are not recognized by UDUNITS'.format(variable_name, units))
        return valid_udunits.to_result()
336606
def any_unique(keys, axis=semantics.axis_default):
    """"""
    index = as_index(keys, axis)
    return np.any(index.count == 1)
697333
def _construct_dataarray(self, name) -> 'DataArray':
        
        from .dataarray import DataArray

        try:
            variable = self._variables[name]
        except KeyError:
            _, name, variable = _get_virtual_variable(
                self._variables, name, self._level_coords, self.dims)

        needed_dims = set(variable.dims)

        coords = OrderedDict()  # type: OrderedDict[Any, Variable]
        for k in self.coords:
            if set(self.variables[k].dims) <= needed_dims:
                coords[k] = self.variables[k]

        if self._indexes is None:
            indexes = None
        else:
            indexes = OrderedDict((k, v) for k, v in self._indexes.items()
                                  if k in coords)

        return DataArray(variable, coords, name=name, indexes=indexes,
                         fastpath=True)
730063
def _get_unique_index(self, dropna=False):
        
        if self.is_unique and not dropna:
            return self

        values = self.values

        if not self.is_unique:
            values = self.unique()

        if dropna:
            try:
                if self.hasnans:
                    values = values[~isna(values)]
            except NotImplementedError:
                pass

        return self._shallow_copy(values)
963811
def get_unique_variable(name):
  
  candidates = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, name)
  if not candidates:
    raise ValueError('Couldnt find variable %s' % name)

  for candidate in candidates:
    if candidate.op.name == name:
      return candidate
  raise ValueError('Variable %s does not uniquely identify a variable', name)
1354528
def check_valid_varname(varname,
                        custom_units,
                        custom_structs,
                        constants,
                        pos,
                        error_prefix="Variable name invalid.",
                        exc=None):
    
    exc = VariableDeclarationException if exc is None else exc

    valid_varname, msg = is_varname_valid(varname, custom_units, custom_structs, constants)
    if not valid_varname:
        raise exc(error_prefix + msg, pos)

    return True
47500
public boolean isUnique(String columnName) {
        if (columnName == null) {
            return false;
        }

        for (IndexHolder ih : indexHoldersByName.values()) {
            if (ih.isUnique() && ih.getSize() == 1) {
                if (ih.getIndexes().iterator().next().getColumnName().equalsIgnoreCase(columnName)) {
                    return true;
                }
            }
        }

        return false;
    }
751240
def find_unique_values(input_file, property_name):
    '''
    
    '''

    with open(input_file) as f:
        feature_collection = geojson.load(f)

    features = feature_collection['features']
    values = np.array([feat['properties'].get(property_name)
                       for feat in features])
    return np.unique(values)
313449
def _check_var(var, dtype, ndmin, name, shape=None, shape2=None):
    """
    if var is None:
        raise ValueError
    var = np.array(var, dtype=dtype, copy=True, ndmin=ndmin)
    if shape:
        _check_shape(var, name, shape, shape2)
    return var
735052
def _check_samples_nodups(fnames):
    
    counts = defaultdict(int)
    for f in fnames:
        for s in get_samples(f):
            counts[s] += 1
    duplicates = [s for s, c in counts.items() if c > 1]
    if duplicates:
        raise ValueError("Duplicate samples found in inputs %s: %s" % (duplicates, fnames))
81534
def _variable_components(self, variable):
        """"""
        var_list = pd.Series(self.data.variable.unique())
        return var_list[pattern_match(var_list, '{}|*'.format(variable), 0)]
188414
def _check_names_match(data_names, data_shapes, name, throw):
    """"""
    actual = [x[0] for x in data_shapes]
    if sorted(data_names) != sorted(actual):
        msg = "Data provided by %s_shapes don't match names specified by %s_names (%s vs. %s)"%(
            name, name, str(data_shapes), str(data_names))
        if throw:
            raise ValueError(msg)
        else:
            warnings.warn(msg)
395483
def _all_indexes_same(indexes):
    
    first = indexes[0]
    for index in indexes[1:]:
        if not first.equals(index):
            return False
    return True
303922
def rand_indices(x, rand_attr):
    
    loop = True
    indices = range(len(x[0]))

    while loop:
        loop = False
        # randomly selected features without replacement
        rand_list = random.sample(indices, rand_attr)
        for i in rand_list:
            if len(np.unique(x[:, i])) == 1:
                loop = True
                indices.remove(i)
                if len(indices) == rand_attr - 1:
                    return -1  # all features in dataset have one distinct value
                break
    return rand_list
670775
def is_unique(keys, *, scope=None, comparison_operators=None, present_optional=False,
                message=None):
    
    def check(pname, validator):
      """Checks that a value is unique in its column, with an optional scope."""
      # pylint: disable=too-many-branches
      model = validator.model
      data_access = validator.data_access
      pkname = model.primary_key_name
      pkey = model.primary_key

      if isinstance(keys, str):
        key = getattr(model, keys)

        if present_optional and key is None:
          return True

        if comparison_operators:
          if isinstance(comparison_operators, str):
            op = comparison_operators
          else:
            op = comparison_operators[0]
        else:
          op = " = "

        constraints = [(keys, key, op)]
      else:
        if comparison_operators:
          ops = comparison_operators
        else:
          ops = [" = "] * len(keys)

        constraints = list(zip(keys, [getattr(model, key) for key in keys], ops))

      if scope:
        if comparison_operators:
          ops = comparison_operators[len(constraints):]
        else:
          ops = [" = "] * len(scope)

        constraints.extend(zip(scope, [getattr(model, col) for col in scope], ops))

      dupe = data_access.find(model.table_name, constraints, columns=pkname)

      if dupe is None:
        return True
      if isinstance(pkname, str):
        return dupe[0] == pkey
      else:
        return tuple(dupe) == tuple(pkey)

    return Validation(check, keys, message or "is already taken", is_simple=False)
945889
def uniquecols(df):
    
    bool_idx = df.apply(lambda col: len(np.unique(col)) == 1, axis=0)
    df = df.loc[:, bool_idx].iloc[0:1, :].reset_index(drop=True)
    return df