Inserts a new LC_LOAD_DYLIB load command into the target Mach-O header.
	
	Note: the target file will be overwritten. Consider backing it up first before calling this function.
	Returns True if everything is OK. Otherwise rises an exception.
435593
def insert_load_command(target_path, library_install_name):
	
	def patchHeader(t):
		load_command = generate_dylib_load_command(t, library_install_name)
		return insert_load_command_into_header(t, load_command)
		
	return modify_macho_file_headers(target_path, patchHeader)
476321
def install_readline(hook):
    ''''''
    global readline_hook, readline_ref
    # save the hook so the wrapper can call it
    readline_hook = hook
    # get the address of PyOS_ReadlineFunctionPointer so we can update it
    PyOS_RFP = c_void_p.from_address(Console.GetProcAddress(sys.dllhandle,
                                            "PyOS_ReadlineFunctionPointer"))
    # save a reference to the generated C-callable so it doesn't go away
    if sys.version < '2.3':
        readline_ref = HOOKFUNC22(hook_wrapper)
    else:
        readline_ref = HOOKFUNC23(hook_wrapper_23)
    # get the address of the function
    func_start = c_void_p.from_address(addressof(readline_ref)).value
    # write the function address into PyOS_ReadlineFunctionPointer
    PyOS_RFP.value = func_start
981264
def _is_target_valid(self, cfg, target):  # pylint:disable=no-self-use
        

        if self.base_state is not None:
            try:
                if self.base_state.solver.is_true((self.base_state.memory.permissions(target) & 4) == 4):
                    return True
            except SimMemoryError:
                pass
            return False

        if cfg._addr_in_exec_memory_regions(target):
            # the jump target is executable
            return True
        if self.project.is_hooked(target):
            # the jump target is hooked
            return True
        return False
508546
def _add_umis_with_fastp(read_fq, umi_fq, out_fq, cores):
    
    with utils.open_gzipsafe(umi_fq) as in_handle:
        in_handle.readline()  # name
        umi_size = len(in_handle.readline().strip())
    cmd = ("fastp -Q -A -L -G -w 1 --in1 {read_fq} --in2 {umi_fq} "
           "--umi --umi_prefix UMI --umi_loc read2 --umi_len {umi_size} "
           "--out1 >(bgzip --threads {cores} -c > {out_fq}) --out2 /dev/null "
           "-j /dev/null -h /dev/null")
    do.run(cmd.format(**locals()), "Add UMIs to fastq file with fastp")
614277
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
                                                     String targetFolder) {
        String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
        // Include architecture name in temporary filename in order to avoid conflicts
        // when multiple JVMs with different architectures running at the same time
        String uuid = UUID.randomUUID().toString();
        String extractedLibFileName = String.format("secp256k1-%s-%s", uuid, libraryFileName);
        String extractedLckFileName = extractedLibFileName + ".lck";

        File extractedLibFile = new File(targetFolder, extractedLibFileName);
        File extractedLckFile = new File(targetFolder, extractedLckFileName);

        try {
            // Extract a native library file into the target directory
            InputStream reader = Secp256k1Loader.class.getResourceAsStream(nativeLibraryFilePath);
            if(!extractedLckFile.exists()) {
                new FileOutputStream(extractedLckFile).close();
            }
            FileOutputStream writer = new FileOutputStream(extractedLibFile);
            try {
                byte[] buffer = new byte[8192];
                int bytesRead = 0;
                while((bytesRead = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, bytesRead);
                }
            }
            finally {
                // Delete the extracted lib file on JVM exit.
                extractedLibFile.deleteOnExit();
                extractedLckFile.deleteOnExit();


                if(writer != null) {
                    writer.close();
                }
                if(reader != null) {
                    reader.close();
                }
            }

            // Set executable (x) flag to enable Java to load the native library
            extractedLibFile.setReadable(true);
            extractedLibFile.setWritable(true, true);
            extractedLibFile.setExecutable(true);

            // Check whether the contents are properly copied from the resource folder
            {
                InputStream nativeIn = Secp256k1Loader.class.getResourceAsStream(nativeLibraryFilePath);
                InputStream extractedLibIn = new FileInputStream(extractedLibFile);
                try {
                    if(!contentsEquals(nativeIn, extractedLibIn)) {
                        throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile));
                    }
                }
                finally {
                    if(nativeIn != null) {
                        nativeIn.close();
                    }
                    if(extractedLibIn != null) {
                        extractedLibIn.close();
                    }
                }
            }
            return loadNativeLibrary(targetFolder, extractedLibFileName);
        }
        catch(IOException e) {
            System.err.println(e.getMessage());
            return false;
        }

    }
76842
public boolean addSourceFile(FileSystem fs, PolicyInfo info, FileStatus src,
      RaidState.Checker checker, long now, int targetReplication) 
          throws IOException {
    
    List<FileStatus> lfs = RaidNode.listDirectoryRaidFileStatus(
                    fs.getConf(), fs, src.getPath()); 
    if (lfs == null) {
      return false;
    }
    RaidState state = checker.check(info, src, now, false, lfs);
    Counters counters = stateToSourceCounters.get(state);
    counters.inc(lfs);
    if (state == RaidState.RAIDED) {
      long paritySize = computeParitySize(lfs, targetReplication);
      estimatedParitySize += paritySize;
      estimatedDoneParitySize += paritySize;
      estimatedDoneSourceSize += DirectoryStripeReader.getDirPhysicalSize(lfs);
      return false;
    }
    if (state == RaidState.NOT_RAIDED_BUT_SHOULD) {
      estimatedDoneParitySize += computeParitySize(lfs, targetReplication);
      estimatedDoneSourceSize += DirectoryStripeReader.getDirPhysicalSize(lfs);
      return true;
    }
    return false;
  }
572069
def _open_target_files(self):
        '''
        
        '''
        # Validate the target files listed in target_files
        for tfile in self.files:
            # Ignore directories.
            if not self.subclass == io.FileIO or not os.path.isdir(tfile):
                # Make sure we can open the target files
                try:
                    fp = self.open_file(tfile)
                    fp.close()
                    self.target_files.append(tfile)
                except KeyboardInterrupt as e:
                    raise e
                except Exception as e:
                    self.error(description="Cannot open file %s (CWD: %s) : %s" % (tfile, os.getcwd(), str(e)))
548911
def add(self, name, monitor=True):
        

        if os.path.isdir(name):
            if (not os.path.basename(name).startswith(".")):
                self.add_folder(name)

        elif os.path.isfile(name):
            if ((self._looks_like_resource_file(name)) or
                (self._looks_like_libdoc_file(name)) or
                (self._looks_like_library_file(name))):
                self.add_file(name)
        else:
            # let's hope it's a library name!
            self.add_library(name)
183828
def load(self, cachedir=None, cfgstr=None, fpath=None, verbose=None,
             quiet=QUIET, ignore_keys=None):
        
        if verbose is None:
            verbose = getattr(self, 'verbose', VERBOSE)
        if fpath is None:
            fpath = self.get_fpath(cachedir, cfgstr=cfgstr)
        if verbose:
            print('[Cachable] cache tryload: %r' % (basename(fpath),))
        try:
            self._unsafe_load(fpath, ignore_keys)
            if verbose:
                print('... self cache hit: %r' % (basename(fpath),))
        except ValueError as ex:
            import utool as ut
            msg = '[!Cachable] Cachable(%s) is likely corrupt' % (self.get_cfgstr())
            print('CORRUPT fpath = %s' % (fpath,))
            ut.printex(ex, msg, iswarning=True)
            raise
        #except BadZipFile as ex:
        except zipfile.error as ex:
            import utool as ut
            msg = '[!Cachable] Cachable(%s) has bad zipfile' % (self.get_cfgstr())
            print('CORRUPT fpath = %s' % (fpath,))
            ut.printex(ex, msg, iswarning=True)
            raise
            #if exists(fpath):
            #    #print('[Cachable] Removing corrupted file: %r' % fpath)
            #    #os.remove(fpath)
            #    raise hsexcept.HotsNeedsRecomputeError(msg)
            #else:
            #    raise Exception(msg)
        except IOError as ex:
            import utool as ut
            if not exists(fpath):
                msg = '... self cache miss: %r' % (basename(fpath),)
                if verbose:
                    print(msg)
                raise
            print('CORRUPT fpath = %s' % (fpath,))
            msg = '[!Cachable] Cachable(%s) is corrupt' % (self.get_cfgstr())
            ut.printex(ex, msg, iswarning=True)
            raise
        except Exception as ex:
            import utool as ut
            ut.printex(ex, 'unknown exception while loading query result')
            raise
709663
def add_rel(self, source_id, target_id, rel):
        '''  '''
        if (source_id, target_id) not in self.rel_cache:
            self.workbench.add_rel(source_id, target_id, rel)
            self.rel_cache.add((source_id, target_id))
209491
def add_load(self, lv_load):
        
        if lv_load not in self._loads and isinstance(lv_load,
                                                     LVLoadDing0):
            self._loads.append(lv_load)
            self.graph_add_node(lv_load)
418740
def check_import_stdlib(module):
        
        if (
            module in stdlib_list('2.7')  # pylint: disable=R0916
            or module in stdlib_list('3.4')
            or module in stdlib_list('3.5')
            or module in stdlib_list('3.6')
            or module in stdlib_list('3.7')
            or module in ['app', 'args', 'playbook_app']
        ):
            return True
        return False
1076135
def fuzzyload(self, cachedir=None, partial_cfgstr='', **kwargs):
        
        valid_targets = self.glob_valid_targets(cachedir, partial_cfgstr)
        if len(valid_targets) != 1:
            import utool as ut
            msg = 'need to further specify target. valid_targets=%s' % (ut.repr3(valid_targets,))
            raise ValueError(msg)
        fpath = valid_targets[0]
        self.load(fpath=fpath, **kwargs)
12596
def load_cache(dpath, fname, cfgstr, ext='.cPkl', verbose=None, enabled=True):
    
    if verbose is None:
        verbose = VERBOSE_CACHE
    if not USE_CACHE or not enabled:
        if verbose > 1:
            print('[util_cache] ... cache disabled: dpath=%s cfgstr=%r' %
                    (basename(dpath), cfgstr,))
        raise IOError(3, 'Cache Loading Is Disabled')
    fpath = _args2_fpath(dpath, fname, cfgstr, ext)
    if not exists(fpath):
        if verbose > 0:
            print('[util_cache] ... cache does not exist: dpath=%r fname=%r cfgstr=%r' % (
                basename(dpath), fname, cfgstr,))
        raise IOError(2, 'No such file or directory: %r' % (fpath,))
    else:
        if verbose > 2:
            print('[util_cache] ... cache exists: dpath=%r fname=%r cfgstr=%r' % (
                basename(dpath), fname, cfgstr,))
        import utool as ut
        nbytes = ut.get_file_nBytes(fpath)
        big_verbose = (nbytes > 1E6 and verbose > 2) or verbose > 2
        if big_verbose:
            print('[util_cache] About to read file of size %s' % (ut.byte_str2(nbytes),))
    try:
        with ut.Timer(fpath, verbose=big_verbose and verbose > 3):
            data = util_io.load_data(fpath, verbose=verbose > 2)
    except (EOFError, IOError, ImportError) as ex:
        print('CORRUPTED? fpath = %s' % (fpath,))
        if verbose > 1:
            print('[util_cache] ... cache miss dpath=%s cfgstr=%r' % (
                basename(dpath), cfgstr,))
        raise IOError(str(ex))
    except Exception:
        print('CORRUPTED? fpath = %s' % (fpath,))
        raise
    else:
        if verbose > 2:
            print('[util_cache] ... cache hit')
    return data
265284
protected int loadLibraryFrom(
      String soName, int loadFlags, File libDir, StrictMode.ThreadPolicy threadPolicy)
      throws IOException {
    File soFile = new File(libDir, soName);
    if (!soFile.exists()) {
      Log.d(SoLoader.TAG, soName + " not found on " + libDir.getCanonicalPath());
      return LOAD_RESULT_NOT_FOUND;
    } else {
      Log.d(SoLoader.TAG, soName + " found on " + libDir.getCanonicalPath());
    }
    if ((loadFlags & LOAD_FLAG_ALLOW_IMPLICIT_PROVISION) != 0 &&
        (flags & ON_LD_LIBRARY_PATH) != 0) {
      Log.d(SoLoader.TAG, soName + " loaded implicitly");
      return LOAD_RESULT_IMPLICITLY_PROVIDED;
    }

    if ((flags & RESOLVE_DEPENDENCIES) != 0) {
      loadDependencies(soFile, loadFlags, threadPolicy);
    } else {
      Log.d(SoLoader.TAG, "Not resolving dependencies for " + soName);
    }

    try {
      SoLoader.sSoFileLoader.load(soFile.getAbsolutePath(), loadFlags);
    } catch (UnsatisfiedLinkError e) {
      if (e.getMessage().contains("bad ELF magic")) {
        Log.d(SoLoader.TAG, "Corrupted lib file detected");
        // Swallow exception. Higher layers will try again from a backup source
        return LOAD_RESULT_CORRUPTED_LIB_FILE;
      } else {
        throw e;
      }
    }

    return LOAD_RESULT_LOADED;
  }
1136259
def add_dir_entry(backup_run, dir_entry_path, process_bar, result):
    
    # print(dir_entry_path.pformat())
    # print(dir_entry_path.stat.st_nlink)

    backup_entry = Path2(dir_entry_path.path)
    filesize = dir_entry_path.stat.st_size
    hash_filepath = Path2("%s%s%s" % (backup_entry.path, os.extsep, phlb_config.hash_name))
    if hash_filepath.is_file():
        with hash_filepath.open("r") as hash_file:
            hash_hexdigest = hash_file.read().strip()
        if filesize > 0:
            process_bar.update(filesize)
    else:
        with hash_filepath.open("w") as hash_file:
            callback = HashCallback(process_bar)
            with backup_entry.open("rb") as f:
                hash = calculate_hash(f, callback)

            hash_hexdigest = hash.hexdigest()
            hash_file.write(hash_hexdigest)

    old_backup_entry = deduplicate(backup_entry, hash_hexdigest)
    if old_backup_entry is None:
        result.add_new_file(filesize)
    else:
        result.add_stined_file(filesize)

    BackupEntry.objects.create(
        backup_run, dir_entry_path.path_instance, hash_hexdigest=hash_hexdigest  # Path2() instance
    )
828352
def load
      load_source_and_set_module
      module_callbacks if @module
      yield if block_given? # load dependencies
      detect_additions { load_commands } if load_commands?
      set_library_commands
      loaded_correctly? && (@loaded = true)
    end