Parses STAR-Fusion format and returns an Expando object with basic features

    :param str infile: path to STAR-Fusion prediction file
    :return: Fusion prediction attributes
    :rtype: bd2k.util.expando.Expando
554624
def parse_star_fusion(infile):
    
    reader = csv.reader(infile, delimiter='\t')
    header = reader.next()
    header = {key: index for index, key in enumerate(header)}

    features = ['LeftGene', 'LeftLocalBreakpoint', 'LeftBreakpoint',
                'RightGene', 'RightLocalBreakpoint', 'RightBreakpoint',
                'LargeAnchorSupport', 'JunctionReadCount', 'SpanningFragCount']

    for line in reader:
        yield Expando(dict((feature, line[header[feature]]) for feature in features))
803901
def from_file(file)
      check_read_only

      if file && File.exist?(file)
        file = File.expand_path(file)
        RubyUtils.loadPropertiesFile(spark_conf, file)
      end
    end
1151063
def read_sources_from_numpy_file(npfile):
    
    srcs = np.load(npfile).flat[0]['sources']

    roi = ROIModel()
    roi.load_sources(srcs.values())
    return roi.create_table()
398956
def infer_delimiter(filename, comment_char="#", n_lines=3):
    
    lines = []
    with open(filename, "r") as f:
        for line in f:
            if line.startswith(comment_char):
                continue
            if len(lines) < n_lines:
                lines.append(line)
            else:
                break
    if len(lines) < n_lines:
        raise ValueError(
            "Not enough lines in %s to infer delimiter" % filename)
    candidate_delimiters = ["\t", ",", "\s+"]
    for candidate_delimiter in candidate_delimiters:
        counts = [len(re.split(candidate_delimiter, line)) for line in lines]
        first_line_count = counts[0]
        if all(c == first_line_count for c in counts) and first_line_count > 1:
            return candidate_delimiter
    raise ValueError("Could not determine delimiter for %s" % filename)
230201
def extract_images_from_tscube(infile, outfile):
    
    inhdulist = fits.open(infile)
    wcs = pywcs.WCS(inhdulist[0].header)
    map_shape = inhdulist[0].data.shape

    t_eng = Table.read(infile, "EBOUNDS")
    t_scan = Table.read(infile, "SCANDATA")
    t_fit = Table.read(infile, "FITDATA")

    n_ebin = len(t_eng)
    energies = np.ndarray((n_ebin + 1))
    energies[0:-1] = t_eng["E_MIN"]
    energies[-1] = t_eng["E_MAX"][-1]

    cube_shape = (n_ebin, map_shape[1], map_shape[0])

    wcs_cube = wcs_utils.wcs_add_energy_axis(wcs, energies)

    outhdulist = [inhdulist[0], inhdulist["EBOUNDS"]]

    FIT_COLNAMES = ['FIT_TS', 'FIT_STATUS', 'FIT_NORM',
                    'FIT_NORM_ERR', 'FIT_NORM_ERRP', 'FIT_NORM_ERRN']
    SCAN_COLNAMES = ['TS', 'BIN_STATUS', 'NORM', 'NORM_UL',
                     'NORM_ERR', 'NORM_ERRP', 'NORM_ERRN', 'LOGLIKE']

    for c in FIT_COLNAMES:
        data = t_fit[c].data.reshape(map_shape)
        hdu = fits.ImageHDU(data, wcs.to_header(), name=c)
        outhdulist.append(hdu)

    for c in SCAN_COLNAMES:
        data = t_scan[c].data.swapaxes(0, 1).reshape(cube_shape)
        hdu = fits.ImageHDU(data, wcs_cube.to_header(), name=c)
        outhdulist.append(hdu)

    hdulist = fits.HDUList(outhdulist)
    hdulist.writeto(outfile, clobber=True)
    return hdulist
1247007
public static void convert(String inFile, String outFile)
                    throws IOException, org.nd4j.linalg.exception.ND4JIllegalStateException {
        SameDiff tg = TFGraphMapper.getInstance().importGraph(new File(inFile));
        tg.asFlatFile(new File(outFile));
    }
1338456
def import_file(filename, name=None):
    
    # Specifying a traditional dot-separated fully qualified name here
    # results in a number of "Parent module 'astropy' not found while
    # handling absolute import" warnings.  Using the same name, the
    # namespaces of the modules get merged together.  So, this
    # generates an underscore-separated name which is more likely to
    # be unique, and it doesn't really matter because the name isn't
    # used directly here anyway.
    mode = 'r'

    if name is None:
        basename = os.path.splitext(filename)[0]
        name = '_'.join(os.path.relpath(basename).split(os.sep)[1:])

    if not os.path.exists(filename):
        raise ImportError('Could not import file {0}'.format(filename))

    if import_machinery:
        loader = import_machinery.SourceFileLoader(name, filename)
        mod = loader.load_module()
    else:
        with open(filename, mode) as fd:
            mod = imp.load_module(name, fd, filename, ('.py', mode, 1))

    return mod
1271816
def from_bubble_file(bblfile:str, oriented:bool=False,
                          symmetric_edges:bool=True) -> 'BubbleTree':
        
        return BubbleTree.from_bubble_data(utils.data_from_bubble(bblfile),
                                           oriented=bool(oriented),
                                           symmetric_edges=symmetric_edges)
750270
def convert(self, infile, item=None):
        
        if not os.path.isfile(infile):
            raise IOError('{} is not a valid file'.format(infile))

        if item is None:
            item = os.path.splitext(infile)[0]

        ext = os.path.splitext(infile)[1]
        if ext == '.npz':
            self.npz_convert(infile, item)
        elif ext == '.mat':
            self.mat_convert(infile, item)
        elif ext == '.h5':
            self.h5features_convert(infile)
        else:
            raise IOError('Unknown file format for {}'.format(infile))
1156256
def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None):
    
    lineno = lineno - 1
    lower_bound = max(0, lineno - context_lines)
    upper_bound = lineno + context_lines

    source = None
    if loader is not None and hasattr(loader, "get_source"):
        result = get_source_lines_from_loader(loader, module_name, lineno, lower_bound, upper_bound)
        if result is not None:
            return result

    if source is None:
        try:
            with open(filename, "rb") as file_obj:
                encoding = "utf8"
                # try to find encoding of source file by "coding" header
                # if none is found, utf8 is used as a fallback
                for line in itertools.islice(file_obj, 0, 2):
                    match = _coding_re.search(line.decode("utf8"))
                    if match:
                        encoding = match.group(1)
                        break
                file_obj.seek(0)
                lines = [
                    compat.text_type(line, encoding, "replace")
                    for line in itertools.islice(file_obj, lower_bound, upper_bound + 1)
                ]
                offset = lineno - lower_bound
                return (
                    [l.strip("\r\n") for l in lines[0:offset]],
                    lines[offset].strip("\r\n"),
                    [l.strip("\r\n") for l in lines[offset + 1 :]] if len(lines) > offset else [],
                )
        except (OSError, IOError, IndexError):
            pass
    return None, None, None
662064
def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None):
        
        source = None
        if loader is not None and hasattr(loader, "get_source"):
            try:
                source = loader.get_source(module_name)
            except ImportError:
                pass
            if source is not None:
                source = source.splitlines()
        if source is None:
            try:
                with open(filename, 'rb') as fp:
                    source = fp.read().splitlines()
            except (OSError, IOError):
                pass
        if source is None:
            return None, [], None, []

        # If we just read the source from a file, or if the loader did not
        # apply tokenize.detect_encoding to decode the source into a Unicode
        # string, then we should do that ourselves.
        if isinstance(source[0], six.binary_type):
            encoding = 'ascii'
            for line in source[:2]:
                # File coding may be specified. Match pattern from PEP-263
                # (http://www.python.org/dev/peps/pep-0263/)
                match = re.search(br'coding[:=]\s*([-\w.]+)', line)
                if match:
                    encoding = match.group(1).decode('ascii')
                    break
            source = [six.text_type(sline, encoding, 'replace') for sline in source]

        lower_bound = max(0, lineno - context_lines)
        upper_bound = lineno + context_lines

        pre_context = source[lower_bound:lineno]
        context_line = source[lineno]
        post_context = source[lineno + 1:upper_bound]

        return lower_bound, pre_context, context_line, post_context
1067219
def generate_lines(self, infile):
        
        pound = '#'
        
        for line in infile:

            heading = self.hash_count(line)

            indent = self.hash_count(line, pound=' ')

            yield dict(line=line.strip(),
                       heading=heading,
                       indent=indent)
1276866
def expand_star(mod_name):
    
    expanded = []
    mod_dir = os.path.dirname(
        __import__(mod_name[:-2], {}, {}, ['']).__file__)
    for f in glob.glob1(mod_dir, "[!_]*.py"):
        expanded.append('%s.%s' % (mod_name[:-2], f[:-3]))
    return expanded
881402
def hydra_parser(in_file, options=None):
    
    if options is None: options = {}
    BedPe = namedtuple('BedPe', ["chrom1", "start1", "end1",
                                 "chrom2", "start2", "end2",
                                 "name", "strand1", "strand2",
                                 "support"])
    with open(in_file) as in_handle:
        reader = csv.reader(in_handle, dialect="excel-tab")
        for line in reader:
            cur = BedPe(line[0], int(line[1]), int(line[2]),
                        line[3], int(line[4]), int(line[5]),
                        line[6], line[8], line[9],
                        float(line[18]))
            if cur.support >= options.get("min_support", 0):
                yield cur
119099
def proc_file(infile: str, outfile: str, opts: Namespace) -> bool:
    
    g = fhir_json_to_rdf(infile, opts.uribase, opts.graph, add_ontology_header=not opts.noontology,
                         do_continuations=not opts.nocontinuation, replace_narrative_text=bool(opts.nonarrative),
                         metavoc=opts.fhir_metavoc)

    # If we aren't carrying graph in opts, we're doing a file by file transformation
    if g:
        if not opts.graph:
            serialize_graph(g, outfile, opts)
        return True
    else:
        print("{} : Not a FHIR collection or resource".format(infile))
        return False
247668
def metamodel_from_file(file_name, **kwargs):
    
    with codecs.open(file_name, 'r', 'utf-8') as f:
        lang_desc = f.read()

    metamodel = metamodel_from_str(lang_desc=lang_desc,
                                   file_name=file_name,
                                   **kwargs)

    return metamodel
934685
def inis2dict(ini_paths: Union[str, Sequence[str]]) -> dict:
    

    var_dflt = r'\${(.*?):-(.*?)}'
    def _interpolate(content):
        rv = expandvars(content)
        while True:
            match = re.search(var_dflt, rv)
            if match is None:
                break
            bash_var = '${{{}}}'.format(match.group(1))
            value = expandvars(bash_var)
            rv = re.sub(var_dflt, match.group(2) if value == bash_var else value, rv, count=1)

        return rv

    parser = ConfigParser()

    for ini in [ini_paths] if isinstance(ini_paths, str) else ini_paths:
        if not isfile(ini):
            raise FileNotFoundError('No such file: {}'.format(ini))
        with open(ini, 'r') as ini_fh:
            ini_text = _interpolate(ini_fh.read())
            parser.read_string(ini_text)

    return {s: dict(parser[s].items()) for s in parser.sections()}