Try to guess header from +binary_str+
 @param [String] binary_str
 @return [String] header/protocol name
170823
def guess_first_header(binary_str)
      first_header = nil
      Header.all.each do |hklass|
        hdr = hklass.new(packet: self)
        # #read may return another object (more specific class)
        hdr = hdr.read(binary_str)
        # First header is found when, for one known header,
        # * +#parse?+ is true
        # * it exists a known binding with a upper header
        next unless hdr.parse?

        first_header = hklass.to_s.gsub(/.*::/, '') if search_upper_header(hdr)
        break unless first_header.nil?
      end
      first_header
    end
1293357
def _mime_type
      if defined? @_mime_type
        @_mime_type
      else
        guesses = ::MIME::Types.type_for(extname.to_s)

        # Prefer text mime types over binary
        @_mime_type = guesses.detect { |type| type.ascii? } ||
          # Otherwise use the first guess
          guesses.first
      end
    end
365966
def parse_upgrade_protocol(
    header: str, pos: int, header_name: str
) -> Tuple[UpgradeProtocol, int]:
    
    match = _protocol_re.match(header, pos)
    if match is None:
        raise InvalidHeaderFormat(header_name, "expected protocol", header, pos)
    return cast(UpgradeProtocol, match.group()), match.end()
763959
def get_header
      begin
        size = @out.read(33)
        size = size[0..-2]

        # Sanity check the size
        if not size_check(size)
          @log.error "Size returned from mentos.py invalid."
          stop "Size returned from mentos.py invalid."
          raise MentosError, "Size returned from mentos.py invalid."
        end

        # Read the amount of bytes we should be expecting. We first
        # convert the string of bits into an integer.
        header_bytes = size.to_s.to_i(2) + 1
        @log.info "Size in: #{size.to_s} (#{header_bytes.to_s})"
        @out.read(header_bytes)
      rescue
        @log.error "Failed to get header."
        stop "Failed to get header."
        raise MentosError, "Failed to get header."
      end
    end
1256587
public static byte[] fromBinaryString(String binaryStr) {
    if (!binaryStr.matches("^[01]*$"))
      throw new IllegalArgumentException("Invalid binary string");
    if (binaryStr.isEmpty()) return new byte[0];

    int complementary = binaryStr.length() % 8;
    if (complementary != 0)
      binaryStr += Ruby.Array.of("0").multiply(8 - complementary).join();
    return rjust(new BigInteger(binaryStr, 2).toByteArray(),
        binaryStr.length() / 8);
  }
951974
def parse(bin_payload):
    
    
    if len(bin_payload) != LENGTHS['name_consensus_hash'] + LENGTHS['value_hash']:
        log.error("Invalid update length %s" % len(bin_payload))
        return None 

    name_consensus_hash_bin = bin_payload[:LENGTHS['name_consensus_hash']]
    value_hash_bin = bin_payload[LENGTHS['name_consensus_hash']:]
    
    name_consensus_hash = hexlify( name_consensus_hash_bin )
    value_hash = hexlify( value_hash_bin )
  
    try:
        rc = update_sanity_test( None, name_consensus_hash, value_hash )
        if not rc:
            raise Exception("Invalid update data")
    except Exception, e:
        log.error("Invalid update data")
        return None

    return {
        'opcode': 'NAME_UPDATE',
        'name_consensus_hash': name_consensus_hash,
        'value_hash': value_hash
    }
346966
def binary_value(self):
        
        str_raw_value = str(self.raw_value)
        if len(str_raw_value) % 2 == 1:
            str_raw_value = '0' + str_raw_value

        return binascii.unhexlify(str_raw_value)
1283004
def asBinary(self):
        
        binString = binary.bin(self._value)[2:]
        return '0' * (len(self._value) - len(binString)) + binString
1358179
function toDebug(arr) {
                var binary = toBinaryString(arr);
                var str = '';
                for (var i = 0; i < arr.length; i++) {
                    str += '0000'.substr((i * 32).toString(16).length) + (i * 32).toString(16) + ':';
                    for (var j = 0; j < 32; j += 4) {
                        str += ' ' + binary.substr(i * 32 + j, 4);
                    }
                    if (i < arr.length - 1) str += '\n';
                }
                return str
            }
518813
function _get_binary_packet($skip_channel_filter = false)
    {
        if (!is_resource($this->fsock) || feof($this->fsock)) {
            user_error('Connection closed prematurely');
            $this->bitmap = 0;
            return false;
        }

        $start = microtime(true);
        $raw = stream_get_contents($this->fsock, $this->decrypt_block_size);

        if (!strlen($raw)) {
            return '';
        }

        if ($this->decrypt !== false) {
            $raw = $this->decrypt->decrypt($raw);
        }
        if ($raw === false) {
            user_error('Unable to decrypt content');
            return false;
        }

        if (strlen($raw) < 5) {
            return false;
        }
        extract(unpack('Npacket_length/Cpadding_length', $this->_string_shift($raw, 5)));

        $remaining_length = $packet_length + 4 - $this->decrypt_block_size;

        // quoting <http://tools.ietf.org/html/rfc4253#section-6.1>,
        // "implementations SHOULD check that the packet length is reasonable"
        // PuTTY uses 0x9000 as the actual max packet size and so to shall we
        if ($remaining_length < -$this->decrypt_block_size || $remaining_length > 0x9000 || $remaining_length % $this->decrypt_block_size != 0) {
            if (!$this->bad_key_size_fix && $this->_bad_algorithm_candidate($this->decrypt_algorithm) && !($this->bitmap & SSH2::MASK_LOGIN)) {
                $this->bad_key_size_fix = true;
                $this->_reset_connection(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
                return false;
            }
            user_error('Invalid size');
            return false;
        }

        $buffer = '';
        while ($remaining_length > 0) {
            $temp = stream_get_contents($this->fsock, $remaining_length);
            if ($temp === false || feof($this->fsock)) {
                user_error('Error reading from socket');
                $this->bitmap = 0;
                return false;
            }
            $buffer.= $temp;
            $remaining_length-= strlen($temp);
        }

        $stop = microtime(true);
        if (strlen($buffer)) {
            $raw.= $this->decrypt !== false ? $this->decrypt->decrypt($buffer) : $buffer;
        }

        $payload = $this->_string_shift($raw, $packet_length - $padding_length - 1);
        $padding = $this->_string_shift($raw, $padding_length); // should leave $raw empty

        if ($this->hmac_check !== false) {
            $hmac = stream_get_contents($this->fsock, $this->hmac_size);
            if ($hmac === false || strlen($hmac) != $this->hmac_size) {
                user_error('Error reading socket');
                $this->bitmap = 0;
                return false;
            } elseif ($hmac != $this->hmac_check->hash(pack('NNCa*', $this->get_seq_no, $packet_length, $padding_length, $payload . $padding))) {
                user_error('Invalid HMAC');
                return false;
            }
        }

        //if ($this->decompress) {
        //    $payload = gzinflate(substr($payload, 2));
        //}

        $this->get_seq_no++;

        if (defined('NET_SSH2_LOGGING')) {
            $current = microtime(true);
            $message_number = isset($this->message_numbers[ord($payload[0])]) ? $this->message_numbers[ord($payload[0])] : 'UNKNOWN (' . ord($payload[0]) . ')';
            $message_number = '<- ' . $message_number .
                              ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)';
            $this->_append_log($message_number, $payload);
            $this->last_packet = $current;
        }

        return $this->_filter($payload, $skip_channel_filter);
    }
452962
def body
      if raw_post = get_header("RAW_POST_DATA")
        raw_post = raw_post.dup.force_encoding(Encoding::BINARY)
        StringIO.new(raw_post)
      else
        body_stream
      end
    end
1091352
def erlang_inspect(raw = false)
      return Erlang.inspect(Erlang::Binary.new(@data), raw: raw) if @bits == 8
      result = '<<'
      bytes = @data.bytes
      if last = bytes.pop
        result << bytes.join(',')
        result << ',' if not bytes.empty?
        if @bits == 8
          result << "#{last}"
        else
          result << "#{last}:#{@bits}"
        end
      end
      result << '>>'
      return result
    end
75153
function _btoa(str) {
  let buffer;

  if (str instanceof Buffer) {
    buffer = str;
  } else {
    buffer = Buffer.from(str.toString(), "binary");
  }

  return buffer.toString("base64");
}
1073312
def code_binary(item):
    
    code_str = code(item)
    if isinstance(code_str, six.string_types):
        return code_str.encode('utf-8')
    return code_str
332393
def binary?
      # Large blobs aren't even loaded into memory
      if data.nil?
        true

      # Treat blank files as text
      elsif data == ""
        false

      # Charlock doesn't know what to think
      elsif encoding.nil?
        true

      # If Charlock says its binary
      else
        detect_encoding[:type] == :binary
      end
    end
1195466
def safe_shlex_split(text_or_binary):
  
  value = ensure_text(text_or_binary) if PY3 else ensure_binary(text_or_binary)
  return shlex.split(value)
887892
def encode_string(str)
      str = str.to_s.encode('UTF-8')

      # Force to binary, when assembling the packet
      str.force_encoding('ASCII-8BIT')
      encode_short(str.bytesize) + str
    end