Parses a PSAT data file and returns a case object

            file_or_filename: File object or path to PSAT data file
            return: Case object
427004
def read(self, file_or_filename):
        
        self.file_or_filename = file_or_filename

        logger.info("Parsing PSAT case file [%s]." % file_or_filename)

        t0 = time.time()

        self.case = Case()

        # Name the case
        if isinstance(file_or_filename, basestring):
            name, _ = splitext(basename(file_or_filename))
        else:
            name, _ = splitext(file_or_filename.name)

        self.case.name = name

        bus_array = self._get_bus_array_construct()
        line_array = self._get_line_array_construct()
        # TODO: Lines.con - Alternative line data format
        slack_array = self._get_slack_array_construct()
        pv_array = self._get_pv_array_construct()
        pq_array = self._get_pq_array_construct()
        demand_array = self._get_demand_array_construct()
        supply_array = self._get_supply_array_construct()
        # TODO: Varname.bus (Bus names)

        # Pyparsing case:
        case = \
            ZeroOrMore(matlab_comment) + bus_array + \
            ZeroOrMore(matlab_comment) + line_array + \
            ZeroOrMore(matlab_comment) + slack_array + \
            ZeroOrMore(matlab_comment) + pv_array + \
            ZeroOrMore(matlab_comment) + pq_array + \
            ZeroOrMore(matlab_comment) + demand_array + \
            ZeroOrMore(matlab_comment) + supply_array

        case.parseFile(file_or_filename)

        elapsed = time.time() - t0
        logger.info("PSAT case file parsed in %.3fs." % elapsed)

        return self.case
436848
def parse(self, limit=None):
        
        if limit is not None:
            LOG.info("Only parsing first %s rows fo each file", str(limit))

        LOG.info("Parsing files...")

        if self.test_only:
            self.test_mode = True

        # for f in ['impc', 'euro', 'mgd', '3i']:
        for f in ['all']:
            file = '/'.join((self.rawdir, self.files[f]['file']))
            self._process_data(file, limit)

        LOG.info("Finished parsing")

        return
1358565
def read_parfile(parfile):
    
    assert os.path.exists(parfile), "Pst.parrep(): parfile not found: " +\
                                    str(parfile)
    f = open(parfile, 'r')
    header = f.readline()
    par_df = pd.read_csv(f, header=None,
                             names=["parnme", "parval1", "scale", "offset"],
                             sep="\s+")
    par_df.index = par_df.parnme
    return par_df
811597
def parse_file(fname):
        
        try:
            with fopen(fname) as f:
                fstr = f.read()
        except IOError:
            if fname != 'stdin':
                raise
            sys.stdout.write('\nReading from stdin:\n\n')
            fstr = sys.stdin.read()
        fstr = fstr.replace('\r\n', '\n').replace('\r', '\n')
        if not fstr.endswith('\n'):
            fstr += '\n'
        return ast.parse(fstr, filename=fname)
794004
def recognize_file(self, file_path):
        
        file_path = _convert_to_charp(file_path)
        ptr = self._recognize_file_func(self.alpr_pointer, file_path)
        json_data = ctypes.cast(ptr, ctypes.c_char_p).value
        json_data = _convert_from_charp(json_data)
        response_obj = json.loads(json_data)
        self._free_json_mem_func(ctypes.c_void_p(ptr))
        return response_obj
571556
def __get_filedate(self):
        

        if os.access(self.__filename, os.R_OK):

            # Read first line of the file
            try:
                sar_file = open(self.__filename, "r")

            except OSError:
                ### DEBUG
                traceback.print_exc()
                return False

            except:
                ### DEBUG
                traceback.print_exc()
                return False

            firstline = sar_file.readline()
            info = firstline.split()
            sar_file.close()

            try:
                self.__file_date = info[3]

            except KeyError:
                self.__file_date = ''
                return False

            except:
                ### DEBUG
                traceback.print_exc()
                return False

            return True

        return False
387454
def parse_template(input_filename, output_filename=''):
    
    data = load_input()
    with open(input_filename, 'rb') as file:
        template = file.read().decode("utf-8")
    
    # Check if 'input' in data
    if not 'input' in data:
        raise ValueError("Could not find 'input' in data")
    
    # Parse template
    for field in data['input']:
        subs = ["filename", "value"] if isinstance(data['input'][field], dict) and "filename" in data['input'][field] and "value" in data['input'][field] else [""]
        for sub in subs:
            displayed_field = field + (":" if sub else "") + sub
            regex = re.compile("@([^@]*)@" + displayed_field + '@([^@]*)@')
            for prefix, postfix in set(regex.findall(template)):
                if sub == "value":
                    text = open(data['input'][field][sub], 'rb').read().decode('utf-8')
                elif sub:
                    text = data['input'][field][sub]
                else:
                    text = data['input'][field]
                rep = "\n".join([prefix + v + postfix for v in text.splitlines()])
                template = template.replace("@{0}@{1}@{2}@".format(prefix, displayed_field, postfix), rep)
    
    if output_filename == '':
        output_filename=input_filename
    
    # Ensure directory of resulting file exists
    try:
        os.makedirs(os.path.dirname(output_filename))
    except OSError as e:
        pass

    # Write file
    with open(output_filename, 'wb') as file:
        file.write(template.encode("utf-8"))
1238278
def parsefile(self, filename):
        
        with open(filename, 'rb') as fd:
            return self.parse(fd.read())
1260831
def _load_mtdata(gzfile):
    
    path = os.path.join(os.path.dirname(__file__), 'tests', 'data', gzfile)
    return np.loadtxt(gzip.open(path))
1215100
def which(filename, interactive=False, verbose=False):
    
    exe = [e.lower() for e in os.environ.get('PATHEXT', '').split(';')]
    if sys.platform != 'win32':  # pragma: nocover
        exe.append('')

    name, ext = os.path.splitext(filename)
    has_extension = bool(ext)
    if has_extension and ext.lower() not in exe:
        raise ValueError("which can only search for executable files")

    def match(filenames):
        """Returns the sorted subset of ``filenames`` that matches ``filename``.
        """
        res = set()
        for fname in filenames:
            if fname == filename:  # pragma: nocover
                res.add(fname)  # exact match
                continue
            fname_name, fname_ext = os.path.splitext(fname)
            if fname_name == name and fname_ext.lower() in exe: # pragma: nocover
                res.add(fname)
        return sorted(res)

    returnset = set()
    found = False
    for pth in get_path_directories():
        if verbose:  # pragma: nocover
            print('checking pth..')

        fnames = _listdir(pth, exe)
        if not fnames:
            continue

        for m in match(fnames):
            found_file = _normalize(os.path.join(pth, m))
            if found_file not in returnset:  # pragma: nocover
                if is_executable(found_file):
                    yield found_file
                returnset.add(found_file)
        found = True

    if not found and interactive:  # pragma: nocover
        print("Couldn't find %r anywhere on the path.." % filename)
        sys.exit(1)
13615
def parse_path(f1, f2):

    """"""

    import glob

    # if second argument is missing or is a wild card, point it
    # to the current directory
    f2 = f2.strip()
    if f2 == '' or f2 == '*':
        f2 = './'

    # if the first argument is a directory, use all GEIS files
    if os.path.isdir(f1):
        f1 = os.path.join(f1, '*.??h')
    list1 = glob.glob(f1)
    list1 = [name for name in list1 if name[-1] == 'h' and name[-4] == '.']

    # if the second argument is a directory, use file names in the
    # first argument to construct file names, i.e.
    # abc.xyh will be converted to abc_xyf.fits
    if os.path.isdir(f2):
        list2 = []
        for file in list1:
            name = os.path.split(file)[-1]
            fitsname = name[:-4] + '_' + name[-3:-1] + 'f.fits'
            list2.append(os.path.join(f2, fitsname))
    else:
        list2 = [s.strip() for s in f2.split(",")]

    if list1 == [] or list2 == []:
        err_msg = ""
        if list1 == []:
            err_msg += "Input files `{:s}` not usable/available. ".format(f1)

        if list2 == []:
            err_msg += "Input files `{:s}` not usable/available. ".format(f2)

        raise IOError(err_msg)

    else:
        return list1, list2
389124
def _parse(contents=None, file_name=None):
    '''
    
    '''
    if contents:
        pass
    elif file_name and os.path.exists(file_name):
        with salt.utils.files.fopen(file_name, 'r') as ifile:
            contents = salt.utils.stringutils.to_unicode(ifile.read())
    else:
        log.error('File "%s" does not exist', file_name)
        return False

    rules = []
    for line in contents.splitlines():
        if not line:
            continue
        if line.startswith('#'):
            continue
        control_flag = ''
        module = ''
        arguments = []
        comps = line.split()
        interface = comps[0]
        position = 1
        if comps[1].startswith('['):
            control_flag = comps[1].replace('[', '')
            for part in comps[2:]:
                position += 1
                if part.endswith(']'):
                    control_flag += ' {0}'.format(part.replace(']', ''))
                    position += 1
                    break
                else:
                    control_flag += ' {0}'.format(part)
        else:
            control_flag = comps[1]
            position += 1
        module = comps[position]
        if len(comps) > position:
            position += 1
            arguments = comps[position:]
        rules.append({'interface': interface,
                      'control_flag': control_flag,
                      'module': module,
                      'arguments': arguments})
    return rules
936047
def parse(isatab_ref):
    
    if os.path.isdir(isatab_ref):
        fnames = glob.glob(os.path.join(isatab_ref, "i_*.txt")) + \
                 glob.glob(os.path.join(isatab_ref, "*.idf.txt"))
        assert len(fnames) == 1
        isatab_ref = fnames[0]
    assert os.path.exists(isatab_ref), "Did not find investigation file: %s" % isatab_ref
    i_parser = InvestigationParser()
    with open(isatab_ref, "rU") as in_handle:
        rec = i_parser.parse(in_handle)
    s_parser = StudyAssayParser(isatab_ref)
    rec = s_parser.parse(rec)
    return rec
436535
def from_file(filename_or_file_object):
    
    if isinstance(filename_or_file_object, basestring):
        file_ = open(filename_or_file_object, 'r')
        we_opened = True
    else:
        we_opened = False
        file_ = filename_or_file_object

    try:
        data = load(file_.read())
    finally:
        if we_opened:
            file_.close()

    return data
148865
def from_file(cls, filename_or_file_object):
        
        object_ = from_file(filename_or_file_object)
        if not isinstance(object_, cls):
            raise ValueError('Expected to read {0!r} object, but got {1!r} instead'.format(cls, type(object_)))

        return object_
1204965
def parse_meta(filename, data):
    
    if "." not in filename:
        raise MetaParsingException(
            "Can't recognize type of your metadata ('%s')!" % filename
        )

    suffix = filename.rsplit(".", 1)[1].lower()

    if suffix not in SUPPORTED_FILES:
        raise MetaParsingException("Can't parse file of type '%s'!" % suffix)

    fp = validator.FieldParser()
    for key, val in SUPPORTED_FILES[suffix](data).items():
        fp.process(key, val)

    return fp.get_epublication()
559132
def parseFile( self, file_or_filename ):
        
        try:
            file_contents = file_or_filename.read()
        except AttributeError:
            f = open(file_or_filename, "rb")
            file_contents = f.read()
            f.close()
        return self.parseString(file_contents)