Read the content of a file.
550559
def read(fname, URL, URLImage):
    """"""
    readme = open(path.join(path.dirname(__file__), fname)).read()
    if hasattr(readme, 'decode'):
        # In Python 3, turn bytes into str.
        readme = readme.decode('utf8')
    # turn relative links into absolute ones
    readme = re.sub(r'`<([^>]*)>`__',
                    r'`\1 <' + URL + r"/blob/master/\1>`__",
                    readme)
    readme = re.sub(r"\.\. image:: /", ".. image:: " + URLImage + "/", readme)

    return readme
649001
def read_file(name):
    """"""
    cur_path = os.path.dirname(__file__)
    exts = ('txt', 'rst')
    for ext in exts:
        path = os.path.join(cur_path, '.'.join((name, ext)))
        if os.path.exists(path):
            with open(path, 'rt') as file_obj:
                return file_obj.read()

    return ''
223137
def _readuntil(f, end=_TYPE_END):
	""""""
	buf = bytearray()
	byte = f.read(1)
	while byte != end:
		if byte == b'':
			raise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))
		buf += byte
		byte = f.read(1)
	return buf
539650
def read_file():
    """"""
    path = request.args.get("path")
    start_line = int(request.args.get("start_line"))
    end_line = int(request.args.get("end_line"))

    start_line = max(1, start_line)  # make sure it's not negative

    try:
        highlight = json.loads(request.args.get("highlight", "true"))
    except Exception as e:
        if app.debug:
            print("Raising exception since debug is on")
            raise e

        else:
            highlight = (
                True
            )  # highlight argument was invalid for some reason, default to true

    if path and os.path.isfile(path):
        try:
            last_modified = os.path.getmtime(path)
            with open(path, "r") as f:
                raw_source_code_list = f.read().split("\n")
                num_lines_in_file = len(raw_source_code_list)
                end_line = min(
                    num_lines_in_file, end_line
                )  # make sure we don't try to go too far

                # if leading lines are '', then the lexer will strip them out, but we want
                # to preserve blank lines. Insert a space whenever we find a blank line.
                for i in range((start_line - 1), (end_line)):
                    if raw_source_code_list[i] == "":
                        raw_source_code_list[i] = " "
                raw_source_code_lines_of_interest = raw_source_code_list[
                    (start_line - 1) : (end_line)
                ]
            try:
                lexer = get_lexer_for_filename(path)
            except Exception:
                lexer = None

            if lexer and highlight:
                highlighted = True
                # convert string into tokens
                tokens = lexer.get_tokens("\n".join(raw_source_code_lines_of_interest))
                # format tokens into nice, marked up list of html
                formatter = (
                    htmllistformatter.HtmlListFormatter()
                )  # Don't add newlines after each line
                source_code = formatter.get_marked_up_list(tokens)
            else:
                highlighted = False
                source_code = raw_source_code_lines_of_interest

            return jsonify(
                {
                    "source_code_array": source_code,
                    "path": path,
                    "last_modified_unix_sec": last_modified,
                    "highlighted": highlighted,
                    "start_line": start_line,
                    "end_line": end_line,
                    "num_lines_in_file": num_lines_in_file,
                }
            )

        except Exception as e:
            return client_error({"message": "%s" % e})

    else:
        return client_error({"message": "File not found: %s" % path})
1128740
def read(self, filepath):
        """"""
        fp = codecs.open(filepath, 'r', encoding='utf-8')
        try:
            self.read_file(fp)
        finally:
            fp.close()
1019485
def read_text(self, name):
        """"""
        with self.open_readable(name) as fp:
            res = fp.read()  # StringIO or file object
            # try:
            #     res = fp.getvalue()  # StringIO returned by FtpTarget
            # except AttributeError:
            #     res = fp.read()  # file object returned by FsTarget
            res = res.decode("utf-8")
            return res
822082
def read(file, system, header=True):
    """"""
    retval = True
    fid = open(file, 'r')
    sep = re.compile(r'\s*,\s*')
    comment = re.compile(r'^#\s*')
    equal = re.compile(r'\s*=\s*')
    math = re.compile(r'[*/+-]')
    double = re.compile(r'[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?')

    # parse data
    while True:
        line = fid.readline()
        if not line:
            break
        line = line.replace('\n', '')
        line = line.strip()
        if not line:
            continue
        if comment.search(line):
            continue
        # span multiple line
        while line.endswith(',') or line.endswith(';'):
            newline = fid.readline()
            line = line.replace('\n', '')
            newline = newline.strip()
            if not newline:
                continue
            if comment.search(newline):
                continue
            line += ' ' + newline
        data = sep.split(line)
        device = data.pop(0)
        device = device.strip()
        if device == 'ALTER':
            alter(data, system)
            continue
        if device == 'INCLUDE':
            logger.debug('Parsing include file <{}>'.format(data[0]))
            newpath = data[0]
            if not os.path.isfile(newpath):
                newpath = os.path.join(system.files.path, data[0])
                if not os.path.isfile(newpath):
                    raise FileNotFoundError(
                        'Unable to locate file in {}'.format(newpath))
            read(newpath, system, header=False)  # recursive call
            logger.debug('Parsing of include file <{}> completed.'.format(
                data[0]))
            continue
        kwargs = {}
        for item in data:
            pair = equal.split(item)
            key = pair[0].strip()
            value = pair[1].strip()
            if value.startswith('"'):
                value = value[1:-1]
            elif value.startswith('['):
                array = value[1:-1].split(';')
                if math.search(value):  # execute simple operations
                    value = list(map(lambda x: eval(x), array))
                else:
                    value = list(map(lambda x: float(x), array))
            elif double.search(value):
                if math.search(value):  # execute simple operations
                    value = eval(value)
                else:
                    value = float(value)
            elif value == 'True':
                value = True
            elif value == 'False':
                value = False
            else:
                value = int(value)
            kwargs[key] = value
        index = kwargs.pop('idx', None)
        namex = kwargs.pop('name', None)
        try:
            system.__dict__[device].elem_add(idx=index, name=namex, **kwargs)
        except KeyError:
            logger.error(
                'Error adding device {:s} to powersystem object.'.format(
                    device))
            logger.debug(
                'Make sure you have added the jit models in __init__.py'
            )

    fid.close()
    return retval
783685
def _read_file(name, encoding='utf-8') -> str:
    
    with open(name, encoding=encoding) as f:
        return f.read()
704424
def read(self):
        """"""
        data = bytearray()
        while True:
            incoming_bytes = self.comport.inWaiting()
            if incoming_bytes == 0:
                break
            else:
                content = self.comport.read(size=incoming_bytes)
                data.extend(bytearray(content))
        return data
956520
def _read_from_file(self):
        
        # test if we can read the given file
        if not gf.file_can_be_read(self.file_path):
            self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError)

        if self.file_format not in TextFileFormat.ALLOWED_VALUES:
            self.log_exc(u"Text file format '%s' is not supported." % (self.file_format), None, True, ValueError)

        # read the contents of the file
        self.log([u"Reading contents of file '%s'", self.file_path])
        with io.open(self.file_path, "r", encoding="utf-8") as text_file:
            lines = text_file.readlines()

        # clear text fragments
        self.clear()

        # parse the contents
        map_read_function = {
            TextFileFormat.MPLAIN: self._read_mplain,
            TextFileFormat.MUNPARSED: self._read_munparsed,
            TextFileFormat.PARSED: self._read_parsed,
            TextFileFormat.PLAIN: self._read_plain,
            TextFileFormat.SUBTITLES: self._read_subtitles,
            TextFileFormat.UNPARSED: self._read_unparsed
        }
        map_read_function[self.file_format](lines)

        # log the number of fragments
        self.log([u"Parsed %d fragments", len(self.fragments)])
1184704
public static String readFileContents(File file) throws IOException {

        try (Scanner in = new Scanner(file)) {
            in.useDelimiter("\\Z");
            return (in.next());
        }       
    }
365305
def read_file(self):
        
        file_obj = open(self.file, 'r')
        content = file_obj.read()
        file_obj.close()
        if content:
            content = json.loads(content)
            return content
        else:
            return {}
208423
def read(self, size=None):
    
    if size is None:
      return self.buf.read() + self.open_file.read()
    contents = self.buf.read(size)
    if len(contents) < size:
      contents += self.open_file.read(size - len(contents))
    return contents
1071980
def read_content(self):
        """"""
        maxbytes = self.aggregate.config["maxfilesizedownload"]
        buf = StringIO()
        for data in self.url_connection.iter_content(chunk_size=self.ReadChunkBytes):
            if buf.tell() + len(data) > maxbytes:
                raise LinkCheckerError(_("File size too large"))
            buf.write(data)
        return buf.getvalue()
652486
def read(cls, f):
    """"""
    header = WETHeader.read(f)
    if header is None:
      # EOF
      return None
    content = f.read(header.length)

    # Consume empty separators
    f.readline()
    f.readline()

    return cls(header.url, content)
780485
def _read_value(self, file):
        """"""

        if self.data_type.nptype is not None:
            dtype = (np.dtype(self.data_type.nptype).newbyteorder(
                self.endianness))
            return fromfile(file, dtype=dtype, count=1)
        return self.data_type.read(file, self.endianness)
910560
def _read_file(self, filename):
        """"""
        result = []
        with open(filename, 'r') as f:
            lines = f.read().split('\n')
            for line in lines:
                nocomment = line.strip().split('#')[0].strip()
                if nocomment:
                    result.append(nocomment)
        return result