Open an ARF file, creating as necessary.

    Use this instead of h5py.File to ensure that root-level attributes and group
    creation property lists are set correctly.
967942
def open_file(name, mode=None, driver=None, libver=None, userblock_size=None, **kwargs):
    
    import sys
    import os
    from h5py import h5p
    from h5py._hl import files

    try:
        # If the byte string doesn't match the default
        # encoding, just pass it on as-is.  Note Unicode
        # objects can always be encoded.
        name = name.encode(sys.getfilesystemencoding())
    except (UnicodeError, LookupError):
        pass
    exists = os.path.exists(name)
    try:
        fcpl = h5p.create(h5p.FILE_CREATE)
        fcpl.set_link_creation_order(
            h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED)
    except AttributeError:
        # older version of h5py
        fp = files.File(name, mode=mode, driver=driver,
                        libver=libver, **kwargs)
    else:
        fapl = files.make_fapl(driver, libver, **kwargs)
        fp = files.File(files.make_fid(name, mode, userblock_size, fapl, fcpl))

    if not exists and fp.mode == 'r+':
        set_attributes(fp,
                       arf_library='python',
                       arf_library_version=__version__,
                       arf_version=spec_version)
    return fp
1003471
def open_and_parse_yaml(yamlfile):
        

        # ??? what if the yaml file does not contain a dict datastructure?
        mapping = dict()
        if os.path.exists(os.path.join(os.path.dirname(__file__), yamlfile)):
            map_file = open(os.path.join(os.path.dirname(__file__), yamlfile), 'r')
            mapping = yaml.safe_load(map_file)
            map_file.close()
        else:
            LOG.warning("file: %s not found", yamlfile)

        return mapping
795412
def Open(self, file_object):
    
    self._file_object = file_object
    self._regf_file.open_file_object(self._file_object)
    return True
13545
def create_tar_file(source_files, target=None):
    
    if target:
        filename = target
    else:
        _, filename = tempfile.mkstemp()

    with tarfile.open(filename, mode='w:gz') as t:
        for sf in source_files:
            # Add all files from the directory into the root of the directory structure of the tar
            t.add(sf, arcname=os.path.basename(sf))
    return filename
780621
def open_file(file)
      # Check if file already exists:
      if File.exist?(file)
        # Is (the existing file) writable?
        unless File.writable?(file)
          raise "The program does not have permission or resources to create this file: #{file}"
        end
      else
        # File does not exist.
        # Check if this file's path contains a folder that does not exist, and therefore needs to be created:
        folders = file.split(File::SEPARATOR)
        if folders.length > 1
          # Remove last element (which should be the file string):
          folders.pop
          path = folders.join(File::SEPARATOR)
          # Check if this path exists:
          unless File.directory?(path)
            # We need to create (parts of) this path:
            require 'fileutils'
            FileUtils.mkdir_p(path)
          end
        end
      end
      # It has been verified that the file can be created:
      return File.new(file, 'wb:ISO8859-1')
    end
1084426
def new(filename: str, *, file_attrs: Optional[Dict[str, str]] = None) -> LoomConnection:
	
	if filename.startswith("~/"):
		filename = os.path.expanduser(filename)
	if file_attrs is None:
		file_attrs = {}

	# Create the file (empty).
	# Yes, this might cause an exception, which we prefer to send to the caller
	f = h5py.File(name=filename, mode='w')
	f.create_group('/layers')
	f.create_group('/row_attrs')
	f.create_group('/col_attrs')
	f.create_group('/row_graphs')
	f.create_group('/col_graphs')
	f.flush()
	f.close()

	ds = connect(filename, validate=False)
	for vals in file_attrs:
		ds.attrs[vals] = file_attrs[vals]
	# store creation date
	currentTime = time.localtime(time.time())
	ds.attrs['CreationDate'] = timestamp()
	ds.attrs["LOOM_SPEC_VERSION"] = loompy.loom_spec_version
	return ds
1333764
def open(self, create_if_not_found=True):
        
        try:
            self.data = self._read()
        # If the file does
        except FileNotFoundError as e: 
            if create_if_not_found is True:
                self.data = {}
            else: 
                raise e

        # Enforce the following keys exists in data.
        if 'clusters' not in self.data:
            self.data['clusters'] = []
        if 'contexts' not in self.data:
            self.data['clusters'] = []
        if 'users' not in self.data:
            self.data['users'] = []
        if 'apiVersion' not in self.data:
            self.data['apiVersion'] = 'v1'
        if 'kind' not in self.data:
            self.data['kind'] = 'Config'
        if 'preferences' not in self.data:
            self.data['preferences'] = {}
        if 'current-context' not in self.data:
            self.data['current-context'] = ''

        return self
434694
def eval_file(file_path)
      parent_context = IRB.CurrentContext
      new_io = IRB::FileInputMethod.new(File.expand_path(file_path, parent_context.io.file_name))
      new_irb = IRB::Irb.new(parent_context.workspace, new_io)
      new_irb.context.irb_name = File.basename(new_io.file_name)
      new_irb.context.irb_path = new_io.file_name
      IRT::Session.eval_input(new_irb.context, :file)
      IRT::Session.exit
    end
924903
def _open(filename, mode='r', buffering=0):
    """"""
    if mode not in ('r', 'rb', 'rU'):
        raise RuntimeError("Invalid open file mode, must be 'r', 'rb', or 'rU'")
    if buffering > MAX_OPEN_BUFFER:
        raise RuntimeError("Invalid buffering value, max buffer size is {}".format(MAX_OPEN_BUFFER))
    return open(filename, mode, buffering)
557651
def open_fasta_index(self):
        
        index = self.fasta_index
        try:
            handle = open(index, 'rb')
        except (IOError, TypeError):
            sys.stderr.write('index not found, creating it\n')
            try:
                self.build_fasta_index()
                return
            except IOError:
                raise IOError("Index File "+self.fasta_index+"can't be found nor created, check file permissions")
        self.sequence_index = {}
        _seq_dict = self.sequence_index
        for row in handle:
            entry = row.decode('utf-8').strip().split('\t')
            #stored as: {header: length, # of chars to end of this header, length of fasta lines, length of each line including breakchar}
            _seq_dict[entry[0]] = (entry[1], entry[2], entry[3], entry[4])
1049484
def open(self, filename):
        '''  '''
        # Ensure old file is closed before opening a new one
        self.close()

        self._f = open(filename, 'rb')
        self._dbtype = struct.unpack('B', self._f.read(1))[0]
        self._dbcolumn = struct.unpack('B', self._f.read(1))[0]
        self._dbyear = struct.unpack('B', self._f.read(1))[0]
        self._dbmonth = struct.unpack('B', self._f.read(1))[0]
        self._dbday = struct.unpack('B', self._f.read(1))[0]
        self._ipv4dbcount = struct.unpack('<I', self._f.read(4))[0]
        self._ipv4dbaddr = struct.unpack('<I', self._f.read(4))[0]
        self._ipv6dbcount = struct.unpack('<I', self._f.read(4))[0]
        self._ipv6dbaddr = struct.unpack('<I', self._f.read(4))[0]
        self._ipv4indexbaseaddr = struct.unpack('<I', self._f.read(4))[0]
        self._ipv6indexbaseaddr = struct.unpack('<I', self._f.read(4))[0]
811116
def openfile(cls, filepath):
        
        if not os.path.isfile(filepath):
            logger.error("%s.openfile: arg `filepath`=«%s» not valid." % (cls.__name__, filepath))
            return False
        try:
            with open(filepath, "rb") as pf:
                pkldata = pickle.load(pf)
            rootnode = cls(treedict=pkldata)
            rootnode._vnpkl_fpath = os.path.abspath(filepath)
        except Exception as err:
            logger.error("%s.openfile: data in file «%s» not valid: %s" % (cls.__name__, filepath, err))
            return False
        return rootnode
1218080
def create(
    name,

    create_file,
    open_file,
    remove_file,

    create_directory,
    list_directory,
    remove_empty_directory,
    temporary_directory,

    stat,

    lstat,
    link,
    readlink,

    realpath=_realpath,
    remove=_recursive_remove,
):
    

    methods = dict(
        create=create_file,
        open=lambda fs, path, mode="r": open_file(
            fs=fs, path=path, mode=mode,
        ),
        remove_file=remove_file,

        create_directory=create_directory,
        list_directory=list_directory,
        remove_empty_directory=remove_empty_directory,
        temporary_directory=temporary_directory,

        get_contents=_get_contents,
        set_contents=_set_contents,
        create_with_contents=_create_with_contents,

        remove=remove,
        removing=_removing,

        stat=stat,

        lstat=lstat,
        link=link,
        readlink=readlink,
        realpath=realpath,

        exists=_exists,
        is_dir=_is_dir,
        is_file=_is_file,
        is_link=_is_link,

        touch=_touch,

        children=_children,
        glob_children=_glob_children,
    )
    return attr.s(hash=True)(type(name, (object,), methods))
1369430
def create(self):
        
        fdint = os.open(self.path, (os.O_EXCL |
                                    os.O_CREAT |
                                    os.O_RDWR))

        # XXX TODO: 'name' attribute of returned files is not mutable or
        # settable via fdopen, so this file is slighly less functional than the
        # one returned from 'open' by default.  send a patch to Python...

        return os.fdopen(fdint, 'w+b')
489112
def createCorrFile(outfile, arrlist, template):
    
    # Remove the existing cor file if it exists
    if os.path.isfile(outfile):
        os.remove(outfile)
        print("Removing old corr file: '{:s}'".format(outfile))

    with fits.open(template, memmap=False) as ftemplate:
        for arr in arrlist:
            ftemplate[arr['sciext']].data = arr['corrFile']
            if arr['dqext'][0] != arr['sciext'][0]:
                ftemplate[arr['dqext']].data = arr['dqMask']
        ftemplate.writeto(outfile)
        print("Created CR corrected file: '{:s}'".format(outfile))
1041870
def open_mdf(self):
        
        mdf_path = self.mdf_path
        if not mdf_path:
            logger.critical("%s didn't produce a MDF file in %s" % (self, self.outdir))
            return None

        # Open the DFF file and add its data to results.out
        from abipy.electrons.bse import MdfFile
        try:
            return MdfFile(mdf_path)
        except Exception as exc:
            logger.critical("Exception while reading MDF file at %s:\n%s" % (mdf_path, str(exc)))
            return None
975077
def _openResources(self):
        
        logger.info("Opening: {}".format(self._fileName))
        self._ncGroup = Dataset(self._fileName)