Enbode a file as an embedded buffer
519864
function encodeEmbeddedFileBuffer( encoder, buffer_type, filename, mime_type ) {
	// Get MIME And payload
	var mime = mime_type || mimeTypeFromFilename( filename ),
		mime_id = encoder.stringID( mime ),
		buffer = bufferFromFile( filename );

	// Write buffer header
	encoder.log(LOG.EMB,"file='"+filename+"', mime="+mime+", len="+buffer.length);
	encodeBuffer( encoder, buffer_type, mime_id, buffer );

}
83679
def embeddedFileUpd(self, id, buffer=None, filename=None, ufilename=None, desc=None):
        """"""
        return _fitz.Document_embeddedFileUpd(self, id, buffer, filename, ufilename, desc)
200606
function encodeChunk(type, data) {
    var cursor = new BufferCursor(new buffer.Buffer(
        buffer.Buffer.byteLength(type) + 4 + data.length
    ));

    cursor.write(type);
    cursor.writeUInt32BE(data.length);
    cursor.copy(data);

    return cursor.buffer;
}
1312665
def encode(self, boundary):
        """"""
        if self.value is None:
            value = self.fileobj.read()
        else:
            value = self.value

        if re.search("^--%s$" % re.escape(boundary), value, re.M):
            raise ValueError("boundary found in encoded string")

        return "%s%s\r\n" % (self.encode_hdr(boundary), value)
19706
function fromBufferWithMime( type, bufferContent, options, cb, withPath ) {
  if ( typeof type === 'string' &&
       bufferContent &&
       bufferContent instanceof Buffer &&
       ( typeof options === 'function' || typeof cb === 'function' ) ) {
    _writeBufferToDisk( bufferContent, function( newPath ) {
      fromFileWithMimeAndPath( type, newPath, options, cb );
    });
  } else {
    _returnArgsError( arguments );
  }
}
278482
def into_buffer(self, buf, offset):
    
    self.payload = containerize(exclude_fields(self))
    self.parser = MsgEphemerisGPSDepF._parser
    self.stream_payload.reset(buf, offset)
    return self.pack_into(buf, offset, self._build_payload)
500699
public void encodeBuffer(ByteBuffer aBuffer, OutputStream aStream)
        throws IOException {
        byte [] buf = getBytes(aBuffer);
        encodeBuffer(buf, aStream);
    }
154889
function buffer(patch) {
		var mw = (patch || core.base());
		mw.lines = [];
		mw.enabled = true;
		mw.writeln = function (line) {
			if (mw.enabled) {
				mw.lines.push(String(line));
			}
		};
		//TODO add wordwrap?
		mw.concat = function (seperator, indent, sepAfter) {
			if (mw.lines.length > 0) {
				sepAfter = (typeof sepAfter !== 'undefined' ? sepAfter : true);
				seperator = (typeof seperator !== 'undefined' ? seperator : '\n');
				indent = (typeof indent !== 'undefined' ? indent : '');
				return indent + mw.lines.join(seperator + indent) + (sepAfter ? seperator : '');
			}
			return '';
		};
		mw.clear = function () {
			mw.lines.length = 0;
		};
		if (!patch) {
			mw.toString = function () {
				return '<miniwrite-buffer>';
			};
		}
		return mw;
	}
101650
function setStorageBufferFile(buffer, addr, filename, data) {
  if (!typeof data=="string") throw "Expecting string";
  if (addr&3) throw "Unaligned";
  var fileSize = data.length;
  var nextAddr = addr+16+((fileSize+3)&~3);
  if (nextAddr>buffer.length) throw "File too big for buffer";
  // https://github.com/espruino/Espruino/blob/master/src/jsflash.h#L30
  // 'size'
  buffer.set([fileSize&255, (fileSize>>8)&255,
              (fileSize>>16)&255, (fileSize>>24)&255], addr);
  // 'replacement' - none, since this is the only file
  buffer.set([0xFF,0xFF,0xFF,0xFF], addr+4);
  // 'filename', 8 bytes
  if (filename.length>8) throw "Filename "+JSON.stringify(filename)+" too big";
  buffer.set([0,0,0,0,0,0,0,0], addr+8);
  for (var i=0;i<filename.length;i++)
    buffer[addr+8+i] = filename.charCodeAt(i);
  // Write the data in
  for (var i=0;i<fileSize;i++)
    buffer[addr+16+i] = data.charCodeAt(i);
  // return next addr
  return nextAddr;
}
1309920
def _mudraw(buffer, fmt):
    """"""
    with NamedTemporaryFile(suffix='.pdf') as tmp_in:
        tmp_in.write(buffer)
        tmp_in.seek(0)
        tmp_in.flush()

        proc = run(
            ['mudraw', '-F', fmt, '-o', '-', tmp_in.name], stdout=PIPE, stderr=PIPE
        )
        if proc.stderr:
            raise RuntimeError(proc.stderr.decode())
        return proc.stdout
504882
function dumpAndWrap(fName /*, localDir:string*/, sourceToDump) {
    let p = new Promise(function (resolve) {
        fs.stat(fName, (err, stat) => {
            if (!err) {
                if (stat.isFile()) {
                    logger.debug(`Found a file to wrap at ${fName}`);
                    let stream = fs.createReadStream(fName, {
                        'encoding': 'utf8'
                    });
                    resolve(stream);
                    return;
                }
                logger.error(`Should not be here:\n ${util.format(stat)}`);
            }
            else {
                logger.warn(`cant find file ${fName}`);
                if (sourceToDump) {
                    logger.debug(`Found alternative source dumping it from \n ${util.format(sourceToDump)}`);
                    let target = fs.createWriteStream(fName, { 'flags': 'a' });
                    sourceToDump.pipe(target);
                    target.on('close', () => {
                        let stream = fs.createReadStream(fName, {
                            'encoding': 'utf8'
                        });
                        logger.debug(`should resolve with ${util.format(stream)}`);
                        resolve(stream);
                        return;
                    });
                }
                else {
                    logger.error("Output file error, Still cant open output file, returning empy stream");
                    let dummyStream = new streamLib.Readable();
                    dummyStream.push(null);
                    resolve(dummyStream);
                    return;
                }
            }
        });
    });
    return p;
}
144088
def buffer2file(self):
        
        if self.current_file is not None and self.buffer:
            self.current_file.add_block_data(self.buffered_block_length, self.buffer)
            self.buffer = []
            self.buffered_block_length = 0
392138
def load_stream(filename):
    """"""
    rawfile = pkg_resources.resource_stream(__name__, filename)
    if six.PY2:
        return rawfile
    return io.TextIOWrapper(rawfile, 'utf-8')
791641
def fromfile(cls, f):
        """"""
        filter = cls()
        filter._setup(*unpack(cls.FILE_FMT, f.read(calcsize(cls.FILE_FMT))))
        nfilters, = unpack(b'<l', f.read(calcsize(b'<l')))
        if nfilters > 0:
            header_fmt = b'<' + b'Q'*nfilters
            bytes = f.read(calcsize(header_fmt))
            filter_lengths = unpack(header_fmt, bytes)
            for fl in filter_lengths:
                filter.filters.append(BloomFilter.fromfile(f, fl))
        else:
            filter.filters = []

        return filter
556694
def _input_file_as_lines(cls, session: AppSession):
        ''''''
        if session.args.input_file == sys.stdin:
            input_file = session.args.input_file
        else:
            reader = codecs.getreader(session.args.local_encoding or 'utf-8')
            input_file = reader(session.args.input_file)

        return input_file
420415
def _stdio_stream_as(src_fd, dst_fd, dst_sys_attribute, mode):
  """"""
  if src_fd == -1:
    src = open('/dev/null', mode)
    src_fd = src.fileno()

  # Capture the python and os level file handles.
  old_dst = getattr(sys, dst_sys_attribute)
  old_dst_fd = os.dup(dst_fd)
  if src_fd != dst_fd:
    os.dup2(src_fd, dst_fd)

  # Open up a new file handle to temporarily replace the python-level io object, then yield.
  new_dst = os.fdopen(dst_fd, mode)
  setattr(sys, dst_sys_attribute, new_dst)
  try:
    yield
  finally:
    new_dst.close()

    # Restore the python and os level file handles.
    os.dup2(old_dst_fd, dst_fd)
    setattr(sys, dst_sys_attribute, old_dst)
1000715
def file_chunk(filename, size=_BUFFERING):
    

    def chunks():
        with open(filename, "rb", _BUFFERING) as fd:
            buf = fd.read(size)
            while buf:
                yield buf
                buf = fd.read(size)
    return chunks