Input:  {
              http - http object
              type - content type
              bin  - bytes to output
            }

    Output: {
              return - 0
            }
515044
def web_err(i):

    

    http=i['http']
    tp=i['type']
    bin=i['bin']

    try: bin=bin.decode('utf-8')
    except Exception as e: pass

    if tp=='json':
       rx=ck.dumps_json({'dict':{'return':1, 'error':bin}})
       if rx['return']>0:
          bin2=rx['error'].encode('utf8')
       else:
          bin2=rx['string'].encode('utf-8')
    elif tp=='con':
       bin2=bin.encode('utf8')
    else:
       bin2=b'<html><body><pre>'+bin.encode('utf8')+b'</pre></body></html>'

    i['bin']=bin2
    return web_out(i)
669335
function validateObjectAttributeHTTPInput( $http, $base, $contentObjectAttribute )
    {
        $classAttribute = $contentObjectAttribute->contentClassAttribute();
        $useSeconds = ( $classAttribute->attribute( self::USE_SECONDS_FIELD ) == 1 );

        if ( $http->hasPostVariable( $base . '_datetime_year_' . $contentObjectAttribute->attribute( 'id' ) ) and
             $http->hasPostVariable( $base . '_datetime_month_' . $contentObjectAttribute->attribute( 'id' ) ) and
             $http->hasPostVariable( $base . '_datetime_day_' . $contentObjectAttribute->attribute( 'id' ) ) and
             $http->hasPostVariable( $base . '_datetime_hour_' . $contentObjectAttribute->attribute( 'id' ) ) and
             $http->hasPostVariable( $base . '_datetime_minute_' . $contentObjectAttribute->attribute( 'id' ) ) and
             ( !$useSeconds or $http->hasPostVariable( $base . '_datetime_second_' . $contentObjectAttribute->attribute( 'id' ) ) ) )
        {
            $year   = $http->postVariable( $base . '_datetime_year_' . $contentObjectAttribute->attribute( 'id' ) );
            $month  = $http->postVariable( $base . '_datetime_month_' . $contentObjectAttribute->attribute( 'id' ) );
            $day    = $http->postVariable( $base . '_datetime_day_' . $contentObjectAttribute->attribute( 'id' ) );
            $hour   = $http->postVariable( $base . '_datetime_hour_' . $contentObjectAttribute->attribute( 'id' ) );
            $minute = $http->postVariable( $base . '_datetime_minute_' . $contentObjectAttribute->attribute( 'id' ) );
            $second = $useSeconds ? $http->postVariable( $base . '_datetime_second_' . $contentObjectAttribute->attribute( 'id' ) ) : 0;

            if ( $year == '' or
                 $month == '' or
                 $day == '' or
                 $hour == '' or
                 $minute == '' or
                 ( $useSeconds and $second == '' ) )
            {
                if ( !( $year == '' and
                        $month == '' and
                        $day == '' and
                        $hour == '' and
                        $minute == '' and
                        ( !$useSeconds or $second == '' ) ) or
                     ( !$classAttribute->attribute( 'is_information_collector' ) and
                       $contentObjectAttribute->validateIsRequired() ) )
                {
                    $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes',
                                                                         'Missing datetime input.' ) );
                    return eZInputValidator::STATE_INVALID;
                }
                else
                    return eZInputValidator::STATE_ACCEPTED;
            }
            else
            {
                return $this->validateDateTimeHTTPInput( $day, $month, $year, $hour, $minute, $second, $contentObjectAttribute );
            }
        }
        else if ( !$classAttribute->attribute( 'is_information_collector' ) and $contentObjectAttribute->validateIsRequired() )
        {
            $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes', 'Missing datetime input.' ) );
            return eZInputValidator::STATE_INVALID;
        }
        else
            return eZInputValidator::STATE_ACCEPTED;
    }
1162602
def to_bytes(s, encoding=None, errors='strict'):
    """"""
    encoding = encoding or 'utf-8'
    if isinstance(s, bytes):
        if encoding != 'utf-8':
            return s.decode('utf-8', errors).encode(encoding, errors)
        else:
            return s
    if not is_string(s):
        s = string_type(s)
    return s.encode(encoding, errors)
834277
def deserialize_from_http_generics(cls, body_bytes, headers):
        # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any
        
        # Try to use content-type from headers if available
        content_type = None
        if 'content-type' in headers:
            content_type = headers['content-type'].split(";")[0].strip().lower()
        # Ouch, this server did not declare what it sent...
        # Let's guess it's JSON...
        # Also, since Autorest was considering that an empty body was a valid JSON,
        # need that test as well....
        else:
            content_type = "application/json"

        if body_bytes:
            return cls.deserialize_from_text(body_bytes, content_type)
        return None
212373
int version()
  {
    if (_version > 0) {
      return _version;
    }

    CharSegment protocol = getProtocolBuffer();
    if (protocol.equals("HTTP/1.1")) {
      _version = HTTP_1_1;
      return HTTP_1_1;
    }
    else if (protocol.equals("HTTP/1.0")) {
      _version = HTTP_1_0;
      return _version;
    }
    else if (protocol.equals("HTTP/0.9")) {
      _version = HTTP_0_9;
      return HTTP_0_9;
    }
    else if (protocol.length() < 8) {
      _version = HTTP_0_9;
      return _version;
    }

    int i = protocol.indexOf('/');
    int len = protocol.length();
    int major = 0;
    for (i++; i < len; i++) {
      char ch = protocol.charAt(i);

      if ('0' <= ch && ch <= '9')
        major = 10 * major + ch - '0';
      else if (ch == '.')
        break;
      else {
        _version = HTTP_1_0;
        return _version;
      }
    }

    int minor = 0;
    for (i++; i < len; i++) {
      char ch = protocol.charAt(i);

      if ('0' <= ch && ch <= '9')
        minor = 10 * minor + ch - '0';
      else
        break;
    }

    _version = 256 * major + minor;

    return _version;
  }
702858
function validateObjectAttributeHTTPInput( $http, $base, $contentObjectAttribute )
    {
        $data = false;
        if ( $http->hasPostVariable( $base . '_ezmatrix_cell_' . $contentObjectAttribute->attribute( 'id' ) ) )
            $data = $http->PostVariable( $base . '_ezmatrix_cell_' . $contentObjectAttribute->attribute( 'id' ) );
        $count = 0;
        for ( $i = 0; $i < count( $data ); ++$i )
             if ( trim( $data[$i] ) <> '' )
             {
                 ++$count;
                 break;
             }
        if ( $contentObjectAttribute->validateIsRequired() and ( $count == 0 or $data === false ) )
        {
            $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes',
                                                                 'Missing matrix input.' ) );
            return eZInputValidator::STATE_INVALID;
        }
        return eZInputValidator::STATE_ACCEPTED;
    }
989402
function fetchObjectAttributeHTTPInput( $http, $base, $contentObjectAttribute )
    {
        eZBinaryFileType::checkFileUploads();
        if ( $this->isDeletingFile( $http, $contentObjectAttribute ) )
        {
            return false;
        }

        if ( !eZHTTPFile::canFetch( $base . "_data_binaryfilename_" . $contentObjectAttribute->attribute( "id" ) ) )
            return false;

        $httpBinaryFile = eZHTTPFile::fetch( $base . "_data_binaryfilename_" . $contentObjectAttribute->attribute( "id" ) );

        $contentObjectAttribute->setContent( $httpBinaryFile );

        if ( $httpBinaryFile instanceof eZHTTPFile )
        {
            $contentObjectAttributeID = $contentObjectAttribute->attribute( "id" );
            $version = $contentObjectAttribute->attribute( "version" );

            /*
            $mimeObj = new  eZMimeType();
            $mimeData = $mimeObj->findByURL( $httpBinaryFile->attribute( "original_filename" ), true );
            $mime = $mimeData['name'];
            */

            $mimeData = eZMimeType::findByFileContents( $httpBinaryFile->attribute( "original_filename" ) );
            $mime = $mimeData['name'];

            if ( $mime == '' )
            {
                $mime = $httpBinaryFile->attribute( "mime_type" );
            }
            $extension = eZFile::suffix( $httpBinaryFile->attribute( "original_filename" ) );
            $httpBinaryFile->setMimeType( $mime );
            if ( !$httpBinaryFile->store( "original", $extension ) )
            {
                eZDebug::writeError( "Failed to store http-file: " . $httpBinaryFile->attribute( "original_filename" ),
                                     "eZBinaryFileType" );
                return false;
            }

            $binary = eZBinaryFile::fetch( $contentObjectAttributeID, $version );
            if ( $binary === null )
            {
                $binary = eZBinaryFile::create( $contentObjectAttributeID, $version );
            }
            else
            {
                // if storing a different file for the same version, see if the existing file can be removed.
                $newFileName = basename( $httpBinaryFile->attribute( "filename" ) );
                if ( $newFileName != $binary->Filename )
                {
                    $this->deleteStoredObjectAttribute( $contentObjectAttribute, $version );
                }
            }

            $orig_dir = $httpBinaryFile->storageDir( "original" );

            $binary->setAttribute( "contentobject_attribute_id", $contentObjectAttributeID );
            $binary->setAttribute( "version", $version );
            $binary->setAttribute( "filename", basename( $httpBinaryFile->attribute( "filename" ) ) );
            $binary->setAttribute( "original_filename", $httpBinaryFile->attribute( "original_filename" ) );
            $binary->setAttribute( "mime_type", $mime );

            $binary->store();

            $filePath = $httpBinaryFile->attribute( 'filename' );
            $fileHandler = eZClusterFileHandler::instance();
            $fileHandler->fileStore( $filePath, 'binaryfile', true, $mime );

            $contentObjectAttribute->setContent( $binary );
        }
        return true;
    }
593147
def to_bytes(s):
    '''
    '''
    if isinstance(s, six.binary_type):
        return s
    if isinstance(s, six.string_types):
        return s.encode('utf-8')
    raise TypeError('want string or bytes, got {}', type(s))
930419
def to_bytes(s, encoding="utf-8"):
    
    if isinstance(s, six.binary_type):
        return s
    else:
        return six.text_type(s).encode(encoding)
200596
def to_bytes(value):
    
    if isinstance(value, text_type):
        return value.encode('utf-8')
    elif isinstance(value, ffi.CData):
        return ffi.string(value)
    elif isinstance(value, binary_type):
        return value
    else:
        raise ValueError('Value must be text, bytes, or char[]')
317551
@Override
  public Response binary(
    String toplevelCorpusName,
    String corpusName,
    String rawOffset,
    String rawLength,
    String fileName)
  {
    Subject user = SecurityUtils.getSubject();
    user.checkPermission("query:binary:" + toplevelCorpusName);

    String acceptHeader = request.getHeader(HttpHeaders.ACCEPT);
    if (acceptHeader == null || acceptHeader.trim().isEmpty())
    {
      acceptHeader = "*/*";
    }

    List<AnnisBinaryMetaData> meta = queryDao.getBinaryMeta(toplevelCorpusName,
      corpusName);
    HashMap<String, AnnisBinaryMetaData> matchedMetaByType = new LinkedHashMap<>();

    for (AnnisBinaryMetaData m : meta)
    {
      if (fileName == null)
      {
        // just add all available media types
        if (!matchedMetaByType.containsKey(m.getMimeType()))
        {
          matchedMetaByType.put(m.getMimeType(), m);
        }
      }
      else
      {
        // check if this binary has the right title/file name
        if (fileName.equals(m.getFileName()))
        {
          matchedMetaByType.put(m.getMimeType(), m);
        }
      }
    }

    if (matchedMetaByType.isEmpty())
    {
      return Response.status(Response.Status.NOT_FOUND)
        .entity("Requested binary not found")
        .build();
    }

    // find the best matching mime type
    String bestMediaTypeMatch =
      MIMEParse.bestMatch(matchedMetaByType.keySet(), acceptHeader);
    if (bestMediaTypeMatch.isEmpty())
    {
      return Response.status(Response.Status.NOT_ACCEPTABLE)
        .entity("Client must accept one of the following media types: "
        + StringUtils.join(matchedMetaByType.keySet(), ", "))
        .build();
    }
    MediaType mediaType = MediaType.valueOf(bestMediaTypeMatch);

    int offset = 0;
    int length = 0;

    if (rawLength == null || rawOffset == null)
    {
      // use matched binary meta data to get the complete file size
      AnnisBinaryMetaData matchedBinary = matchedMetaByType.get(mediaType.
        toString());
      if (matchedBinary != null)
      {
        length = matchedBinary.getLength();
      }
    }
    else
    {
      // use the provided information
      offset = Integer.parseInt(rawOffset);
      length = Integer.parseInt(rawLength);
    }

    log.debug(
      "fetching  " + (length / 1024) + "kb (" + offset + "-" + (offset + length) + ") from binary "
      + toplevelCorpusName + "/" + corpusName + (fileName == null ? "" : fileName) + " "
      + mediaType.toString());

    final InputStream stream = queryDao.
      getBinary(toplevelCorpusName, corpusName, mediaType.toString(), fileName,
      offset, length);

    log.debug("fetch successfully");
    StreamingOutput result = new StreamingOutput()
    {
      @Override
      public void write(OutputStream output) throws IOException, WebApplicationException
      {
        try
        {
          ByteStreams.copy(stream, output);
          output.close();
        }
        finally
        {
          stream.close();
        }
      }
    };

    return Response.ok(result, mediaType).build();
  }
1283004
def asBinary(self):
        
        binString = binary.bin(self._value)[2:]
        return '0' * (len(self._value) - len(binString)) + binString
505187
function intToBytes(num) {
	var bytes = [];

	for(var i=7 ; i>=0 ; --i) {
		bytes[i] = num & (255);
		num = num >> 8;
	}

	return bytes;
}
957352
function jsonDump (data) {
  if (data == null) return 'null' // python gives a fuck about 'undefined'
  switch (typeof data) {
    case 'number':
    case 'boolean':
      return JSON.stringify(data) // hand off primitives to JSON.stringify
    case 'string':
      return unicodeEscape(JSON.stringify(data)) // strings are special because unicode
    case 'object':
      if (Array.isArray(data)) {
        return '[' + data.map(jsonDump).join(', ') + ']'
      }
      return '{' + Object.keys(data).map(key =>
        '"' + key + '": ' + jsonDump(data[key])).join(', ') + '}'
    default:
      throw new Error('Cannot handle unknown type ' + typeof data + '! Report as ZeroNetJS Bug!')
  }
}
33699
def _parse_lambda_output(lambda_output, binary_types, flask_request):
        
        json_output = json.loads(lambda_output)

        if not isinstance(json_output, dict):
            raise TypeError("Lambda returned %{s} instead of dict", type(json_output))

        status_code = json_output.get("statusCode") or 200
        headers = CaseInsensitiveDict(json_output.get("headers") or {})
        body = json_output.get("body") or "no data"
        is_base_64_encoded = json_output.get("isBase64Encoded") or False

        try:
            status_code = int(status_code)
            if status_code <= 0:
                raise ValueError
        except ValueError:
            message = "statusCode must be a positive int"
            LOG.error(message)
            raise TypeError(message)

        # If the customer doesn't define Content-Type default to application/json
        if "Content-Type" not in headers:
            LOG.info("No Content-Type given. Defaulting to 'application/json'.")
            headers["Content-Type"] = "application/json"

        if LocalApigwService._should_base64_decode_body(binary_types, flask_request, headers, is_base_64_encoded):
            body = base64.b64decode(body)

        return status_code, headers, body
408107
def decompress(obj, return_type="bytes"):
    
    if isinstance(obj, binary_type):
        b = zlib.decompress(obj)
    elif isinstance(obj, string_types):
        b = zlib.decompress(base64.b64decode(obj.encode("utf-8")))
    else:
        raise TypeError("input cannot be anything other than str and bytes!")

    if return_type == "bytes":
        return b
    elif return_type == "str":
        return b.decode("utf-8")
    elif return_type == "obj":
        return pickle.loads(b)
    else:
        raise ValueError(
            "'return_type' has to be one of 'bytes', 'str' or 'obj'!")
617883
function bytes(b) {
    if (!readable) return b;

    var tb = ((1 << 30) * 1024)
      , gb = 1 << 30
      , mb = 1 << 20
      , kb = 1 << 10
      , abs = Math.abs(b);

    if (abs >= tb) return (Math.round(b / tb * 100) / 100) + 'tb';
    if (abs >= gb) return (Math.round(b / gb * 100) / 100) + 'gb';
    if (abs >= mb) return (Math.round(b / mb * 100) / 100) + 'mb';
    if (abs >= kb) return (Math.round(b / kb * 100) / 100) + 'kb';

    return b + 'b';
  }