Parse attribute from file 'pefile.py' and avoid importing
    this module directly.

    __version__, __author__, __contact__,
197975
def _read_attr(attr_name):
    
    regex = attr_name + r"\s+=\s+'(.+)'"
    if sys.version_info.major == 2:
        with open('pefile.py', 'r') as f:
            match = re.search(regex, f.read())
    else:
        with open('pefile.py', 'r', encoding='utf-8') as f:
            match = re.search(regex, f.read())
    # Second item in the group is the value of attribute.
    return match.group(1)
679521
def _import_attr_n_module(module_name, attr):
    
    __import__(module_name)
    module = sys.modules[module_name]
    attr = getattr(module, attr)
    return attr, module
297019
def obj_from_file(filename='annotation.yaml', filetype='auto'):
    '''  '''

    if filetype == 'auto':
        _, ext = os.path.splitext(filename)
        filetype = ext[1:]

    if filetype in ('yaml', 'yml'):
        from ruamel.yaml import YAML
        yaml = YAML(typ="unsafe")
        with open(filename, encoding="utf-8") as f:
            obj = yaml.load(f)
        if obj is None:
            obj = {}
        # import yaml
        # with open(filename, encoding="utf-8") as f:
        #     intext = f.read()
        #     obj = yaml.load(intext)
    elif filetype in ('pickle', 'pkl', 'pklz', 'picklezip'):
        fcontent = read_pkl_and_pklz(filename)
        # import pickle
        if sys.version_info[0] < 3:
            import cPickle as pickle
        else:
            import _pickle as pickle
        # import sPickle as pickle
        if sys.version_info.major == 2:
            obj = pickle.loads(fcontent)
        else:
            obj = pickle.loads(fcontent, encoding="latin1")
    else:
        logger.error('Unknown filetype ' + filetype)
    return obj
980598
def parse(self, file_obj, parsed_files=None):
        '''
        
        '''
        host = {'host': ['*'], 'config': {}}
        for line in file_obj:
            # Strip any leading or trailing whitespace from the line.
            # Refer to https://github.com/paramiko/paramiko/issues/499
            line = line.strip()
            if not line or line.startswith('#'):
                continue

            match = re.match(self.SETTINGS_REGEX, line)
            if not match:
                raise Exception('Unparsable line {}'.format(line))
            key = match.group(1).lower()
            value = match.group(2)

            if key == 'host':
                self._config.append(host)
                host = {
                    'host': self._get_hosts(value),
                    'config': {}
                }
            elif key == 'proxycommand' and value.lower() == 'none':
                # Store 'none' as None; prior to 3.x, it will get stripped out
                # at the end (for compatibility with issue #415). After 3.x, it
                # will simply not get stripped, leaving a nice explicit marker.
                host['config'][key] = None
            elif key == 'include':
                # support for Include directive in ssh_config
                path = value
                # the path can be relative to its parent configuration file
                if os.path.isabs(path) is False and path[0] != '~':
                    folder = os.path.dirname(file_obj.name)
                    path = os.path.join(folder, path)

                # expand the user home path
                path = os.path.expanduser(path)
                if parsed_files is None:
                    parsed_files = []

                # parse every included file
                for filename in glob.iglob(path):
                    if os.path.isfile(filename):
                        if filename in parsed_files:
                            raise Exception('Include loop detected in ssh config file: %s' % filename)
                        with open(filename) as fd:
                            parsed_files.append(filename)
                            self.parse(fd, parsed_files)

            else:
                if value.startswith('"') and value.endswith('"'):
                    value = value[1:-1]

                # identityfile, localforward, remoteforward keys are special
                # cases, since they are allowed to be specified multiple times
                # and they should be tried in order of specification.
                if key in ['identityfile', 'localforward', 'remoteforward']:
                    if key in host['config']:
                        host['config'][key].append(value)
                    else:
                        host['config'][key] = [value]
                elif key not in host['config']:
                    host['config'][key] = value
        self._config.append(host)
492492
def parse(self, filename):
        
        path = os.path.abspath(filename)

        # Only PAW supports XML at present.
        if filename.endswith(".xml"):
            return PawXmlSetup(path)

        ppdesc = self.read_ppdesc(path)

        if ppdesc is None:
            logger.critical("Cannot find ppdesc in %s" % path)
            return None

        psp_type = ppdesc.psp_type

        parsers = {
            "FHI": NcAbinitHeader.fhi_header,
            "GTH": NcAbinitHeader.gth_header,
            "TM": NcAbinitHeader.tm_header,
            "Teter": NcAbinitHeader.tm_header,
            "HGH": NcAbinitHeader.hgh_header,
            "HGHK": NcAbinitHeader.hgh_header,
            "ONCVPSP": NcAbinitHeader.oncvpsp_header,
            "PAW_abinit_text": PawAbinitHeader.paw_header,
        }

        try:
            header = parsers[ppdesc.name](path, ppdesc)
        except Exception:
            raise self.Error(path + ":\n" + straceback())

        if psp_type == "NC":
            pseudo = NcAbinitPseudo(path, header)
        elif psp_type == "PAW":
            pseudo = PawAbinitPseudo(path, header)
        else:
            raise NotImplementedError("psp_type not in [NC, PAW]")

        return pseudo
478090
def import_from(name):
    
    obj = name
    if isinstance(name, str) and len(name):
        try:
            obj = locate(name)
            assert obj is not None
        except (AttributeError, TypeError, AssertionError, ErrorDuringImport):
            try:
                name = name.split(".")
                attr = name[-1]
                name = ".".join(name[:-1])
                mod = importlib.import_module(name)
                obj = getattr(mod, attr)
            except (SyntaxError, AttributeError, ImportError, ValueError):
                try:
                    name = name.split(".")
                    attr_sup = name[-1]
                    name = ".".join(name[:-1])
                    mod = importlib.import_module(name)
                    obj = getattr(getattr(mod, attr_sup), attr)
                except:
                    # We give up.
                    pass

    obj = unwrap_obj(obj)
    return obj
905389
def importpath(path, error_text=None):
    
    result = None
    attrs = []
    parts = path.split('.')
    exception = None
    while parts:
        try:
            result = __import__('.'.join(parts), {}, {}, [''])
        except ImportError as e:
            if exception is None:
                exception = e
            attrs = parts[-1:] + attrs
            parts = parts[:-1]
        else:
            break
    for attr in attrs:
        try:
            result = getattr(result, attr)
        except (AttributeError, ValueError) as e:
            if error_text is not None:
                raise ImproperlyConfigured('Error: %s can import "%s"' % (
                    error_text, path))
            else:
                raise exception
    return result
1125732
def get_setup_attribute(attribute, setup_path):
    
    args = ["python", setup_path, "--%s" % attribute]
    return Popen(args, stdout=PIPE).communicate()[0].decode('utf-8').strip()
855301
def parse_python(spec):  # Ignore PyDocStyleBear
        

        def _extract_op_version(spec):
            # https://www.python.org/dev/peps/pep-0440/#compatible-release
            if spec.operator == "~=":
                version = spec.version.split(".")
                if len(version) in {2, 3, 4}:
                    if len(version) in {3, 4}:
                        del version[-1]  # will increase the last but one in next line
                    version[-1] = str(int(version[-1]) + 1)
                else:
                    raise ValueError("%r must not be used with %r" % (spec.operator, spec.version))
                return [(">=", spec.version), ("<", ".".join(version))]
            # Trailing .* is permitted per
            # https://www.python.org/dev/peps/pep-0440/#version-matching
            elif spec.operator == "==" and spec.version.endswith(".*"):
                try:
                    result = check_output(["/usr/bin/semver-ranger", spec.version], universal_newlines=True).strip()
                    gte, lt = result.split()
                    return [(">=", gte.lstrip(">=")), ("<", lt.lstrip("<"))]
                except ValueError:
                    _LOGGER.warning("couldn't resolve ==%s", spec.version)
                    return spec.operator, spec.version
            # https://www.python.org/dev/peps/pep-0440/#arbitrary-equality
            # Use of this operator is heavily discouraged, so just convert it to 'Version matching'
            elif spec.operator == "===":
                return "==", spec.version
            else:
                return spec.operator, spec.version

        def _get_pip_spec(requirements):
            """There is no `specs` field In Pip 8+, take info from `specifier` field."""
            if hasattr(requirements, "specs"):
                return requirements.specs
            elif hasattr(requirements, "specifier"):
                specs = [_extract_op_version(spec) for spec in requirements.specifier]
                if len(specs) == 0:
                    # TODO: I'm not sure with this one
                    # we should probably return None instead and let pip deal with this
                    specs = [(">=", "0.0.0")]
                return specs

        _LOGGER.info("Parsing dependency %r", spec)
        # create a temporary file and store the spec there since
        # `parse_requirements` requires a file
        with NamedTemporaryFile(mode="w+", suffix="pysolve") as f:
            f.write(spec)
            f.flush()
            parsed = parse_requirements(f.name, session=f.name)
            dependency = [Dependency(x.name, _get_pip_spec(x.req)) for x in parsed].pop()

        return dependency
872860
def execute(self, input_data):

        '''  '''
        raw_bytes = input_data['sample']['raw_bytes']

        # Have the PE File module process the file
        pefile_handle, error_str = self.open_using_pefile('unknown', raw_bytes)
        if not pefile_handle:
            return {'error': error_str, 'dense_features': [], 'sparse_features': []}

        # Now extract the various features using pefile
        dense_features, sparse_features = self.extract_features_using_pefile(pefile_handle)

        # Okay set my response
        return {'dense_features': dense_features, 'sparse_features': sparse_features, 'tags': input_data['tags']['tags']}
694820
def _parse_attrs(elem, container=dict, **options):
    
    adic = dict((_tweak_ns(a, **options), v) for a, v in elem.attrib.items())
    if options.get("ac_parse_value", False):
        return container(dict((k, anyconfig.parser.parse_single(v))
                              for k, v in adic.items()))

    return container(adic)
601611
def import_module_from_file(full_path_to_module):
    
    if inspect.ismodule(full_path_to_module):
        return full_path_to_module

    module = None

    try:

        # Get module name and path from full path
        module_dir, module_file = os.path.split(full_path_to_module)
        module_name, module_ext = os.path.splitext(module_file)

        # Get module "spec" from filename
        spec = spec_from_file_location(module_name, full_path_to_module)

        module = spec.loader.load_module()

    except Exception as ec:
        # Simple error printing
        # Insert "sophisticated" stuff here
        print(ec)

    finally:
        return module
835947
def version_from_xml_filename(filename):
    ""
    try:
        filename_parts = filename.split(os.sep)[-1].split('-')
    except AttributeError:
        return None
    if len(filename_parts) == 3:
        try:
            return int(filename_parts[-1].lstrip('v').rstrip('.xml'))
        except ValueError:
            return None
    else:
        return None
841771
def parse_file(self, name):
        
        with open(name, "rb") as fp:
            return self.parse(fp.read())
412124
def parse(self, file_name):
        
        self.object = self.parsed_class()
        with open(file_name, encoding='utf-8') as f:
            self.parse_str(f.read())
        return self.object
296394
def import_object(module_name, attribute_name):
    
    # Py2 compatibility: force str (i.e bytes) when importing.
    module = __import__(str(module_name), {}, {}, [str(attribute_name)], 0)
    return getattr(module, str(attribute_name))
542353
def fromFile(filename):
        
        xdata = None
        ydata = None

        # try parsing an XML file
        try:
            xdata = ElementTree.parse(filename).getroot()
        except StandardError:
            xdata = None

        if xdata is None:
            # try parsing a yaml file
            if yaml:
                with open(filename, 'r') as f:
                    text = f.read()

                try:
                    ydata = yaml.load(text)
                except StandardError:
                    return None
            else:
                log.warning('Could not process yaml builder!')

        # load a yaml definition
        if type(ydata) == dict:
            typ = ydata.get('type')
            module = ydata.get('module')
            builder = Builder.plugin(typ, module)
            if builder:
                return builder.fromYaml(ydata, os.path.dirname(filename))
            else:
                log.warning('Could not find builder: {0}'.format(typ))

        # load an xml definition
        elif xdata is not None:
            typ = xdata.get('type')
            module = xdata.get('module')
            builder = Builder.plugin(typ, module)
            if builder:
                return builder.fromXml(xdata, os.path.dirname(filename))
            else:
                log.warning('Could not find builder: {0}'.format(typ))

        return None