idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
18,700
def search_artist ( self , artist_name , quiet = False , limit = 9 ) : result = self . search ( artist_name , search_type = 100 , limit = limit ) if result [ 'result' ] [ 'artistCount' ] <= 0 : LOG . warning ( 'Artist %s not existed!' , artist_name ) raise SearchNotFound ( 'Artist {} not existed.' . format ( artist_nam...
Search artist by artist name .
18,701
def search_playlist ( self , playlist_name , quiet = False , limit = 9 ) : result = self . search ( playlist_name , search_type = 1000 , limit = limit ) if result [ 'result' ] [ 'playlistCount' ] <= 0 : LOG . warning ( 'Playlist %s not existed!' , playlist_name ) raise SearchNotFound ( 'playlist {} not existed' . forma...
Search playlist by playlist name .
18,702
def search_user ( self , user_name , quiet = False , limit = 9 ) : result = self . search ( user_name , search_type = 1002 , limit = limit ) if result [ 'result' ] [ 'userprofileCount' ] <= 0 : LOG . warning ( 'User %s not existed!' , user_name ) raise SearchNotFound ( 'user {} not existed' . format ( user_name ) ) els...
Search user by user name .
18,703
def get_user_playlists ( self , user_id , limit = 1000 ) : url = 'http://music.163.com/weapi/user/playlist?csrf_token=' csrf = '' params = { 'offset' : 0 , 'uid' : user_id , 'limit' : limit , 'csrf_token' : csrf } result = self . post_request ( url , params ) playlists = result [ 'playlist' ] return self . display . se...
Get a user s all playlists .
18,704
def get_playlist_songs ( self , playlist_id , limit = 1000 ) : url = 'http://music.163.com/weapi/v3/playlist/detail?csrf_token=' csrf = '' params = { 'id' : playlist_id , 'offset' : 0 , 'total' : True , 'limit' : limit , 'n' : 1000 , 'csrf_token' : csrf } result = self . post_request ( url , params ) songs = result [ '...
Get a playlists s all songs .
18,705
def get_album_songs ( self , album_id ) : url = 'http://music.163.com/api/album/{}/' . format ( album_id ) result = self . get_request ( url ) songs = result [ 'album' ] [ 'songs' ] songs = [ Song ( song [ 'id' ] , song [ 'name' ] ) for song in songs ] return songs
Get a album s all songs .
18,706
def get_artists_hot_songs ( self , artist_id ) : url = 'http://music.163.com/api/artist/{}' . format ( artist_id ) result = self . get_request ( url ) hot_songs = result [ 'hotSongs' ] songs = [ Song ( song [ 'id' ] , song [ 'name' ] ) for song in hot_songs ] return songs
Get a artist s top50 songs .
18,707
def get_song_url ( self , song_id , bit_rate = 320000 ) : url = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token=' csrf = '' params = { 'ids' : [ song_id ] , 'br' : bit_rate , 'csrf_token' : csrf } result = self . post_request ( url , params ) song_url = result [ 'data' ] [ 0 ] [ 'url' ] if song_url is No...
Get a song s download address .
18,708
def get_song_lyric ( self , song_id ) : url = 'http://music.163.com/api/song/lyric?os=osx&id={}&lv=-1&kv=-1&tv=-1' . format ( song_id ) result = self . get_request ( url ) if 'lrc' in result and result [ 'lrc' ] [ 'lyric' ] is not None : lyric_info = result [ 'lrc' ] [ 'lyric' ] else : lyric_info = 'Lyric not found.' r...
Get a song s lyric .
18,709
def get_song_by_url ( self , song_url , song_name , folder , lyric_info ) : if not os . path . exists ( folder ) : os . makedirs ( folder ) fpath = os . path . join ( folder , song_name + '.mp3' ) if sys . platform == 'win32' or sys . platform == 'cygwin' : valid_name = re . sub ( r'[<>:"/\\|?*]' , '' , song_name ) if ...
Download a song and save it to disk .
18,710
def login ( self ) : username = click . prompt ( 'Please enter your email or phone number' ) password = click . prompt ( 'Please enter your password' , hide_input = True ) pattern = re . compile ( r'^0\d{2,3}\d{7,8}$|^1[34578]\d{9}$' ) if pattern . match ( username ) : url = 'https://music.163.com/weapi/login/cellphone...
Login entrance .
18,711
def to_representation ( self , instance ) : feature = OrderedDict ( ) fields = list ( self . fields . values ( ) ) if self . Meta . id_field : field = self . fields [ self . Meta . id_field ] value = field . get_attribute ( instance ) feature [ "id" ] = field . to_representation ( value ) fields . remove ( field ) feat...
Serialize objects - > primitives .
18,712
def get_properties ( self , instance , fields ) : properties = OrderedDict ( ) for field in fields : if field . write_only : continue value = field . get_attribute ( instance ) representation = None if value is not None : representation = field . to_representation ( value ) properties [ field . field_name ] = represent...
Get the feature metadata which will be used for the GeoJSON properties key .
18,713
def to_internal_value ( self , data ) : if 'properties' in data : data = self . unformat_geojson ( data ) return super ( GeoFeatureModelSerializer , self ) . to_internal_value ( data )
Override the parent method to first remove the GeoJSON formatting
18,714
def unformat_geojson ( self , feature ) : attrs = feature [ "properties" ] if 'geometry' in feature : attrs [ self . Meta . geo_field ] = feature [ 'geometry' ] if self . Meta . bbox_geo_field and 'bbox' in feature : attrs [ self . Meta . bbox_geo_field ] = Polygon . from_bbox ( feature [ 'bbox' ] ) return attrs
This function should return a dictionary containing keys which maps to serializer fields .
18,715
def ready ( self ) : from django . contrib . gis . db import models from rest_framework . serializers import ModelSerializer from . fields import GeometryField try : field_mapping = ModelSerializer . _field_mapping . mapping except AttributeError : field_mapping = ModelSerializer . serializer_field_mapping field_mappin...
update Django Rest Framework serializer mappings
18,716
def dist_to_deg ( self , distance , latitude ) : lat = latitude if latitude >= 0 else - 1 * latitude rad2deg = 180 / pi earthRadius = 6378160.0 latitudeCorrection = 0.5 * ( 1 + cos ( lat * pi / 180 ) ) return ( distance / ( earthRadius * latitudeCorrection ) * rad2deg )
distance = distance in meters latitude = latitude in degrees
18,717
def _SetCredentials ( self , ** kwds ) : args = { 'api_key' : self . _API_KEY , 'client' : self , 'client_id' : self . _CLIENT_ID , 'client_secret' : self . _CLIENT_SECRET , 'package_name' : self . _PACKAGE , 'scopes' : self . _SCOPES , 'user_agent' : self . _USER_AGENT , } args . update ( kwds ) from apitools . base ....
Fetch credentials and set them for this client .
18,718
def JsonResponseModel ( self ) : old_model = self . response_type_model self . __response_type_model = 'json' yield self . __response_type_model = old_model
In this context return raw JSON instead of proto .
18,719
def ProcessRequest ( self , method_config , request ) : if self . log_request : logging . info ( 'Calling method %s with %s: %s' , method_config . method_id , method_config . request_type_name , request ) return request
Hook for pre - processing of requests .
18,720
def ProcessHttpRequest ( self , http_request ) : http_request . headers . update ( self . additional_http_headers ) if self . log_request : logging . info ( 'Making http %s to %s' , http_request . http_method , http_request . url ) logging . info ( 'Headers: %s' , pprint . pformat ( http_request . headers ) ) if http_r...
Hook for pre - processing of http requests .
18,721
def DeserializeMessage ( self , response_type , data ) : try : message = encoding . JsonToMessage ( response_type , data ) except ( exceptions . InvalidDataFromServerError , messages . ValidationError , ValueError ) as e : raise exceptions . InvalidDataFromServerError ( 'Error decoding response "%s" as type %s: %s' % (...
Deserialize the given data as method_config . response_type .
18,722
def FinalizeTransferUrl ( self , url ) : url_builder = _UrlBuilder . FromUrl ( url ) if self . global_params . key : url_builder . query_params [ 'key' ] = self . global_params . key return url_builder . url
Modify the url for a given transfer based on auth and version .
18,723
def GetMethodConfig ( self , method ) : method_config = self . _method_configs . get ( method ) if method_config : return method_config func = getattr ( self , method , None ) if func is None : raise KeyError ( method ) method_config = getattr ( func , 'method_config' , None ) if method_config is None : raise KeyError ...
Returns service cached method config for given method .
18,724
def __CombineGlobalParams ( self , global_params , default_params ) : util . Typecheck ( global_params , ( type ( None ) , self . __client . params_type ) ) result = self . __client . params_type ( ) global_params = global_params or self . __client . params_type ( ) for field in result . all_fields ( ) : value = global...
Combine the given params with the defaults .
18,725
def __FinalUrlValue ( self , value , field ) : if isinstance ( field , messages . BytesField ) and value is not None : return base64 . urlsafe_b64encode ( value ) elif isinstance ( value , six . text_type ) : return value . encode ( 'utf8' ) elif isinstance ( value , six . binary_type ) : return value . decode ( 'utf8'...
Encode value for the URL using field to skip encoding for bytes .
18,726
def __ConstructQueryParams ( self , query_params , request , global_params ) : global_params = self . __CombineGlobalParams ( global_params , self . __client . global_params ) global_param_names = util . MapParamNames ( [ x . name for x in self . __client . params_type . all_fields ( ) ] , self . __client . params_type...
Construct a dictionary of query parameters for this request .
18,727
def __FinalizeRequest ( self , http_request , url_builder ) : if ( http_request . http_method == 'GET' and len ( http_request . url ) > _MAX_URL_LENGTH ) : http_request . http_method = 'POST' http_request . headers [ 'x-http-method-override' ] = 'GET' http_request . headers [ 'content-type' ] = 'application/x-www-form-...
Make any final general adjustments to the request .
18,728
def __ProcessHttpResponse ( self , method_config , http_response , request ) : if http_response . status_code not in ( http_client . OK , http_client . CREATED , http_client . NO_CONTENT ) : raise exceptions . HttpError . FromResponse ( http_response , method_config = method_config , request = request ) if http_respons...
Process the given http response .
18,729
def __SetBaseHeaders ( self , http_request , client ) : user_agent = client . user_agent or 'apitools-client/1.0' http_request . headers [ 'user-agent' ] = user_agent http_request . headers [ 'accept' ] = 'application/json' http_request . headers [ 'accept-encoding' ] = 'gzip, deflate'
Fill in the basic headers on http_request .
18,730
def __SetBody ( self , http_request , method_config , request , upload ) : if not method_config . request_field : return request_type = _LoadClass ( method_config . request_type_name , self . __client . MESSAGES_MODULE ) if method_config . request_field == REQUEST_IS_BODY : body_value = request body_type = request_type...
Fill in the body on http_request .
18,731
def PrepareHttpRequest ( self , method_config , request , global_params = None , upload = None , upload_config = None , download = None ) : request_type = _LoadClass ( method_config . request_type_name , self . __client . MESSAGES_MODULE ) util . Typecheck ( request , request_type ) request = self . __client . ProcessR...
Prepares an HTTP request to be sent .
18,732
def _RunMethod ( self , method_config , request , global_params = None , upload = None , upload_config = None , download = None ) : if upload is not None and download is not None : raise exceptions . NotYetImplementedError ( 'Cannot yet use both upload and download at once' ) http_request = self . PrepareHttpRequest ( ...
Call this method with request .
18,733
def ProcessHttpResponse ( self , method_config , http_response , request = None ) : return self . __client . ProcessResponse ( method_config , self . __ProcessHttpResponse ( method_config , http_response , request ) )
Convert an HTTP response to the expected message type .
18,734
def describe_enum_value ( enum_value ) : enum_value_descriptor = EnumValueDescriptor ( ) enum_value_descriptor . name = six . text_type ( enum_value . name ) enum_value_descriptor . number = enum_value . number return enum_value_descriptor
Build descriptor for Enum instance .
18,735
def describe_enum ( enum_definition ) : enum_descriptor = EnumDescriptor ( ) enum_descriptor . name = enum_definition . definition_name ( ) . split ( '.' ) [ - 1 ] values = [ ] for number in enum_definition . numbers ( ) : value = enum_definition . lookup_by_number ( number ) values . append ( describe_enum_value ( val...
Build descriptor for Enum class .
18,736
def describe_field ( field_definition ) : field_descriptor = FieldDescriptor ( ) field_descriptor . name = field_definition . name field_descriptor . number = field_definition . number field_descriptor . variant = field_definition . variant if isinstance ( field_definition , messages . EnumField ) : field_descriptor . ...
Build descriptor for Field instance .
18,737
def describe_message ( message_definition ) : message_descriptor = MessageDescriptor ( ) message_descriptor . name = message_definition . definition_name ( ) . split ( '.' ) [ - 1 ] fields = sorted ( message_definition . all_fields ( ) , key = lambda v : v . number ) if fields : message_descriptor . fields = [ describe...
Build descriptor for Message class .
18,738
def describe_file ( module ) : descriptor = FileDescriptor ( ) descriptor . package = util . get_package_for_module ( module ) if not descriptor . package : descriptor . package = None message_descriptors = [ ] enum_descriptors = [ ] for name in sorted ( dir ( module ) ) : value = getattr ( module , name ) if isinstanc...
Build a file from a specified Python module .
18,739
def describe_file_set ( modules ) : descriptor = FileSet ( ) file_descriptors = [ ] for module in modules : file_descriptors . append ( describe_file ( module ) ) if file_descriptors : descriptor . files = file_descriptors return descriptor
Build a file set from a specified Python modules .
18,740
def describe ( value ) : if isinstance ( value , types . ModuleType ) : return describe_file ( value ) elif isinstance ( value , messages . Field ) : return describe_field ( value ) elif isinstance ( value , messages . Enum ) : return describe_enum_value ( value ) elif isinstance ( value , type ) : if issubclass ( valu...
Describe any value as a descriptor .
18,741
def import_descriptor_loader ( definition_name , importer = __import__ ) : if definition_name . startswith ( '.' ) : definition_name = definition_name [ 1 : ] if not definition_name . startswith ( '.' ) : leaf = definition_name . split ( '.' ) [ - 1 ] if definition_name : try : module = importer ( definition_name , '' ...
Find objects by importing modules as needed .
18,742
def lookup_descriptor ( self , definition_name ) : try : return self . __descriptors [ definition_name ] except KeyError : pass if self . __descriptor_loader : definition = self . __descriptor_loader ( definition_name ) self . __descriptors [ definition_name ] = definition return definition else : raise messages . Defi...
Lookup descriptor by name .
18,743
def lookup_package ( self , definition_name ) : while True : descriptor = self . lookup_descriptor ( definition_name ) if isinstance ( descriptor , FileDescriptor ) : return descriptor . package else : index = definition_name . rfind ( '.' ) if index < 0 : return None definition_name = definition_name [ : index ]
Determines the package name for any definition .
18,744
def _load_json_module ( ) : first_import_error = None for module_name in [ 'json' , 'simplejson' ] : try : module = __import__ ( module_name , { } , { } , 'json' ) if not hasattr ( module , 'JSONEncoder' ) : message = ( 'json library "%s" is not compatible with ProtoRPC' % module_name ) logging . warning ( message ) ra...
Try to load a valid json module .
18,745
def default ( self , value ) : if isinstance ( value , messages . Enum ) : return str ( value ) if six . PY3 and isinstance ( value , bytes ) : return value . decode ( 'utf8' ) if isinstance ( value , messages . Message ) : result = { } for field in value . all_fields ( ) : item = value . get_assigned_value ( field . n...
Return dictionary instance from a message object .
18,746
def encode_message ( self , message ) : message . check_initialized ( ) return json . dumps ( message , cls = MessageJSONEncoder , protojson_protocol = self )
Encode Message instance to JSON string .
18,747
def decode_message ( self , message_type , encoded_message ) : encoded_message = six . ensure_str ( encoded_message ) if not encoded_message . strip ( ) : return message_type ( ) dictionary = json . loads ( encoded_message ) message = self . __decode_dictionary ( message_type , dictionary ) message . check_initialized ...
Merge JSON structure to Message instance .
18,748
def __find_variant ( self , value ) : if isinstance ( value , bool ) : return messages . Variant . BOOL elif isinstance ( value , six . integer_types ) : return messages . Variant . INT64 elif isinstance ( value , float ) : return messages . Variant . DOUBLE elif isinstance ( value , six . string_types ) : return messa...
Find the messages . Variant type that describes this value .
18,749
def __decode_dictionary ( self , message_type , dictionary ) : message = message_type ( ) for key , value in six . iteritems ( dictionary ) : if value is None : try : message . reset ( key ) except AttributeError : pass continue try : field = message . field_by_name ( key ) except KeyError : variant = self . __find_var...
Merge dictionary in to message .
18,750
def WriteSetupPy ( self , out ) : printer = self . _GetPrinter ( out ) year = datetime . datetime . now ( ) . year printer ( '# Copyright %s Google Inc. All Rights Reserved.' % year ) printer ( '#' ) printer ( '# Licensed under the Apache License, Version 2.0 (the' '"License");' ) printer ( '# you may not use this file...
Write a setup . py for upload to PyPI .
18,751
def DownloadProgressPrinter ( response , unused_download ) : if 'content-range' in response . info : print ( 'Received %s' % response . info [ 'content-range' ] ) else : print ( 'Received %d bytes' % response . length )
Print download progress based on response .
18,752
def _Initialize ( self , http , url ) : self . EnsureUninitialized ( ) if self . http is None : self . __http = http or http_wrapper . GetHttp ( ) self . __url = url
Initialize this download by setting self . http and self . url .
18,753
def FromFile ( cls , filename , overwrite = False , auto_transfer = True , ** kwds ) : path = os . path . expanduser ( filename ) if os . path . exists ( path ) and not overwrite : raise exceptions . InvalidUserInputError ( 'File %s exists and overwrite not specified' % path ) return cls ( open ( path , 'wb' ) , close_...
Create a new download object from a filename .
18,754
def FromStream ( cls , stream , auto_transfer = True , total_size = None , ** kwds ) : return cls ( stream , auto_transfer = auto_transfer , total_size = total_size , ** kwds )
Create a new Download object from a stream .
18,755
def FromData ( cls , stream , json_data , http = None , auto_transfer = None , ** kwds ) : info = json . loads ( json_data ) missing_keys = cls . _REQUIRED_SERIALIZATION_KEYS - set ( info . keys ( ) ) if missing_keys : raise exceptions . InvalidDataError ( 'Invalid serialization data, missing keys: %s' % ( ', ' . join ...
Create a new Download object from a stream and serialized data .
18,756
def __SetTotal ( self , info ) : if 'content-range' in info : _ , _ , total = info [ 'content-range' ] . rpartition ( '/' ) if total != '*' : self . __total_size = int ( total ) if self . total_size is None : self . __total_size = 0
Sets the total size based off info if possible otherwise 0 .
18,757
def InitializeDownload ( self , http_request , http = None , client = None ) : self . EnsureUninitialized ( ) if http is None and client is None : raise exceptions . UserError ( 'Must provide client or http.' ) http = http or client . http if client is not None : http_request . url = client . FinalizeTransferUrl ( http...
Initialize this download by making a request .
18,758
def __NormalizeStartEnd ( self , start , end = None ) : if end is not None : if start < 0 : raise exceptions . TransferInvalidError ( 'Cannot have end index with negative start index ' + '[start=%d, end=%d]' % ( start , end ) ) elif start >= self . total_size : raise exceptions . TransferInvalidError ( 'Cannot have sta...
Normalizes start and end values based on total size .
18,759
def __ComputeEndByte ( self , start , end = None , use_chunks = True ) : end_byte = end if start < 0 and not self . total_size : return end_byte if use_chunks : alternate = start + self . chunksize - 1 if end_byte is not None : end_byte = min ( end_byte , alternate ) else : end_byte = alternate if self . total_size : a...
Compute the last byte to fetch for this request .
18,760
def __GetChunk ( self , start , end , additional_headers = None ) : self . EnsureInitialized ( ) request = http_wrapper . Request ( url = self . url ) self . __SetRangeHeader ( request , start , end = end ) if additional_headers is not None : request . headers . update ( additional_headers ) return http_wrapper . MakeR...
Retrieve a chunk and return the full response .
18,761
def GetRange ( self , start , end = None , additional_headers = None , use_chunks = True ) : self . EnsureInitialized ( ) progress_end_normalized = False if self . total_size is not None : progress , end_byte = self . __NormalizeStartEnd ( start , end ) progress_end_normalized = True else : progress = start end_byte = ...
Retrieve a given byte range from this download inclusive .
18,762
def StreamInChunks ( self , callback = None , finish_callback = None , additional_headers = None ) : self . StreamMedia ( callback = callback , finish_callback = finish_callback , additional_headers = additional_headers , use_chunks = True )
Stream the entire download in chunks .
18,763
def StreamMedia ( self , callback = None , finish_callback = None , additional_headers = None , use_chunks = True ) : callback = callback or self . progress_callback finish_callback = finish_callback or self . finish_callback self . EnsureInitialized ( ) while True : if self . __initial_response is not None : response ...
Stream the entire download .
18,764
def FromFile ( cls , filename , mime_type = None , auto_transfer = True , gzip_encoded = False , ** kwds ) : path = os . path . expanduser ( filename ) if not os . path . exists ( path ) : raise exceptions . NotFoundError ( 'Could not find file %s' % path ) if not mime_type : mime_type , _ = mimetypes . guess_type ( pa...
Create a new Upload object from a filename .
18,765
def FromStream ( cls , stream , mime_type , total_size = None , auto_transfer = True , gzip_encoded = False , ** kwds ) : if mime_type is None : raise exceptions . InvalidUserInputError ( 'No mime_type specified for stream' ) return cls ( stream , mime_type , total_size = total_size , close_stream = False , auto_transf...
Create a new Upload object from a stream .
18,766
def FromData ( cls , stream , json_data , http , auto_transfer = None , gzip_encoded = False , ** kwds ) : info = json . loads ( json_data ) missing_keys = cls . _REQUIRED_SERIALIZATION_KEYS - set ( info . keys ( ) ) if missing_keys : raise exceptions . InvalidDataError ( 'Invalid serialization data, missing keys: %s' ...
Create a new Upload of stream from serialized json_data and http .
18,767
def __SetDefaultUploadStrategy ( self , upload_config , http_request ) : if upload_config . resumable_path is None : self . strategy = SIMPLE_UPLOAD if self . strategy is not None : return strategy = SIMPLE_UPLOAD if ( self . total_size is not None and self . total_size > _RESUMABLE_UPLOAD_THRESHOLD ) : strategy = RESU...
Determine and set the default upload strategy for this upload .
18,768
def ConfigureRequest ( self , upload_config , http_request , url_builder ) : if ( self . total_size and upload_config . max_size and self . total_size > upload_config . max_size ) : raise exceptions . InvalidUserInputError ( 'Upload too big: %s larger than max size %s' % ( self . total_size , upload_config . max_size )...
Configure the request and url for this upload .
18,769
def __ConfigureMediaRequest ( self , http_request ) : http_request . headers [ 'content-type' ] = self . mime_type http_request . body = self . stream . read ( ) http_request . loggable_body = '<media body>'
Configure http_request as a simple request for this upload .
18,770
def __ConfigureMultipartRequest ( self , http_request ) : msg_root = mime_multipart . MIMEMultipart ( 'related' ) setattr ( msg_root , '_write_headers' , lambda self : None ) msg = mime_nonmultipart . MIMENonMultipart ( * http_request . headers [ 'content-type' ] . split ( '/' ) ) msg . set_payload ( http_request . bod...
Configure http_request as a multipart request for this upload .
18,771
def RefreshResumableUploadState ( self ) : if self . strategy != RESUMABLE_UPLOAD : return self . EnsureInitialized ( ) refresh_request = http_wrapper . Request ( url = self . url , http_method = 'PUT' , headers = { 'Content-Range' : 'bytes */*' } ) refresh_response = http_wrapper . MakeRequest ( self . http , refresh_...
Talk to the server and refresh the state of this resumable upload .
18,772
def InitializeUpload ( self , http_request , http = None , client = None ) : if self . strategy is None : raise exceptions . UserError ( 'No upload strategy set; did you call ConfigureRequest?' ) if http is None and client is None : raise exceptions . UserError ( 'Must provide client or http.' ) if self . strategy != R...
Initialize this upload from the given http_request .
18,773
def StreamMedia ( self , callback = None , finish_callback = None , additional_headers = None ) : return self . __StreamMedia ( callback = callback , finish_callback = finish_callback , additional_headers = additional_headers , use_chunks = False )
Send this resumable upload in a single request .
18,774
def __SendMediaRequest ( self , request , end ) : def CheckResponse ( response ) : if response is None : raise exceptions . RequestError ( 'Request to url %s did not return a response.' % response . request_url ) response = http_wrapper . MakeRequest ( self . bytes_http , request , retry_func = self . retry_func , retr...
Request helper function for SendMediaBody & SendChunk .
18,775
def __SendMediaBody ( self , start , additional_headers = None ) : self . EnsureInitialized ( ) if self . total_size is None : raise exceptions . TransferInvalidError ( 'Total size must be known for SendMediaBody' ) body_stream = stream_slice . StreamSlice ( self . stream , self . total_size - start ) request = http_wr...
Send the entire media stream in a single request .
18,776
def __SendChunk ( self , start , additional_headers = None ) : self . EnsureInitialized ( ) no_log_body = self . total_size is None request = http_wrapper . Request ( url = self . url , http_method = 'PUT' ) if self . __gzip_encoded : request . headers [ 'Content-Encoding' ] = 'gzip' body_stream , read_length , exhaust...
Send the specified chunk .
18,777
def CompressStream ( in_stream , length = None , compresslevel = 2 , chunksize = 16777216 ) : in_read = 0 in_exhausted = False out_stream = StreamingBuffer ( ) with gzip . GzipFile ( mode = 'wb' , fileobj = out_stream , compresslevel = compresslevel ) as compress_stream : while not length or out_stream . length < lengt...
Compresses an input stream into a file - like buffer .
18,778
def read ( self , size = None ) : if size is None : size = self . __size ret_list = [ ] while size > 0 and self . __buf : data = self . __buf . popleft ( ) size -= len ( data ) ret_list . append ( data ) if size < 0 : ret_list [ - 1 ] , remainder = ret_list [ - 1 ] [ : size ] , ret_list [ - 1 ] [ size : ] self . __buf ...
Read at most size bytes from this buffer .
18,779
def _WriteFile ( file_descriptor , package , version , proto_printer ) : proto_printer . PrintPreamble ( package , version , file_descriptor ) _PrintEnums ( proto_printer , file_descriptor . enum_types ) _PrintMessages ( proto_printer , file_descriptor . message_types ) custom_json_mappings = _FetchCustomMappings ( fil...
Write the given extended file descriptor to the printer .
18,780
def WriteMessagesFile ( file_descriptor , package , version , printer ) : _WriteFile ( file_descriptor , package , version , _Proto2Printer ( printer ) )
Write the given extended file descriptor to out as a message file .
18,781
def WritePythonFile ( file_descriptor , package , version , printer ) : _WriteFile ( file_descriptor , package , version , _ProtoRpcPrinter ( printer ) )
Write the given extended file descriptor to out .
18,782
def _FetchCustomMappings ( descriptor_ls ) : custom_mappings = [ ] for descriptor in descriptor_ls : if isinstance ( descriptor , ExtendedEnumDescriptor ) : custom_mappings . extend ( _FormatCustomJsonMapping ( 'Enum' , m , descriptor ) for m in descriptor . enum_mappings ) elif isinstance ( descriptor , ExtendedMessag...
Find and return all custom mappings for descriptors in descriptor_ls .
18,783
def _PrintEnums ( proto_printer , enum_types ) : enum_types = sorted ( enum_types , key = operator . attrgetter ( 'name' ) ) for enum_type in enum_types : proto_printer . PrintEnum ( enum_type )
Print all enums to the given proto_printer .
18,784
def __PrintMessageCommentLines ( self , message_type ) : description = message_type . description or '%s message type.' % ( message_type . name ) width = self . __printer . CalculateWidth ( ) - 3 for line in textwrap . wrap ( description , width ) : self . __printer ( '// %s' , line ) PrintIndentedDescriptions ( self ....
Print the description of this message .
18,785
def __PrintAdditionalImports ( self , imports ) : google_imports = [ x for x in imports if 'google' in x ] other_imports = [ x for x in imports if 'google' not in x ] if other_imports : for import_ in sorted ( other_imports ) : self . __printer ( import_ ) self . __printer ( ) if google_imports : for import_ in sorted ...
Print additional imports needed for protorpc .
18,786
def positional ( max_positional_args ) : def positional_decorator ( wrapped ) : @ functools . wraps ( wrapped ) def positional_wrapper ( * args , ** kwargs ) : if len ( args ) > max_positional_args : plural_s = '' if max_positional_args != 1 : plural_s = 's' raise TypeError ( '%s() takes at most %d positional argument%...
A decorator that declares only the first N arguments may be positional .
18,787
def get_package_for_module ( module ) : if isinstance ( module , six . string_types ) : try : module = sys . modules [ module ] except KeyError : return None try : return six . text_type ( module . package ) except AttributeError : if module . __name__ == '__main__' : try : file_name = module . __file__ except Attribut...
Get package name for a module .
18,788
def decode_datetime ( encoded_datetime ) : time_zone_match = _TIME_ZONE_RE . search ( encoded_datetime ) if time_zone_match : time_string = encoded_datetime [ : time_zone_match . start ( 1 ) ] . upper ( ) else : time_string = encoded_datetime . upper ( ) if '.' in time_string : format_string = '%Y-%m-%dT%H:%M:%S.%f' el...
Decode a DateTimeField parameter from a string to a python datetime .
18,789
def value_from_message ( self , message ) : message = super ( DateTimeField , self ) . value_from_message ( message ) if message . time_zone_offset is None : return datetime . datetime . utcfromtimestamp ( message . milliseconds / 1000.0 ) milliseconds = ( message . milliseconds - 60000 * message . time_zone_offset ) t...
Convert DateTimeMessage to a datetime .
18,790
def DetectGce ( ) : metadata_url = 'http://{}' . format ( os . environ . get ( 'GCE_METADATA_ROOT' , 'metadata.google.internal' ) ) try : o = urllib_request . build_opener ( urllib_request . ProxyHandler ( { } ) ) . open ( urllib_request . Request ( metadata_url , headers = { 'Metadata-Flavor' : 'Google' } ) ) except u...
Determine whether or not we re running on GCE .
18,791
def NormalizeScopes ( scope_spec ) : if isinstance ( scope_spec , six . string_types ) : return set ( scope_spec . split ( ' ' ) ) elif isinstance ( scope_spec , collections . Iterable ) : return set ( scope_spec ) raise exceptions . TypecheckError ( 'NormalizeScopes expected string or iterable, found %s' % ( type ( sc...
Normalize scope_spec to a set of strings .
18,792
def CalculateWaitForRetry ( retry_attempt , max_wait = 60 ) : wait_time = 2 ** retry_attempt max_jitter = wait_time / 4.0 wait_time += random . uniform ( - max_jitter , max_jitter ) return max ( 1 , min ( wait_time , max_wait ) )
Calculates amount of time to wait before a retry attempt .
18,793
def AcceptableMimeType ( accept_patterns , mime_type ) : if '/' not in mime_type : raise exceptions . InvalidUserInputError ( 'Invalid MIME type: "%s"' % mime_type ) unsupported_patterns = [ p for p in accept_patterns if ';' in p ] if unsupported_patterns : raise exceptions . GeneratedClientError ( 'MIME patterns with ...
Return True iff mime_type is acceptable for one of accept_patterns .
18,794
def MapParamNames ( params , request_type ) : return [ encoding . GetCustomJsonFieldMapping ( request_type , json_name = p ) or p for p in params ]
Reverse parameter remappings for URL construction .
18,795
def _JsonValueToPythonValue ( json_value ) : util . Typecheck ( json_value , JsonValue ) _ValidateJsonValue ( json_value ) if json_value . is_null : return None entries = [ ( f , json_value . get_assigned_value ( f . name ) ) for f in json_value . all_fields ( ) ] assigned_entries = [ ( f , value ) for f , value in ent...
Convert the given JsonValue to a json string .
18,796
def _PythonValueToJsonValue ( py_value ) : if py_value is None : return JsonValue ( is_null = True ) if isinstance ( py_value , bool ) : return JsonValue ( boolean_value = py_value ) if isinstance ( py_value , six . string_types ) : return JsonValue ( string_value = py_value ) if isinstance ( py_value , numbers . Numbe...
Convert the given python value to a JsonValue .
18,797
def _EncodeInt64Field ( field , value ) : capabilities = [ messages . Variant . INT64 , messages . Variant . UINT64 , ] if field . variant not in capabilities : return encoding . CodecResult ( value = value , complete = False ) if field . repeated : result = [ str ( x ) for x in value ] else : result = str ( value ) re...
Handle the special case of int64 as a string .
18,798
def _EncodeDateField ( field , value ) : if field . repeated : result = [ d . isoformat ( ) for d in value ] else : result = value . isoformat ( ) return encoding . CodecResult ( value = result , complete = True )
Encoder for datetime . date objects .
18,799
def ReplaceHomoglyphs ( s ) : homoglyphs = { '\xa0' : ' ' , '\u00e3' : '' , '\u00a0' : ' ' , '\u00a9' : '(C)' , '\u00ae' : '(R)' , '\u2014' : '-' , '\u2018' : "'" , '\u2019' : "'" , '\u201c' : '"' , '\u201d' : '"' , '\u2026' : '...' , '\u2e3a' : '-' , } def _ReplaceOne ( c ) : equiv = homoglyphs . get ( c ) if equiv is...
Returns s with unicode homoglyphs replaced by ascii equivalents .