Return a syntax-valid Python reference name from an arbitrary name
347868
def fix_reference_name(name, blacklist=None):
    """"""
    name = "".join(re.split(r'[^0-9a-zA-Z_]', name))
    while name and not re.match(r'([a-zA-Z]+[0-9a-zA-Z_]*)$', name):
        if not re.match(r'[a-zA-Z]', name[0]):
            name = name[1:]
            continue
    name = str(name)
    if not name:
        name = "data"
    if blacklist is not None and name in blacklist:
        get_new_name = lambda index: name+('%03d' % index)
        index = 0
        while get_new_name(index) in blacklist:
            index += 1
        name = get_new_name(index)
    return name
136379
def _fake_referencenames(self, namespace, **params):
        
        assert params['ResultClass'] is None or \
            isinstance(params['ResultClass'], CIMClassName)

        rc = None if params['ResultClass'] is None else \
            params['ResultClass'].classname
        role = params['Role']
        obj_name = params['ObjectName']
        classname = obj_name.classname

        if isinstance(obj_name, CIMClassName):
            ref_classnames = self._get_reference_classnames(classname,
                                                            namespace,
                                                            rc, role)

            ref_result = [CIMClassName(classname=cn, host=self.host,
                                       namespace=namespace)
                          for cn in ref_classnames]

            return self._return_assoc_tuple(ref_result)

        assert isinstance(obj_name, CIMInstanceName)
        ref_paths = self._get_reference_instnames(obj_name, namespace,
                                                  rc, role)
        rtn_names = [deepcopy(r) for r in ref_paths]

        for iname in rtn_names:
            if iname.host is None:
                iname.host = self.host

        return self._return_assoc_tuple(rtn_names)
1165901
def visit_NameConstant(self, node: AST, dfltChaining: bool = True) -> str:
        """"""
        return str(node.value)
785929
def get_qualified_name(_object):
    """"""
    module = _object.__module__
    if hasattr(_object, '__name__'):
        _class = _object.__name__

    else:
        _class = _object.__class__.__name__

    return module + '.' + _class
1236751
def qualified_name(self):
        ''''''
        if self.module == self:
            return self.module.name
        else:
            if "." not in self.name:
                return '{0}.{1}'.format(self.module.name, self.name)
            else:
                # We have a fully qualified reference, just return it
                return self.name
352635
def path_to_reference(path):
    """"""

    # By default JSON decodes strings as unicode. The Python __import__ does
    # not like that choice. So we'll just cast all function paths to a string.
    # NOTE: that there is no corresponding unit test for the classmethod
    # version of this problem.  It only impacts importing modules.
    path = str(path)

    if '.' not in path:
        try:
            return globals()["__builtins__"][path]
        except KeyError:
            try:
                return getattr(globals()["__builtins__"], path)
            except AttributeError:
                pass

        try:
            return globals()[path]
        except KeyError:
            pass

        raise errors.BadObjectPathError(
            'Unable to find function "%s".' % (path,))

    module_path, function_name = path.rsplit('.', 1)

    try:
        module = __import__(name=module_path,
                            fromlist=[function_name])
    except ImportError:
        module_path, class_name = module_path.rsplit('.', 1)

        module = __import__(name=module_path, fromlist=[class_name])
        module = getattr(module, class_name)

    try:
        return getattr(module, function_name)
    except AttributeError:
        raise errors.BadObjectPathError(
            'Unable to find function "%s".' % (path,))
1374743
def full_name(cla55: Optional[type]) -> str:
    
    # Special case to handle None:
    if cla55 is None:
        return "?"

    if issubclass(cla55, Initializer) and cla55 not in [Initializer, PretrainedModelInitializer]:
        init_fn = cla55()._init_function
        return f"{init_fn.__module__}.{init_fn.__name__}"

    origin = getattr(cla55, '__origin__', None)
    args = getattr(cla55, '__args__', ())

    # Special handling for compound types
    if origin in (Dict, dict):
        key_type, value_type = args
        return f"""Dict[{full_name(key_type)}, {full_name(value_type)}]"""
    elif origin in (Tuple, tuple, List, list, Sequence, collections.abc.Sequence):
        return f"""{_remove_prefix(str(origin))}[{", ".join(full_name(arg) for arg in args)}]"""
    elif origin == Union:
        # Special special case to handle optional types:
        if len(args) == 2 and args[-1] == type(None):
            return f"""Optional[{full_name(args[0])}]"""
        else:
            return f"""Union[{", ".join(full_name(arg) for arg in args)}]"""
    else:
        return _remove_prefix(f"{cla55.__module__}.{cla55.__name__}")
171962
def __StripName(self, name):
        """"""
        if not name:
            return name
        for prefix in self.__strip_prefixes:
            if name.startswith(prefix):
                return name[len(prefix):]
        return name
678696
def in_tree(self, name):
        
        """
        if self._validate_node_name(name):
            raise RuntimeError("Argument `name` is not valid")
        return name in self._db
252921
def _get_ref(repo, name):
    '''
    
    '''
    if name == 'base':
        name = repo['base']
    if name == repo['base'] or name in envs():
        if repo['branch_method'] == 'branches':
            return _get_branch(repo['repo'], name) \
                or _get_tag(repo['repo'], name)
        elif repo['branch_method'] == 'bookmarks':
            return _get_bookmark(repo['repo'], name) \
                or _get_tag(repo['repo'], name)
        elif repo['branch_method'] == 'mixed':
            return _get_branch(repo['repo'], name) \
                or _get_bookmark(repo['repo'], name) \
                or _get_tag(repo['repo'], name)
    return False
367301
def _get_callable_full_name(self, fob, fin, uobj):
        """"""
        # Check if object is a class property
        name = self._property_search(fob)
        if name:
            del fob, fin, uobj
            return name
        if os.path.isfile(fin):
            lineno = fob.f_lineno
            ret = self._callables_obj.get_callable_from_line(fin, lineno)
            del fob, fin, uobj, name, lineno
            return ret
        # Code executed in doctests does not have an actual callable object
        # exec-based callables do not have a valid file name
        fname = uobj and _get_func_code(uobj).co_filename
        if (not fname) or (fname and (not os.path.isfile(fname))):
            del fob, fin, uobj, name, fname
            return "dynamic"
        code_id = (
            inspect.getfile(uobj).replace(".pyc", "py"),
            inspect.getsourcelines(uobj)[1],
        )
        self._callables_obj.trace([code_id[0]])
        ret = self._callables_obj.reverse_callables_db[code_id]
        del fob, fin, uobj, name, fname, code_id
        return ret
896841
def get_python(self):
        """"""
        cursor = super(ReferenceField, self).get_python()

        if self.multiselect:
            return cursor

        else:
            try:
                return cursor[0]
            except IndexError:
                return None
782863
def getReferenceSetByName(self, name):
        
        if name not in self._referenceSetNameMap:
            raise exceptions.ReferenceSetNameNotFoundException(name)
        return self._referenceSetNameMap[name]
411343
def import_name_or_class(name):
    "  "

    if isinstance(name, str):

        # for "a.b.c.d" -> [ 'a.b.c', 'd' ]
        module_name, object_name = name.rsplit('.',1)
        # __import__ loads the multi-level of module, but returns
        # the top level, which we have to descend into
        mod = __import__(module_name)

        components = name.split('.')

        for comp in components[1:]: # Already got the top level, so start at 1

            mod = getattr(mod, comp)
        return mod
    else:
        return name
580690
def a(value):
    
    name = getattr(value, 'name', value)
    return some(lambda t: t == value).named(u'(a "%s")' % (name,))
296344
def name_for_callable(func):
  """"""
  if isinstance(func, functools.partial):
    return name_for_callable(func.func)

  try:
    name = func.__name__
  except AttributeError:
    return None

  if name == "<lambda>":
    return None
  else:
    return to_snake_case(name)
1026727
def p_dynamic_class_name_reference(p):
    ''''''
    if len(p) == 5:
        name, dims = p[3]
        p[0] = ast.ObjectProperty(p[1], name, lineno=p.lineno(2))
        for class_, dim, lineno in dims:
            p[0] = class_(p[0], dim, lineno=lineno)
        for name, dims in p[4]:
            p[0] = ast.ObjectProperty(p[0], name, lineno=p.lineno(2))
            for class_, dim, lineno in dims:
                p[0] = class_(p[0], dim, lineno=lineno)
    else:
        p[0] = p[1]