Transfer binary to pb message
    :param b: binary content to be transformed to pb message
    :return: pb message
340916
def binary2pb(b, proto_id, proto_fmt_type):
    
    rsp = pb_map[proto_id]
    if rsp is None:
        return None
    if proto_fmt_type == ProtoFMT.Json:
        return json2pb(type(rsp), b.decode('utf-8'))
    elif proto_fmt_type == ProtoFMT.Protobuf:
        rsp = type(rsp)()
        # logger.debug((proto_id))
        if IS_PY2:
            rsp.ParseFromString(str(b))
        else:
            rsp.ParseFromString(b)
        return rsp
    else:
        raise Exception("binary2str: unknown proto format.")
11871
def _encode_to_binary_string(message, on, off):
    
    def to_string(i, s):
        if i == 0 and s == off:
            return off * 4
        return s
    return ''.join(to_string(i, s) for i, s in enumerate(_encode_binary(message, on=on, off=off)))
398509
def to_bytes(self):
		
		
		# grab the chunks we needs
		out = [PNG_SIGN]
		# FIXME: it's tricky to define "other_chunks". HoneyView stop the 
		# animation if it sees chunks other than fctl or idat, so we put other
		# chunks to the end of the file
		other_chunks = []
		seq = 0
		
		# for first frame
		png, control = self.frames[0]
		
		# header
		out.append(png.hdr)
		
		# acTL
		out.append(make_chunk("acTL", struct.pack("!II", len(self.frames), self.num_plays)))
		
		# fcTL
		if control:
			out.append(make_chunk("fcTL", struct.pack("!I", seq) + control.to_bytes()))
			seq += 1
		
		# and others...
		idat_chunks = []
		for type_, data in png.chunks:
			if type_ in ("IHDR", "IEND"):
				continue
			if type_ == "IDAT":
				# put at last
				idat_chunks.append(data)
				continue
			out.append(data)
		out.extend(idat_chunks)
		
		# FIXME: we should do some optimization to frames...
		# for other frames
		for png, control in self.frames[1:]:
			# fcTL
			out.append(
				make_chunk("fcTL", struct.pack("!I", seq) + control.to_bytes())
			)
			seq += 1
			
			# and others...
			for type_, data in png.chunks:
				if type_ in ("IHDR", "IEND") or type_ in CHUNK_BEFORE_IDAT:
					continue
				elif type_ == "IDAT":
					# convert IDAT to fdAT
					out.append(
						make_chunk("fdAT", struct.pack("!I", seq) + data[8:-4])
					)
					seq += 1
				else:
					other_chunks.append(data)
		
		# end
		out.extend(other_chunks)
		out.append(png.end)
		
		return b"".join(out)
424434
def binary(self, length=(1 * 1024 * 1024)):
        
        blob = [self.generator.random.randrange(256) for _ in range(length)]
        return bytes(blob) if sys.version_info[0] >= 3 else bytearray(blob)
858654
def reconstruct_binary(self, attachments):
        
        self.data = self._reconstruct_binary_internal(self.data,
                                                      self.attachments)
892188
def __bytes_to_share_data(self, payload):
        """"""
        rbytes = payload[P_DATA]
        mime = payload[P_MIME]

        if mime is None or not self.__auto_encode_decode:
            return rbytes, mime
        mime = expand_idx_mimetype(mime).lower()
        try:
            if mime == 'application/ubjson':
                return ubjloadb(rbytes), None
            elif mime == 'text/plain; charset=utf8':
                return rbytes.decode('utf-8'), None
            else:
                return rbytes, mime
        except:
            logger.warning('auto-decode failed, returning bytes', exc_info=DEBUG_ENABLED)
            return rbytes, mime
245273
def binary_dumps(obj, alt_format=False):
    
    return b''.join(_binary_dump_gen(obj, alt_format=alt_format))
192358
def data_from_bn(bn, min_length: nil, required_length: nil)
      raise ArgumentError, "Missing big number" if !bn

      length = BN_num_bytes(bn)
      buf = FFI::MemoryPointer.from_string("\x00"*length)
      BN_bn2bin(bn, buf)
      s = buf.read_string(length)
      s = s.rjust(min_length, "\x00") if min_length
      if required_length && s.bytesize != required_length
        raise BTCError, "Non-matching length of the number: #{s.bytesize} bytes vs required #{required_length}"
      end
      s
    end
359056
def from_message(cls, message):
        
        type_ = message.get_text()
        return cls(type_=type_, blob=message.asbytes())
20253
def to_pb(self):
        
        if self.gc_rule is None:
            return table_v2_pb2.ColumnFamily()
        else:
            return table_v2_pb2.ColumnFamily(gc_rule=self.gc_rule.to_pb())
726770
def binary2str(b, proto_id, proto_fmt_type):
    
    if proto_fmt_type == ProtoFMT.Json:
        return b.decode('utf-8')
    elif proto_fmt_type == ProtoFMT.Protobuf:
        rsp = pb_map[proto_id]
        if IS_PY2:
            rsp.ParseFromString(str(b))
        else:
            rsp.ParseFromString(b)
        return MessageToJson(rsp)
    else:
        raise Exception("binary2str: unknown proto format.")
131670
def to_pb(self):
        
        timestamp_range_kwargs = {}
        if self.start is not None:
            timestamp_range_kwargs["start_timestamp_micros"] = (
                _microseconds_from_datetime(self.start) // 1000 * 1000
            )
        if self.end is not None:
            end_time = _microseconds_from_datetime(self.end)
            if end_time % 1000 != 0:
                end_time = end_time // 1000 * 1000 + 1000
            timestamp_range_kwargs["end_timestamp_micros"] = end_time
        return data_v2_pb2.TimestampRange(**timestamp_range_kwargs)
676331
def retrbinary(cmd, blocksize, rest_offset = nil) # :yield: data
      synchronize do
        with_binary(true) do
          begin
            conn = transfercmd(cmd, rest_offset)
            loop do
              data = conn.read(blocksize)
              break if data == nil
              yield(data)
            end
            conn.shutdown(Socket::SHUT_WR)
            conn.read_timeout = 1
            conn.read
          ensure
            conn.close if conn
          end
          voidresp
        end
      end
    end
1353252
async def blob(self, elem=None, elem_type=None, params=None):
        
        elem_type = elem_type if elem_type else elem.__class__
        if hasattr(elem_type, 'kv_serialize'):
            elem = elem_type() if elem is None else elem
            return await elem.kv_serialize(self, elem=elem, elem_type=elem_type, params=params)

        if self.writing:
            elem_is_blob = isinstance(elem, x.BlobType)
            data = getattr(elem, x.BlobType.DATA_ATTR) if elem_is_blob else elem
            if data is None:
                return NoSetSentinel()
            if len(data) == 0:
                return b''

            fval = Modeler.to_bytes(data)
            if self.hexlify:
                return binascii.hexlify(fval).decode('ascii')
            else:
                return fval

        else:
            if elem is None:
                return NoSetSentinel()
            if self.hexlify:
                return bytes(binascii.unhexlify(elem))
            else:
                return bytes(elem)
686192
def StreamSignedBinaryContents(blob_iterator,
                               chunk_size = 1024
                              ):
  
  all_blobs_read = False
  byte_buffer = io.BytesIO()
  while not all_blobs_read or byte_buffer.getvalue():
    while not all_blobs_read and byte_buffer.tell() < chunk_size:
      try:
        blob = next(blob_iterator)
      except StopIteration:
        all_blobs_read = True
        break
      byte_buffer.write(blob.data)
    if byte_buffer.tell() > 0:
      # Yield a chunk of the signed binary and reset the buffer to contain
      # only data that hasn't been sent yet.
      byte_buffer.seek(0)
      yield byte_buffer.read(chunk_size)
      byte_buffer = io.BytesIO(byte_buffer.read())
      byte_buffer.seek(0, io.SEEK_END)
1037422
def encode_base64(msg):
    
    orig = msg.get_payload()
    encdata = str(_bencode(orig), 'ascii')
    msg.set_payload(encdata)
    msg['Content-Transfer-Encoding'] = 'base64'
864284
def to_binary(self):
    
    c = containerize(exclude_fields(self))
    self.payload = MsgEphemerisGPSDepF._parser.build(c)
    return self.pack()