Python load library

60 Python code examples are found related to " load library". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: misc.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def load_library(libname):
# numpy 1.6 has bug in ctypeslib.load_library, see numpy/distutils/misc_util.py
    if '1.6' in numpy.__version__:
        if (sys.platform.startswith('linux') or
            sys.platform.startswith('gnukfreebsd')):
            so_ext = '.so'
        elif sys.platform.startswith('darwin'):
            so_ext = '.dylib'
        elif sys.platform.startswith('win'):
            so_ext = '.dll'
        else:
            raise OSError('Unknown platform')
        libname_so = libname + so_ext
        return ctypes.CDLL(os.path.join(os.path.dirname(__file__), libname_so))
    else:
        _loaderpath = os.path.dirname(__file__)
        return numpy.ctypeslib.load_library(libname, _loaderpath)

#Fixme, the standard resouce module gives wrong number when objects are released
#see http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/#fn:1
#or use slow functions as memory_profiler._get_memory did 
Example 2
Source File: librace.py    From racepwn with MIT License 6 votes vote down vote up
def load_library(self, libname):
        try:
            result = LibraryLoader.load_library(self, libname)
        except ImportError:
            result = None
            if os.path.sep not in libname:
                for name in self.name_formats:
                    try:
                        result = getattr(ctypes.cdll, name % libname)
                        if result:
                            break
                    except WindowsError:
                        result = None
            if result is None:
                try:
                    result = getattr(ctypes.cdll, libname)
                except WindowsError:
                    result = None
            if result is None:
                raise ImportError("%s not found." % libname)
        return result 
Example 3
Source File: loader.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def load_op_library(path):
  """Loads a contrib op library from the given path.

  NOTE(mrry): On Windows, we currently assume that contrib op
  libraries are statically linked into the main TensorFlow Python
  extension DLL.

  Args:
    path: An absolute path to a shared object file.

  Returns:
    A Python module containing the Python wrappers for Ops defined in the
    plugin.
  """
  if os.name != 'nt':
    path = resource_loader.get_path_to_datafile(path)
    ret = load_library.load_op_library(path)
    assert ret, 'Could not load %s' % path
    return ret
  else:
    # NOTE(mrry):
    return None 
Example 4
Source File: defaulttags.py    From bioforum with MIT License 6 votes vote down vote up
def load_from_library(library, label, names):
    """
    Return a subset of tags and filters from a library.
    """
    subset = Library()
    for name in names:
        found = False
        if name in library.tags:
            found = True
            subset.tags[name] = library.tags[name]
        if name in library.filters:
            found = True
            subset.filters[name] = library.filters[name]
        if found is False:
            raise TemplateSyntaxError(
                "'%s' is not a valid tag or filter in tag library '%s'" % (
                    name, label,
                ),
            )
    return subset 
Example 5
Source File: sql.py    From wrds with MIT License 6 votes vote down vote up
def load_library_list(self):
        """ Load the list of Postgres schemata (c.f. SAS LIBNAMEs)
              the user has permission to access. """
        self.insp = sa.inspect(self.connection)
        print("Loading library list...")
        query = """
        WITH RECURSIVE "names"("name") AS (
            SELECT n.nspname AS "name"
                FROM pg_catalog.pg_namespace n
                WHERE n.nspname !~ '^pg_'
                    AND n.nspname <> 'information_schema')
            SELECT "name"
                FROM "names"
                WHERE pg_catalog.has_schema_privilege(
                    current_user, "name", 'USAGE') = TRUE;
        """
        cursor = self.connection.execute(query)
        self.schema_perm = [x[0] for x in cursor.fetchall()
                            if not (x[0].endswith('_old') or
                                    x[0].endswith('_all'))]
        print("Done") 
Example 6
Source File: windows.py    From mayhem with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_library(self, libpath):
		libpath = os.path.abspath(libpath)
		libpath_bytes = libpath.encode('utf-8') + b'\x00'
		remote_page = m_k32.VirtualAllocEx(self.handle, None, len(libpath_bytes), flags("MEM_COMMIT"), flags("PAGE_EXECUTE_READWRITE"))
		if not remote_page:
			raise WindowsProcessError('Error: failed to allocate space for library name in the target process')
		if not m_k32.WriteProcessMemory(self.handle, remote_page, libpath_bytes, len(libpath_bytes), None):
			raise WindowsProcessError('Error: failed to copy the library name to the target process')
		remote_thread = m_k32.CreateRemoteThread(self.handle, None, 0, m_k32.LoadLibraryA.address, remote_page, 0, None)
		m_k32.WaitForSingleObject(remote_thread, -1)

		exitcode = wintypes.DWORD(0)
		m_k32.GetExitCodeThread(remote_thread, ctypes.byref(exitcode))
		m_k32.VirtualFreeEx(self.handle, remote_page, len(libpath_bytes), flags("MEM_RELEASE"))
		if exitcode.value == 0:
			raise WindowsProcessError("Error: failed to load: {0}, thread exited with status: 0x{1:x}".format(libpath, exitcode.value))
		return exitcode.value 
Example 7
Source File: windows.py    From BoomER with GNU General Public License v3.0 6 votes vote down vote up
def load_library(self, libpath):
        libpath = os.path.abspath(libpath)
        libpath = libpath.encode('utf-8') + b'\x00'
        LoadLibraryA = self.k32.GetProcAddress(self.k32.GetModuleHandleA(b'kernel32.dll'), b'LoadLibraryA')
        remote_page = self.k32.VirtualAllocEx(self.handle, None, len(libpath), flags("MEM_COMMIT"),
                                              flags("PAGE_EXECUTE_READWRITE"))
        if not remote_page:
            raise WindowsProcessError('Error: failed to allocate space for library name in the target process')
        if not self.k32.WriteProcessMemory(self.handle, remote_page, libpath, len(libpath), None):
            raise WindowsProcessError('Error: failed to copy the library name to the target process')
        remote_thread = self.k32.CreateRemoteThread(self.handle, None, 0, LoadLibraryA, remote_page, 0, None)
        self.k32.WaitForSingleObject(remote_thread, -1)

        exitcode = wintypes.DWORD(0)
        self.k32.GetExitCodeThread(remote_thread, ctypes.byref(exitcode))
        self.k32.VirtualFreeEx(self.handle, remote_page, len(libpath), flags("MEM_RELEASE"))
        if exitcode.value == 0:
            raise WindowsProcessError(
                "Error: failed to load: {0}, thread exited with status: 0x{1:x}".format(libpath, exitcode.value))
        return exitcode.value 
Example 8
Source File: app.py    From threatspec with MIT License 6 votes vote down vote up
def load_threat_library(self, path, local=False):
        filename = data.abs_path(path, "threatmodel", "threats.json")

        logger.debug("Validating {}".format(filename))
        (valid, error) = data.validate_yaml_file(filename, os.path.join("data", "threats_schema.json"))
        if not valid:
            logger.error("Couldn't validate the threat library file {}: {}".format(filename, error))
            sys.exit(1)

        try:
            if local:
                run_id = self.threatmodel.run_id
            else:
                run_id = None
            self.threat_library.load(data.read_json(filename), run_id)
            logger.debug("Loaded threat library from {}".format(filename))
        except FileNotFoundError:
            pass 
Example 9
Source File: app.py    From threatspec with MIT License 6 votes vote down vote up
def load_control_library(self, path, local=False):
        filename = data.abs_path(path, "threatmodel", "controls.json")

        logger.debug("Validating {}".format(filename))
        (valid, error) = data.validate_yaml_file(filename, os.path.join("data", "controls_schema.json"))
        if not valid:
            logger.error("Couldn't validate the control library file {}: {}".format(filename, error))
            sys.exit(1)

        try:
            if local:
                run_id = self.threatmodel.run_id
            else:
                run_id = None
            self.control_library.load(data.read_json(filename), run_id)
            logger.debug("Loaded control library from path {}".format(filename))
        except FileNotFoundError:
            pass 
Example 10
Source File: app.py    From threatspec with MIT License 6 votes vote down vote up
def load_component_library(self, path, local=False):
        filename = data.abs_path(path, "threatmodel", "components.json")

        logger.debug("Validating {}".format(filename))
        (valid, error) = data.validate_yaml_file(filename, os.path.join("data", "components_schema.json"))
        if not valid:
            logger.error("Couldn't validate the components library file {}: {}".format(filename, error))
            sys.exit(1)

        try:
            if local:
                run_id = self.threatmodel.run_id
            else:
                run_id = None
            self.component_library.load(data.read_json(filename), run_id)
            logger.debug("Loaded component library from path {}".format(filename))
        except FileNotFoundError:
            pass 
Example 11
Source File: backend.py    From dragon with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def load_library(library_location):
    """Load a shared library.

    The library should contain objects registered
    in a registry, e.g., ``CPUOperatorRegistry``.

    Parameters
    ----------
    library_location : str
        The path of the shared library file.

    """
    if not os.path.exists(library_location):
        raise FileNotFoundError('Invalid path: %s' % library_location)
    with dlopen_guard():
        ctypes.cdll.LoadLibrary(library_location)
    _reload_registry() 
Example 12
Source File: load_library.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 6 votes vote down vote up
def load_file_system_library(library_filename):
  """Loads a TensorFlow plugin, containing file system implementation.

  Pass `library_filename` to a platform-specific mechanism for dynamically
  loading a library. The rules for determining the exact location of the
  library are platform-specific and are not documented here.

  Args:
    library_filename: Path to the plugin.
      Relative or absolute filesystem path to a dynamic library file.

  Returns:
    None.

  Raises:
    RuntimeError: when unable to load the library.
  """
  with errors_impl.raise_exception_on_not_ok_status() as status:
    lib_handle = py_tf.TF_LoadLibrary(library_filename, status) 
Example 13
Source File: utils.py    From multibootusb with GNU General Public License v2.0 5 votes vote down vote up
def load_ctypes_library(name, signatures, error_checkers):
    """
    Load library ``name`` and return a :class:`ctypes.CDLL` object for it.

    :param str name: the library name
    :param signatures: signatures of methods
    :type signatures: dict of str * (tuple of (list of type) * type)
    :param error_checkers: error checkers for methods
    :type error_checkers: dict of str * ((int * ptr * arglist) -> int)

    The library has errno handling enabled.
    Important functions are given proper signatures and return types to support
    type checking and argument conversion.

    :returns: a loaded library
    :rtype: ctypes.CDLL
    :raises ImportError: if the library is not found
    """
    library_name = find_library(name)
    if not library_name:
        raise ImportError('No library named %s' % name)
    lib = CDLL(library_name, use_errno=True)
    # Add function signatures
    for funcname, signature in signatures.items():
        function = getattr(lib, funcname, None)
        if function:
            argtypes, restype = signature
            function.argtypes = argtypes
            function.restype = restype
            errorchecker = error_checkers.get(funcname)
            if errorchecker:
                function.errcheck = errorchecker
    return lib 
Example 14
Source File: process.py    From tenpy with GNU General Public License v3.0 5 votes vote down vote up
def load_omp_library(libs=["libiomp5.so",
                           find_library("libiomp5md"),
                           find_library("gomp")],
                     verbose=True):
    """Tries to load openMP library.

    Parameters
    ----------
    libs :
        list of possible library names we should try to load (with ctypes.CDLL).
    verbose : bool
        wheter to print the name of the loaded library.

    Returns
    -------
    omp : CDLL | None
        OpenMP shared libary if found, otherwise None.
        Once it was sucessfully imported, no re-imports are tried.
    """
    global _omp_lib
    if _omp_lib is None:
        for l in libs:
            if l is None:
                continue
            try:
                _omp_lib = ctypes.CDLL(l)
                if verbose:
                    print("loaded " + l + " for omp")
                break
            except OSError:
                pass
    if _omp_lib is None:
        warnings.warn("OpenMP library not found: can get/set nthreads")
    return _omp_lib 
Example 15
Source File: load_library.py    From lambda-packs with MIT License 5 votes vote down vote up
def load_file_system_library(library_filename):
  """Loads a TensorFlow plugin, containing file system implementation.

  Pass `library_filename` to a platform-specific mechanism for dynamically
  loading a library. The rules for determining the exact location of the
  library are platform-specific and are not documented here.

  Args:
    library_filename: Path to the plugin.
      Relative or absolute filesystem path to a dynamic library file.

  Returns:
    None.

  Raises:
    RuntimeError: when unable to load the library.
  """
  status = py_tf.TF_NewStatus()
  lib_handle = py_tf.TF_LoadLibrary(library_filename, status)
  try:
    error_code = py_tf.TF_GetCode(status)
    if error_code != 0:
      error_msg = compat.as_text(py_tf.TF_Message(status))
      # pylint: disable=protected-access
      raise errors_impl._make_specific_exception(
          None, None, error_msg, error_code)
      # pylint: enable=protected-access
  finally:
    py_tf.TF_DeleteStatus(status) 
Example 16
Source File: loader.py    From lambda-packs with MIT License 5 votes vote down vote up
def load_op_library(path):
  """Loads a contrib op library from the given path.

  NOTE(mrry): On Windows, we currently assume that some contrib op
  libraries are statically linked into the main TensorFlow Python
  extension DLL - use dynamically linked ops if the .so is present.

  Args:
    path: An absolute path to a shared object file.

  Returns:
    A Python module containing the Python wrappers for Ops defined in the
    plugin.
  """
  if os.name == 'nt':
    # To avoid makeing every user_ops aware of windows, re-write
    # the file extension from .so to .dll.
    path = re.sub(r'\.so$', '.dll', path)

    # Currently we have only some user_ops as dlls on windows - don't try
    # to load them if the dll is not found.
    # TODO(mrry): Once we have all of them this check should be removed.
    if not os.path.exists(path):
      return None
  path = resource_loader.get_path_to_datafile(path)
  ret = load_library.load_op_library(path)
  assert ret, 'Could not load %s' % path
  return ret 
Example 17
Source File: winobject.py    From LKD with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_library(self, dll_path):
        """Load the library in remote process"""
        x = self.virtual_alloc(0x1000)
        self.write_memory(x, dll_path)
        LoadLibrary = utils.get_func_addr('kernel32', 'LoadLibraryA')
        return self.create_thread(LoadLibrary, x) 
Example 18
Source File: vengine_gen.py    From bioforum with MIT License 5 votes vote down vote up
def load_library(self, flags=0):
        # import it with the CFFI backend
        backend = self.ffi._backend
        # needs to make a path that contains '/', on Posix
        filename = os.path.join(os.curdir, self.verifier.modulefilename)
        module = backend.load_library(filename, flags)
        #
        # call loading_gen_struct() to get the struct layout inferred by
        # the C compiler
        self._load(module, 'loading')

        # build the FFILibrary class and instance, this is a module subclass
        # because modules are expected to have usually-constant-attributes and
        # in PyPy this means the JIT is able to treat attributes as constant,
        # which we want.
        class FFILibrary(types.ModuleType):
            _cffi_generic_module = module
            _cffi_ffi = self.ffi
            _cffi_dir = []
            def __dir__(self):
                return FFILibrary._cffi_dir
        library = FFILibrary("")
        #
        # finally, call the loaded_gen_xxx() functions.  This will set
        # up the 'library' object.
        self._load(module, 'loaded', library=library)
        return library 
Example 19
Source File: ctypeslib.py    From Computable with MIT License 5 votes vote down vote up
def load_library(libname, loader_path):
        if ctypes.__version__ < '1.0.1':
            import warnings
            warnings.warn("All features of ctypes interface may not work " \
                          "with ctypes < 1.0.1")

        ext = os.path.splitext(libname)[1]
        if not ext:
            # Try to load library with platform-specific name, otherwise
            # default to libname.[so|pyd].  Sometimes, these files are built
            # erroneously on non-linux platforms.
            from numpy.distutils.misc_util import get_shared_lib_extension
            so_ext = get_shared_lib_extension()
            libname_ext = [libname + so_ext]
            # mac, windows and linux >= py3.2 shared library and loadable
            # module have different extensions so try both
            so_ext2 = get_shared_lib_extension(is_python_ext=True)
            if not so_ext2 == so_ext:
                libname_ext.insert(0, libname + so_ext2)
        else:
            libname_ext = [libname]

        loader_path = os.path.abspath(loader_path)
        if not os.path.isdir(loader_path):
            libdir = os.path.dirname(loader_path)
        else:
            libdir = loader_path

        for ln in libname_ext:
            libpath = os.path.join(libdir, ln)
            if os.path.exists(libpath):
                try:
                    return ctypes.cdll[libpath]
                except OSError:
                    ## defective lib file
                    raise
        ## if no successful return in the libname_ext loop:
        raise OSError("no file with expected extension") 
Example 20
Source File: pupyimporter.py    From mimipy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_library(self, data, fullname, dlopen=True, initfuncname=None):
            fd = -1
            closefd = True

            result = False

            if self.memfd:
                fd = self.memfd()
                if fd != -1:
                    name = '/proc/self/fd/{}'.format(fd)
                    closefd = False

            if fd == -1:
                fd, name = mkstemp(dir=self.dir)

            try:
                write(fd, data)
                if dlopen:
                    result = ctypes.CDLL(fullname)
                else:
                    if initfuncname:
                        result = imp.load_dynamic(initfuncname[4:], name)
                    else:
                        result = imp.load_dynamic(fullname, name)

            except Exception as e:
                self.dir = None
                raise e

            finally:
                if closefd:
                    close(fd)
                    unlink(name)

            return result 
Example 21
Source File: bruker_tims.py    From ms_deisotope with Apache License 2.0 5 votes vote down vote up
def load_library(search_paths=None):
    if search_paths is None:
        search_paths = []
    elif isinstance(search_paths, str):
        search_paths = [search_paths]
    global dll
    if dll is None:
        for lib_path in search_paths:
            try:
                dll = _load_library(lib_path)
            except (Exception) as err:
                continue
            if dll is not None:
                break
    return dll 
Example 22
Source File: phase.py    From qmpy with MIT License 5 votes vote down vote up
def load_library(self, library):
        """
        Load a library file, containing self-consistent thermochemical data.

        Equivalent to::
            >>> pd = PhaseData()
            >>> pd.read_file(INSTALL_PATH+'/data/thermodata/%s' % library)

        """
        logger.debug('Loading Phases from %s' % library)
        self.read_file(qmpy.INSTALL_PATH+'/data/thermodata/'+library) 
Example 23
Source File: libc.py    From Daniel-Arbuckles-Mastering-Python with MIT License 5 votes vote down vote up
def load_library(*alternates):
    for base_name in alternates:
        lib_name = ctypes.util.find_library(base_name)

        try:
            if lib_name:
                return ctypes.CDLL(lib_name)
            else:
                return ctypes.CDLL(base_name)
        except OSError:
            pass

    raise OSError('Unable to load any of: {}'.format(alternates)) 
Example 24
Source File: core.py    From neural-network-animation with MIT License 5 votes vote down vote up
def load_base_library():
    """Load style library defined in this package."""
    library = dict()
    library.update(read_style_directory(BASE_LIBRARY_PATH))
    return library 
Example 25
Source File: libloader.py    From Pluvia with GNU General Public License v3.0 5 votes vote down vote up
def load_library(lib, name=None, lib_cls=None):
    """Loads a library. Catches and logs exceptions.

    Returns: the loaded library or None

    arguments:
    * lib        -- path to/name of the library to be loaded
    * name       -- the library's identifier (for logging)
                    Defaults to None.
    * lib_cls    -- library class. Defaults to None (-> ctypes.CDLL).
    """
    try:
        if lib_cls:
            return lib_cls(lib)
        else:
            return ctypes.CDLL(lib)
    except Exception:
        if name:
            lib_msg = '%s (%s)' % (name, lib)
        else:
            lib_msg = lib

        lib_msg += ' could not be loaded'

        if sys.platform == 'cygwin':
            lib_msg += ' in cygwin'
        _LOGGER.error(lib_msg, exc_info=True)
        return None 
Example 26
Source File: abstractscene.py    From cross3d with MIT License 5 votes vote down vote up
def loadMaterialsFromLibrary(self, filename=''):
		"""
			\remarks	loads all the materials from a given material library file
			\param		filename	<str>
			\return		<list> [ <cross3d.SceneMaterial> ]
		"""
		from cross3d import SceneMaterial
		return [ SceneMaterial(self, nativeMaterial) for nativeMaterial in self._loadNativeMaterialsFromLibrary(filename) ] 
Example 27
Source File: base.py    From beat with GNU General Public License v3.0 5 votes vote down vote up
def load_gf_library(directory='', filename=None):
    """
    Loading GF Library config and initialise memmaps for Traces and times.
    """
    inpath = os.path.join(directory, filename)
    datatype = filename.split('_')[0]

    if datatype == 'seismic':
        gfs = SeismicGFLibrary()
        gfs.load_config(filename=inpath + '.yaml')
        gfs._gfmatrix = num.load(
            inpath + '.traces.npy',
            mmap_mode=('r'),
            allow_pickle=False)
        gfs._tmins = num.load(
            inpath + '.times.npy',
            mmap_mode=('r'),
            allow_pickle=False)

    elif datatype == 'geodetic':
        gfs = GeodeticGFLibrary()
        gfs.load_config(filename=inpath + '.yaml')
        gfs._gfmatrix = num.load(
            inpath + '.traces.npy',
            mmap_mode=('r'),
            allow_pickle=False)

    else:
        raise ValueError('datatype "%s" not supported!' % datatype)

    gfs._stack_switch['numpy'] = gfs._gfmatrix
    return gfs 
Example 28
Source File: __init__.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def load_library_modules(scene):
    """ Register Every Library Module on Startup
    """
    bpy.ops.fd_general.load_library_modules()

    if bpy.context.scene.mv.product_library_name not in bpy.context.window_manager.cabinetlib.lib_products:
        bpy.context.scene.mv.product_library_name = bpy.context.window_manager.cabinetlib.lib_products[0].name

# Register Startup Events 
Example 29
Source File: fpx_import.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def LoadFromBlendLibrary(self, name, type, file):
        """
        name: 'fpmodel.fpl\\<object>.g'
        type: 'IMAGE', 'MODEL'
        file: '<addons>\\io_scene_fpx\\fpx_resource.blend'
        """
        #print("#DEBUG LoadFromBlendLibrary", name, type, file)

        with self.__data.libraries.load(file) as (data_from, data_to):
            # imports data from library
            if type == Fpt_PackedLibrary_Type.TYPE_IMAGE:
                data_from_list = data_from.images
                name_temp = name

                if name_temp not in data_from.images:
                    return None
                # embed image data from library
                data_to.images = [name_temp, ]

            elif type == Fpt_PackedLibrary_Type.TYPE_MODEL:
                if name.endswith(".g"):
                    name_scene = "{}.s".format(name[:-2])
                    if name_scene not in data_from.scenes:
                        return None
                    # embed scene data from library
                    data_to.scenes = [name_scene, ]

                if name not in data_from.groups:
                    return None
                # embed group data from library
                data_to.groups = [name, ]

            else:
                return None

        # try to get internal data
        return self.LoadFromEmbedded(name, type) 
Example 30
Source File: fpx_import.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def LoadFromPathLibrary(self, name, type, lib, folder):
        """
        name: 'fpmodel.fpl\\<object>.g'
        type: 'IMAGE', 'MODEL'
        lib:  'fpmodel.fpl'
        folder: '.\\'
        """
        #print("#DEBUG LoadFromPathLibrary", name, type, lib, folder)

        filepath = path.join(folder, lib)
        filepath = FpxUtilities.toGoodFilePath(filepath)
        if path.exists(filepath):
            FplImporter(
                    report=self.report,
                    verbose=self.verbose,
                    keep_temp=self.keep_temp,
                    use_library_filter=self.use_library_filter,
                    use_model_filter=self.use_model_filter,
                    use_model_adjustment=self.use_model_adjustment,
                    keep_name=False,
                    ).read(
                            self.__context,
                            filepath,
                            )

            return self.LoadFromEmbedded(name, type)

        return None 
Example 31
Source File: gindexekg.py    From aurum-datadiscovery with MIT License 5 votes vote down vote up
def load_and_config_library(libname):
    global gI
    gI = cdll.LoadLibrary(libname)
    gI.neighbors.argtypes = [POINTER(POINTER(c_int32))]
    gI.neighbors.restype = int
    gI.all_paths.argtypes = [POINTER(POINTER(c_int32))]
    gI.all_paths.restype = int
    gI.release_array.argtypes = [POINTER(c_int32)]
    gI.release_array.restype = None
    gI.serialize_graph_to_disk.argtypes = [c_char_p]
    gI.serialize_graph_to_disk.restype = None 
Example 32
Source File: ext_utils.py    From nvtx-plugins with Apache License 2.0 5 votes vote down vote up
def load_library(name):
    """Loads a .so file containing the specified operators.
    Args:
      name: The name of the .so file to load.
    Raises:
      NotFoundError if were not able to load .so file.
    """

    filename = resource_loader.get_path_to_datafile(name)
    library = _load_library.load_op_library(filename)
    return library 
Example 33
Source File: generic.py    From quantipy with MIT License 5 votes vote down vote up
def loadLibrary(self):
        """This function loads and returns the SPSSIO libraries,
        depending on the platform."""

        arch = platform.architecture()[0]
        is_32bit, is_64bit = arch == "32bit", arch == "64bit"
        pf = sys.platform.lower()

        # windows
        if pf.startswith("win") and is_32bit:
            spssio = self._loadLibs("win32")
        elif pf.startswith("win"):
            spssio = self._loadLibs("win64")

        # linux
        elif pf.startswith("lin") and is_32bit:
            spssio = self._loadLibs("lin32")
        elif pf.startswith("lin") and is_64bit and os.uname()[-1] == "s390x":
            # zLinux64: Thanks Anderson P. from System z Linux LinkedIn Group!
            spssio = self._loadLibs("zlinux")
        elif pf.startswith("lin") and is_64bit:
            spssio = self._loadLibs("lin64")

        # other
        elif pf.startswith("darwin") or pf.startswith("mac"):
            # Mac: Thanks Rich Sadowsky!
            spssio = self._loadLibs("macos")
        elif pf.startswith("aix") and is_64bit:
            spssio = self._loadLibs("aix64")
        elif pf.startswith("hp-ux"):
            spssio = self._loadLibs("hpux_it")
        elif pf.startswith("sunos") and is_64bit:
            spssio = self._loadLibs("sol64")
        else:
            msg = "Your platform (%r) is not supported" % pf
            raise EnvironmentError(msg)

        return spssio 
Example 34
Source File: local.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_library_from_aix_archive(path, member_name='shr.o'):
    """
    Extract the shared object from the archive and load it as a normal
    library.
    """
    import atexit
    import tempfile

    import arpy

    def remove_file_at_exit(path):
        # Reimport os as it might be removed at exit.
        import os
        os.remove(path)

    archive = arpy.AIXBigArchive(path)
    archive.read_all_headers()
    member = archive.archived_files[member_name]
    temp_file = None
    try:
        temp_fd, path = tempfile.mkstemp()
        temp_file = os.fdopen(temp_fd, 'wb')
        atexit.register(remove_file_at_exit, path)
        temp_file.write(member.read())
    finally:
        if temp_file:
            temp_file.close()
    return CDLL(path) 
Example 35
Source File: local.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_library(nickname, search_names=None):
    '''Load a library based on the result of find_library(nickname),
    or hardcoded names found in `search_names`.'''

    library = None
    if search_names is None:
        search_names = []

    # We try to guess the library name using `find_library`.
    # If we found a name, we add it a the first to be tried for loading.
    guess_path = find_library(nickname)
    if guess_path is not None:
        search_names.insert(0, guess_path)

    # Try to load each name, and stop when a name was successfuly loaded.
    for name in search_names:
        try:
            library = CDLL(name)
        except OSError:
            library = None

        if library is not None:
            return library

    if library is None:
        raise AssertionError("Failed to load '%s' library." % (nickname)) 
Example 36
Source File: obj.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_material_library(self, filename):
        material = None
        file = self.open_material_file(filename)

        for line in file:
            if line.startswith('#'):
                continue
            values = line.split()
            if not values:
                continue

            if values[0] == 'newmtl':
                material = Material(values[1])
                self.materials[material.name] = material
            elif material is None:
                warnings.warn('Expected "newmtl" in %s' % filename)
                continue

            try:
                if values[0] == 'Kd':
                    material.diffuse = list(map(float, values[1:]))
                elif values[0] == 'Ka':
                    material.ambient = list(map(float, values[1:]))
                elif values[0] == 'Ks':
                    material.specular = list(map(float, values[1:]))
                elif values[0] == 'Ke':
                    material.emissive = list(map(float, values[1:]))
                elif values[0] == 'Ns':
                    material.shininess = float(values[1])
                elif values[0] == 'd':
                    material.opacity = float(values[1])
                elif values[0] == 'map_Kd':
                    try:
                        material.texture = image.load(values[1]).texture
                    except image.ImageDecodeException:
                        warnings.warn('Could not load texture %s' % values[1])
            except:
                warnings.warn('Parse error in %s.' % filename) 
Example 37
Source File: util.py    From shadowsocks with Apache License 2.0 5 votes vote down vote up
def load_library(path, search_symbol, library_name):
    from ctypes import CDLL
    try:
        lib = CDLL(path)
        if hasattr(lib, search_symbol):
            logging.info('loading %s from %s', library_name, path)
            return lib
        else:
            logging.warn('can\'t find symbol %s in %s', search_symbol,
                         path)
    except Exception:
        pass
    return None 
Example 38
Source File: library.py    From dashman with MIT License 5 votes vote down vote up
def load_library():
    if os.getenv("PYCOIN_NATIVE") != "openssl":
        return None
    library_path = ctypes.util.find_library("crypto")
    if library_path is None:
        return None

    library = ctypes.CDLL(library_path)

    library.BignumType = bignum_type_for_library(library)

    BN_P = ctypes.POINTER(library.BignumType)
    BN_CTX = ctypes.POINTER(BignumContext)

    BIGNUM_API = [
        ("BN_init", [BN_P], None),
        ("BN_new", [], BN_P),
        ("BN_set_word", [BN_P, ctypes.c_ulong], ctypes.c_int),
        ("BN_clear_free", [BN_P], None),
        ("BN_bin2bn", [ctypes.c_char_p, ctypes.c_int, BN_P], BN_P),
        ("BN_mod_inverse", [BN_P, BN_P, BN_P, BN_CTX], BN_P),
        ("BN_CTX_new", [], BN_CTX),
        ("BN_CTX_free", [BN_CTX], None),
        ("BN_mpi2bn", [ctypes.c_char_p, ctypes.c_int, BN_P], BN_P),
    ]

    ECC_API = [
        ("EC_GROUP_new_by_curve_name", [ctypes.c_int], ctypes.c_void_p),
        ("EC_POINT_new", [ctypes.c_void_p], ctypes.c_void_p),  # TODO: make this a EC_POINT type
        ("EC_POINT_free", [ctypes.c_void_p], None),
        ("EC_POINT_set_affine_coordinates_GFp",
            [ctypes.c_void_p, ctypes.c_void_p, BN_P, BN_P, BN_CTX], ctypes.c_int),
        ("EC_POINT_get_affine_coordinates_GFp",
            [ctypes.c_void_p, ctypes.c_void_p, BN_P, BN_P, BN_CTX], ctypes.c_int),
        ("EC_POINT_mul",
            [ctypes.c_void_p, ctypes.c_void_p, BN_P, ctypes.c_void_p, BN_P, BN_CTX], ctypes.c_int),
    ]
    set_api(library, BIGNUM_API)
    set_api(library, ECC_API)
    return library 
Example 39
Source File: clr.py    From PyESAPI with MIT License 5 votes vote down vote up
def LoadTypeLibrary(rcw): # real signature unknown; restored from __doc__
    # type: (rcw: object) -> ComTypeLibInfo

    """
    LoadTypeLibrary(rcw: object) -> ComTypeLibInfo

    LoadTypeLibrary(typeLibGuid: Guid) -> ComTypeLibInfo
    """
    pass 
Example 40
Source File: common.py    From gmusic-playlist with MIT License 5 votes vote down vote up
def load_personal_library():
    plog('Loading personal library... ')
    plib = api.get_all_songs()
    log('done. '+str(len(plib))+' personal tracks loaded.')
    return plib

# opens the log for writing