This function reads the CLAM Data from an XML file. Use this to read
    the clam.xml file from your system wrapper. It returns a CLAMData instance.

    If you make use of CUSTOM_FORMATS, you need to pass the CUSTOM_FORMATS list as 2nd argument.
421453
def getclamdata(filename, custom_formats=None):
    global CUSTOM_FORMATS  #pylint: disable=global-statement
    
    f = io.open(filename,'r',encoding='utf-8')
    xml = f.read(os.path.getsize(filename))
    f.close()
    if custom_formats:
        CUSTOM_FORMATS = custom_formats #dependency injection for CUSTOM_FORMATS
    return CLAMData(xml, None, True)
13065
def read_xml(cls, url, markup, game):
        
        return Players._read_objects(MlbamUtil.find_xml("".join([url, cls.FILENAME]), markup) ,game)
277520
function parseBamHeader(r) {
        if (!r) {
            return callback(null, "Couldn't access BAM");
        }

        var unc = unbgzf(r, r.byteLength);
        var uncba = new Uint8Array(unc);

        var magic = readInt(uncba, 0);
        if (magic != BAM_MAGIC) {
            return callback(null, "Not a BAM file, magic=0x" + magic.toString(16));
        }
        var headLen = readInt(uncba, 4);
        var header = '';
        for (var i = 0; i < headLen; ++i) {
            header += String.fromCharCode(uncba[i + 8]);
        }

        var nRef = readInt(uncba, headLen + 8);
        var p = headLen + 12;

        bam.chrToIndex = {};
        bam.indexToChr = [];
        for (var i = 0; i < nRef; ++i) {
            var lName = readInt(uncba, p);
            var name = '';
            for (var j = 0; j < lName-1; ++j) {
                name += String.fromCharCode(uncba[p + 4 + j]);
            }
            var lRef = readInt(uncba, p + lName + 4);
            bam.chrToIndex[name] = i;
            if (name.indexOf('chr') == 0) {
                bam.chrToIndex[name.substring(3)] = i;
            } else {
                bam.chrToIndex['chr' + name] = i;
            }
            bam.indexToChr.push(name);

            p = p + 8 + lName;
        }

        if (bam.indices) {
            return callback(bam);
        }
    }
1124718
def _internalParse(self, readDataInstance):
        
        self.dosHeader = DosHeader.parse(readDataInstance)
        
        self.dosStub = readDataInstance.read(self.dosHeader.e_lfanew.value - readDataInstance.offset)
        self.ntHeaders = NtHeaders.parse(readDataInstance)
        
        if self.ntHeaders.optionalHeader.magic.value == consts.PE32:
            self.PE_TYPE = consts.PE32
        elif self.ntHeaders.optionalHeader.magic.value == consts.PE64:
            self.PE_TYPE = consts.PE64
            readDataInstance.setOffset(readDataInstance.tell() - OptionalHeader().sizeof())
            self.ntHeaders.optionalHeader = OptionalHeader64.parse(readDataInstance)
            
        self.sectionHeaders = SectionHeaders.parse(readDataInstance,  self.ntHeaders.fileHeader.numberOfSections.value)

        # as padding is possible between the last section header and the beginning of the first section
        # we must adjust the offset in readDataInstance to point to the first byte of the first section.
        readDataInstance.setOffset(self.sectionHeaders[0].pointerToRawData.value)
        
        self.sections = Sections.parse(readDataInstance,  self.sectionHeaders)
        
        self.overlay = self._getOverlay(readDataInstance,  self.sectionHeaders)
        self.signature = self._getSignature(readDataInstance,  self.ntHeaders.optionalHeader.dataDirectory)
        
        if not self._fastLoad:
            self._parseDirectories(self.ntHeaders.optionalHeader.dataDirectory, self.PE_TYPE)
775348
def _read_cmap(self):
        

        try:
            i = 0
            colormap = {0: (0, 0, 0)}
            with open(settings.COLORMAP) as cmap:
                lines = cmap.readlines()
                for line in lines:
                    if i == 0 and 'mode = ' in line:
                        i = 1
                        maxval = float(line.replace('mode = ', ''))
                    elif i > 0:
                        str = line.split()
                        if str == []:  # when there are empty lines at the end of the file
                            break
                        colormap.update(
                            {
                                i: (int(round(float(str[0]) * 255 / maxval)),
                                    int(round(float(str[1]) * 255 / maxval)),
                                    int(round(float(str[2]) * 255 / maxval)))
                            }
                        )
                        i += 1
        except IOError:
            pass

        self.cmap = {k: v[:4] for k, v in colormap.items()}
1164698
def get_parsed_data(fn, *args, **kwargs):
    
    file_format = detect_format(fn, *args, **kwargs)
    data = get_header(fn, file_format, *args, **kwargs)
    parsed_data = parse_header(data, *args, **kwargs)
    return parsed_data
1020977
public Toml read(File file) {
    try {
      return read(new InputStreamReader(new FileInputStream(file), "UTF8"));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
1291865
def fromxml(node, file=None):
        """"""
        if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
            node = parsexmlstring(node)
        if node.tag == 'CLAMMetaData':
            dataformat = node.attrib['format']

            formatclass = None
            for C in CUSTOM_FORMATS: #CUSTOM_FORMATS will be injected by clamservice.py
                if C.__name__ == dataformat:
                    formatclass = C
                    break
            if formatclass is None and dataformat in vars(clam.common.formats) and issubclass(vars(clam.common.formats)[dataformat], CLAMMetaData):
                formatclass = vars(clam.common.formats)[dataformat]
            if formatclass is None:
                raise Exception("Format class " + dataformat + " not found!")

            data = {}
            if 'inputtemplate' in node.attrib:
                data['inputtemplate'] = node.attrib['inputtemplate']
            if 'inputtemplatelabel' in node.attrib:
                data['inputtemplatelabel'] = node.attrib['inputtemplatelabel']



            for subnode in node:
                if subnode.tag == 'meta':
                    key = subnode.attrib['id']
                    value = subnode.text
                    data[key] = value
                elif subnode.tag == 'provenance':
                    data['provenance'] = CLAMProvenanceData.fromxml(subnode)
            return formatclass(file, **data)
        else:
            raise Exception("Invalid CLAM Metadata!")
687097
def load_data(handle, reader=None):
    ''''''
    if not reader:
        reader = os.path.splitext(handle)[1][1:].lower()

    if reader not in _READERS:
        raise NeuroMError('Do not have a loader for "%s" extension' % reader)

    filename = _get_file(handle)
    try:
        return _READERS[reader](filename)
    except Exception as e:
        L.exception('Error reading file %s, using "%s" loader', filename, reader)
        raise RawDataError('Error reading file %s:\n%s' % (filename, str(e)))
1260536
public AbstractDescriptor read( File descriptorFile , Class<? extends AbstractXMLDescriptorHandler> handlerClass ) throws JMSException
    {
        if (!descriptorFile.canRead())
            throw new FFMQException("Can't read descriptor file : "+descriptorFile.getAbsolutePath(),"FS_ERROR");
        
        log.debug("Parsing descriptor : "+descriptorFile.getAbsolutePath());
        
        AbstractXMLDescriptorHandler handler;
        try
        {
            // Create an handler instance
            handler = handlerClass.newInstance();
            
            // Parse the descriptor file
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            FileInputStream in = new FileInputStream(descriptorFile);
            parser.parse(in,handler);
            in.close();
        }
        catch (Exception e)
        {
            throw new FFMQException("Cannot parse descriptor file : "+descriptorFile.getAbsolutePath(),"PARSE_ERROR",e);
        }
        
        AbstractDescriptor descriptor = handler.getDescriptor();
        descriptor.setDescriptorFile(descriptorFile);

        return descriptor;
    }
464105
def from_file( cls, filename ):
        
        with open( filename, 'r' ) as stream:
            data = yaml.load( stream, Loader=yaml.SafeLoader )
            notes = data.get( 'notes' )
            v_type = data.get( 'type' )
            track = data.get( 'track' )
            xargs = {}
            if track:
                if type( track ) is str:
                    track = [ track ]
                xargs['track'] = track 
            vaspmeta = VASPMeta( data['title'], 
                                 data['description'], 
                                 data['status'], 
                                 notes=notes, 
                                 type=v_type,
                                 **xargs )
        return vaspmeta
738265
def parse(data)
      if !data.respond_to?(:read)
        data = StringIO.new(data || "")
      end

      if data.eof?
        {}
      else
        LibXML::XML::Parser.io(data).parse.to_hash
      end
    end
474198
def readstoredmetadata(fname, skiprows=0, linenumber=None, comments='#', 
                       metametadata=None, verbosity=DEFAULT_VERBOSITY):
    
    if is_string_like(fname):
        fh = file(fname, 'rU')
    elif hasattr(fname, 'readline'):
        fh = fname
    else:
        raise ValueError('fname must be a string or file handle')
       
    if not metametadata:
        for _ind in range(skiprows):
            fh.readline()

        phlines = []
        if linenumber is None:
            if comments:
                for line in fh:
                    if not line.startswith(comments):
                        if len(phlines) == 0:
                            phlines = [line]
                        break
                    else:
                        phlines.append(line)
                if len(phlines) == 1:
                    if verbosity >= 10:
                        print '''Looking for metametadata on line 0 
                                 (no comment lines present).'''
                else:
                    if verbosity >= 9:
                        print '''Searching for metametadata lines up to 
                                 and including line %d where comments 
                                 end.''' % (len(phlines) - 1)
            else:
                phlines = [fh.readline()]
                if verbosity >=9:
                    print '''No comments found, looking for metametadata on 
                             line 0.'''
        else:
            for _ind in range(linenumber):
                fh.readline()
            phlines = [fh.readline()]
                               
        metametadata = None
        for (ln, metametaline) in enumerate(phlines):
            s = re.compile(r'metametadata[\s]*=[\s]*{').search(metametaline)
            if s:
                l = s.start()
                if len(uniqify(metametaline[:l])) <= 1:
                    metametaline = metametaline[l:].rstrip()
                    try:
                        X = compiler.parse(metametaline)
                    except SyntaxError:
                        pass
                    else:
                        if IsMetaMetaDict(X):
                            exec metametaline
                            if verbosity > 6:
                                print 'Found valid metametadata at line', ln, 'in file.  Metametadata is:', metametadata
                            break
   
    if metametadata:
        
        metadata = {}
        metadata['metametadata'] = metametadata
        Tval = max([v if isinstance(v,int) else max(v) 
                    for v in metametadata.values()])
        fh = file(fname, 'rU')
        data = [fh.readline() for _ind in range(Tval + 1 + skiprows)][skiprows:]
 
        if (max([v if isinstance(v,int) else max(v) 
                for v in  metametadata.values()]) < len(data)):
            for n in metametadata.keys():
                [s, e] = [metametadata[n], metametadata[n]+1] \
                          if isinstance(metametadata[n],int) \
                          else [metametadata[n][0],metametadata[n][1]]
                metadata[n] = ''.join(data[s:e]).strip('\n')
            processmetadata(metadata, comments=comments, verbosity=verbosity)
        
            return metadata
699073
static BlockMetadataHeader readHeader(File file) throws IOException {
    DataInputStream in = null;
    try {
      in = new DataInputStream(new BufferedInputStream(
                               new FileInputStream(file)));
      return readHeader(in);
    } finally {
      IOUtils.closeStream(in);
    }
  }
1144622
def scan (data, clamconf):
    
    try:
        scanner = ClamdScanner(clamconf)
    except socket.error:
        errmsg = _("Could not connect to ClamAV daemon.")
        return ([], [errmsg])
    try:
        scanner.scan(data)
    finally:
        scanner.close()
    return scanner.infected, scanner.errors
211406
def read_xml(self):
        
        with reading_ancillary_files(self):
            root = super(GenericLayerMetadata, self).read_xml()

        return root
503422
def read_xml_file(self, xml_file):
        

        assert self.__config is not None

        ffname = self.__file_full_name(xml_file)
        self.logger.debug("Reading xml file: [%s]", xml_file)
        decls = self.__dcache.cached_value(ffname, self.__config)
        if not decls:
            self.logger.debug("File has not been found in cache, parsing...")
            decls, _ = self.__parse_xml_file(ffname)
            self.__dcache.update(ffname, self.__config, decls, [])
        else:
            self.logger.debug(
                "File has not been changed, reading declarations from cache.")

        return decls