idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
14,400 | def convert_param ( self , method , param , value ) : rules = self . _get_validation ( method , param ) if not rules or not rules . get ( 'convert' ) : return value try : return rules [ 'convert' ] ( value ) except ValueError : raise ValidationException ( "{0} value {1} does not validate." . format ( param , value ) ) | Converts the parameter using the function convert function of the validation rules . Same parameters as the validate_param method so it might have just been added there . But lumping together the two functionalities would make overwriting harder . | 86 | 46 |
14,401 | def _get_validation ( self , method , param ) : if hasattr ( method , '_validations' ) and param in method . _validations : return method . _validations [ param ] elif ( hasattr ( method . im_class , '_validations' ) and param in method . im_class . _validations ) : return method . im_class . _validations [ param ] else : return None | Return the correct validations dictionary for this parameter . First checks the method itself and then its class . If no validation is defined for this parameter None is returned . | 93 | 32 |
14,402 | def convert_response ( self ) : if hasattr ( self . response , 'body_raw' ) : if self . response . body_raw is not None : to_type = re . sub ( '[^a-zA-Z_]' , '_' , self . type ) to_type_method = 'to_' + to_type if hasattr ( self , to_type_method ) : self . response . body = getattr ( self , to_type_method ) ( self . response . body_raw ) del self . response . body_raw | Finish filling the instance s response object so it s ready to be served to the client . This includes converting the body_raw property to the content type requested by the user if necessary . | 123 | 37 |
14,403 | def handle_exception ( self , e , status = 500 ) : logger . exception ( "An exception occurred while handling the request: %s" , e ) self . response . body_raw = { 'error' : str ( e ) } self . response . status = status | Handle the given exception . Log sets the response code and output the exception message as an error message . | 59 | 20 |
14,404 | def handle_exception_404 ( self , e ) : logger . debug ( "A 404 Not Found exception occurred while handling " "the request." ) self . response . body_raw = { 'error' : 'Not Found' } self . response . status = 404 | Handle the given exception . Log sets the response code to 404 and output the exception message as an error message . | 57 | 22 |
14,405 | def set_response_content_md5 ( self ) : self . response . content_md5 = hashlib . md5 ( self . response . body ) . hexdigest ( ) | Set the Content - MD5 response header . Calculated from the the response body by creating the MD5 hash from it . | 40 | 25 |
14,406 | def get_request_data ( self ) : request_data = [ self . path_params , self . request . GET ] if self . request . headers . get ( 'Content-Type' ) == 'application/json' and self . request . body : try : post = json . loads ( self . request . body ) except ValueError : raise_400 ( self , msg = 'Invalid JSON content data' ) if isinstance ( post , dict ) : request_data . append ( post ) else : request_data . append ( self . request . POST ) return request_data | Read the input values . | 123 | 5 |
14,407 | def _merge_defaults ( self , data , method_params , defaults ) : if defaults : optional_args = method_params [ - len ( defaults ) : ] for key , value in zip ( optional_args , defaults ) : if not key in data : data [ key ] = value return data | Helper method for adding default values to the data dictionary . | 65 | 11 |
14,408 | def _get_columns ( self , X , cols ) : if isinstance ( X , DataSet ) : X = X [ cols ] return_vector = False if isinstance ( cols , basestring ) : return_vector = True cols = [ cols ] if isinstance ( X , list ) : X = [ x [ cols ] for x in X ] X = pd . DataFrame ( X ) if return_vector : t = X [ cols [ 0 ] ] else : t = X . as_matrix ( cols ) return t | Get a subset of columns from the given table X . X a Pandas dataframe ; the table to select columns from cols a string or list of strings representing the columns to select Returns a numpy array with the data from the selected columns | 124 | 49 |
14,409 | def _requirement_element ( self , parent_element , req_data ) : req_data = self . _transform_result ( req_data ) if not req_data : return title = req_data . get ( "title" ) if not title : logger . warning ( "Skipping requirement, title is missing" ) return req_id = req_data . get ( "id" ) if not self . _check_lookup_prop ( req_id ) : logger . warning ( "Skipping requirement `%s`, data missing for selected lookup method" , title ) return attrs , custom_fields = self . _classify_data ( req_data ) attrs , custom_fields = self . _fill_defaults ( attrs , custom_fields ) # For testing purposes, the order of fields in resulting XML # needs to be always the same. attrs = OrderedDict ( sorted ( attrs . items ( ) ) ) custom_fields = OrderedDict ( sorted ( custom_fields . items ( ) ) ) requirement = etree . SubElement ( parent_element , "requirement" , attrs ) title_el = etree . SubElement ( requirement , "title" ) title_el . text = title description = req_data . get ( "description" ) if description : description_el = etree . SubElement ( requirement , "description" ) description_el . text = description self . _fill_custom_fields ( requirement , custom_fields ) | Adds requirement XML element . | 322 | 5 |
14,410 | def export ( self ) : top = self . _top_element ( ) properties = self . _properties_element ( top ) self . _fill_requirements ( top ) self . _fill_lookup_prop ( properties ) return utils . prettify_xml ( top ) | Returns requirements XML . | 60 | 4 |
14,411 | def write_xml ( xml , output_file = None ) : gen_filename = "requirements-{:%Y%m%d%H%M%S}.xml" . format ( datetime . datetime . now ( ) ) utils . write_xml ( xml , output_loc = output_file , filename = gen_filename ) | Outputs the XML content into a file . | 75 | 9 |
14,412 | def _client ( self , id , secret ) : url = self . api_url + self . auth_token_url auth_string = '%s:%s' % ( id , secret ) authorization = base64 . b64encode ( auth_string . encode ( ) ) . decode ( ) headers = { 'Authorization' : "Basic " + authorization , 'Content-Type' : "application/x-www-form-urlencoded" } params = { 'grant_type' : 'client_credentials' , 'response_type' : 'token' } return self . session . post ( url , params = params , headers = headers ) | Performs client login with the provided credentials | 144 | 8 |
14,413 | def aggregate_cap_val ( self , conn , * * kwargs ) : region = kwargs [ 'region' ] [ pv_df , wind_df , cap ] = self . get_timeseries ( conn , geometry = region . geom , * * kwargs ) if kwargs . get ( 'store' , False ) : self . store_full_df ( pv_df , wind_df , * * kwargs ) # Summerize the results to one column for pv and one for wind cap = cap . sum ( ) df = pd . concat ( [ pv_df . sum ( axis = 1 ) / cap [ 'pv_pwr' ] , wind_df . sum ( axis = 1 ) / cap [ 'wind_pwr' ] ] , axis = 1 ) feedin_df = df . rename ( columns = { 0 : 'pv_pwr' , 1 : 'wind_pwr' } ) return feedin_df , cap | Returns the normalised feedin profile and installed capacity for a given region . | 219 | 15 |
14,414 | def save_assets ( self , dest_path ) : for idx , subplot in enumerate ( self . subplots ) : subplot . save_assets ( dest_path , suffix = '_%d' % idx ) | Save plot assets alongside dest_path . | 51 | 8 |
14,415 | def set_empty ( self , row , column ) : subplot = self . get_subplot_at ( row , column ) subplot . set_empty ( ) | Keep one of the subplots completely empty . | 36 | 10 |
14,416 | def set_empty_for_all ( self , row_column_list ) : for row , column in row_column_list : self . set_empty ( row , column ) | Keep all specified subplots completely empty . | 39 | 9 |
14,417 | def set_title ( self , row , column , text ) : subplot = self . get_subplot_at ( row , column ) subplot . set_title ( text ) | Set a title text . | 39 | 5 |
14,418 | def set_label ( self , row , column , text , location = 'upper right' , style = None ) : subplot = self . get_subplot_at ( row , column ) subplot . set_label ( text , location , style ) | Set a label for the subplot . | 54 | 8 |
14,419 | def show_xticklabels ( self , row , column ) : subplot = self . get_subplot_at ( row , column ) subplot . show_xticklabels ( ) | Show the x - axis tick labels for a subplot . | 42 | 12 |
14,420 | def show_xticklabels_for_all ( self , row_column_list = None ) : if row_column_list is None : for subplot in self . subplots : subplot . show_xticklabels ( ) else : for row , column in row_column_list : self . show_xticklabels ( row , column ) | Show the x - axis tick labels for all specified subplots . | 79 | 14 |
14,421 | def show_yticklabels ( self , row , column ) : subplot = self . get_subplot_at ( row , column ) subplot . show_yticklabels ( ) | Show the y - axis tick labels for a subplot . | 42 | 12 |
14,422 | def show_yticklabels_for_all ( self , row_column_list = None ) : if row_column_list is None : for subplot in self . subplots : subplot . show_yticklabels ( ) else : for row , column in row_column_list : self . show_yticklabels ( row , column ) | Show the y - axis tick labels for all specified subplots . | 79 | 14 |
14,423 | def set_xlimits ( self , row , column , min = None , max = None ) : subplot = self . get_subplot_at ( row , column ) subplot . set_xlimits ( min , max ) | Set x - axis limits of a subplot . | 49 | 10 |
14,424 | def set_xlimits_for_all ( self , row_column_list = None , min = None , max = None ) : if row_column_list is None : self . limits [ 'xmin' ] = min self . limits [ 'xmax' ] = max else : for row , column in row_column_list : self . set_xlimits ( row , column , min , max ) | Set x - axis limits of specified subplots . | 88 | 11 |
14,425 | def set_ylimits ( self , row , column , min = None , max = None ) : subplot = self . get_subplot_at ( row , column ) subplot . set_ylimits ( min , max ) | Set y - axis limits of a subplot . | 49 | 10 |
14,426 | def set_ylimits_for_all ( self , row_column_list = None , min = None , max = None ) : if row_column_list is None : self . limits [ 'ymin' ] = min self . limits [ 'ymax' ] = max else : for row , column in row_column_list : self . set_ylimits ( row , column , min , max ) | Set y - axis limits of specified subplots . | 88 | 11 |
14,427 | def set_slimits ( self , row , column , min , max ) : subplot = self . get_subplot_at ( row , column ) subplot . set_slimits ( min , max ) | Set limits for the point sizes . | 45 | 7 |
14,428 | def set_ytick_labels ( self , row , column , labels ) : subplot = self . get_subplot_at ( row , column ) subplot . set_ytick_labels ( labels ) | Manually specify the y - axis tick labels . | 47 | 10 |
14,429 | def get_subplot_at ( self , row , column ) : idx = row * self . columns + column return self . subplots [ idx ] | Return the subplot at row column position . | 35 | 9 |
14,430 | def set_subplot_xlabel ( self , row , column , text ) : subplot = self . get_subplot_at ( row , column ) subplot . set_xlabel ( text ) | Set a label for the x - axis of a subplot . | 44 | 13 |
14,431 | def set_subplot_ylabel ( self , row , column , text ) : subplot = self . get_subplot_at ( row , column ) subplot . set_ylabel ( text ) | Set a label for the y - axis of a subplot . | 44 | 13 |
14,432 | def set_scalebar_for_all ( self , row_column_list = None , location = 'lower right' ) : if row_column_list is None : for subplot in self . subplots : subplot . set_scalebar ( location ) else : for row , column in row_column_list : subplot = self . get_subplot_at ( row , column ) subplot . set_scalebar ( location ) | Show marker area scale for subplots . | 96 | 9 |
14,433 | def set_colorbar ( self , label = '' , horizontal = False ) : if self . limits [ 'mmin' ] is None or self . limits [ 'mmax' ] is None : warnings . warn ( 'Set (only) global point meta limits to ensure the ' 'colorbar is correct for all subplots.' ) self . colorbar = { 'label' : label , 'horizontal' : horizontal } | Show the colorbar it will be attached to the last plot . | 90 | 13 |
14,434 | def set_axis_options ( self , row , column , text ) : subplot = self . get_subplot_at ( row , column ) subplot . set_axis_options ( text ) | Set additionnal options as plain text . | 43 | 9 |
14,435 | def initialize ( self , configfile = None ) : method = "initialize" A = None metadata = { method : configfile } send_array ( self . socket , A , metadata ) A , metadata = recv_array ( self . socket , poll = self . poll , poll_timeout = self . poll_timeout , flags = self . zmq_flags ) | Initialize the module | 79 | 4 |
14,436 | def finalize ( self ) : method = "finalize" A = None metadata = { method : - 1 } send_array ( self . socket , A , metadata ) A , metadata = recv_array ( self . socket , poll = self . poll , poll_timeout = self . poll_timeout , flags = self . zmq_flags ) | Finalize the module | 75 | 4 |
14,437 | def set_current_time ( self , t ) : method = "set_current_time" A = None metadata = { method : t } send_array ( self . socket , A , metadata ) A , metadata = recv_array ( self . socket , poll = self . poll , poll_timeout = self . poll_timeout , flags = self . zmq_flags ) | Set current time of simulation | 82 | 5 |
14,438 | def set_var_slice ( self , name , start , count , var ) : method = "set_var_slice" A = var metadata = { method : name , "start" : start , "count" : count } send_array ( self . socket , A , metadata ) A , metadata = recv_array ( self . socket , poll = self . poll , poll_timeout = self . poll_timeout , flags = self . zmq_flags ) | Set the variable name with the values of var | 100 | 9 |
14,439 | def update ( self , dt ) : method = "update" A = None metadata = { method : dt } send_array ( self . socket , A , metadata ) A , metadata = recv_array ( self . socket , poll = self . poll , poll_timeout = self . poll_timeout , flags = self . zmq_flags ) | Advance the module with timestep dt | 76 | 10 |
14,440 | def subscribe ( self , topic = b'' ) : self . sockets [ zmq . SUB ] . setsockopt ( zmq . SUBSCRIBE , topic ) poller = self . pollers [ zmq . SUB ] return poller | subscribe to the SUB socket to listen for incomming variables return a stream that can be listened to . | 55 | 22 |
14,441 | def download ( remote_location , remotes = None , prefix = "" , dry_run = False ) : if remotes is None : remotes , _ = _resources_files ( abs_paths = remote_location . startswith ( 's3://' ) ) if remote_location . startswith ( 's3://' ) : from . s3 import S3Backend backend = S3Backend ( remote_location , dry_run = dry_run ) backend . download ( list_local ( remotes , prefix ) , prefix ) else : dest_root = '.' shell_command ( [ '/usr/bin/rsync' , '-thrRvz' , '--rsync-path' , '/usr/bin/rsync' , '%s/./' % remote_location , dest_root ] , dry_run = dry_run ) | Download resources from a stage server . | 191 | 7 |
14,442 | def upload ( remote_location , remotes = None , ignores = None , static_root = "/static/" , prefix = "" , dry_run = False ) : # pylint:disable=too-many-arguments if remotes is None : remotes , ignores = _resources_files ( abs_paths = remote_location . startswith ( 's3://' ) ) if remote_location . startswith ( 's3://' ) : from deployutils . s3 import S3Backend backend = S3Backend ( remote_location , static_root = static_root , dry_run = dry_run ) backend . upload ( list_local ( remotes , prefix ) , prefix ) else : excludes = [ ] if ignores : for ignore in ignores : excludes += [ '--exclude' , ignore ] # -O omit to set mod times on directories to avoid permissions error. shell_command ( [ '/usr/bin/rsync' ] + excludes + [ '-pOthrRvz' , '--rsync-path' , '/usr/bin/rsync' ] + remotes + [ remote_location ] , dry_run = dry_run ) | Upload resources to a stage server . | 258 | 7 |
14,443 | def json_dumps ( obj ) : try : return json . dumps ( obj , indent = 2 , sort_keys = True , allow_nan = False ) except ValueError : pass # we don't want to call do_map on the original object since it can # contain objects that need to be converted for JSON. after reading # in the created JSON we get a limited set of possible types we # can encounter json_str = json . dumps ( obj , indent = 2 , sort_keys = True , allow_nan = True ) json_obj = json . loads ( json_str ) def do_map ( obj ) : if obj is None : return None if isinstance ( obj , basestring ) : return obj if isinstance ( obj , dict ) : res = { } for ( key , value ) in obj . items ( ) : res [ key ] = do_map ( value ) return res if isinstance ( obj , collections . Iterable ) : res = [ ] for el in obj : res . append ( do_map ( el ) ) return res # diverging numbers need to be passed as strings otherwise it # will throw a parsing error on the ECMAscript consumer side if math . isnan ( obj ) : return "NaN" if math . isinf ( obj ) : return "Infinity" if obj > 0 else "-Infinity" return obj return json . dumps ( do_map ( json_obj ) , indent = 2 , sort_keys = True , allow_nan = False ) | A safe JSON dump function that provides correct diverging numbers for a ECMAscript consumer . | 319 | 18 |
14,444 | def msg ( message , * args , * * kwargs ) : global log_file if log_file is None : log_file = sys . stderr if long_msg : file_name , line = caller_trace ( ) file_name , file_type = os . path . splitext ( file_name ) if file_name . endswith ( '/__init__' ) : file_name = os . path . basename ( os . path . dirname ( file_name ) ) elif file_name . endswith ( '/__main__' ) : file_name = "(-m) {0}" . format ( os . path . basename ( os . path . dirname ( file_name ) ) ) else : file_name = os . path . basename ( file_name ) head = '{0}{1} ({2}): ' . format ( file_name , file_type , line ) else : head = '[SERVER] ' out = StringIO ( ) for line in message . format ( * args , * * kwargs ) . split ( '\n' ) : out . write ( '{0}{1}\n' . format ( head , line ) ) out . flush ( ) out . seek ( 0 ) if _msg_stderr : sys . stderr . write ( out . read ( ) ) sys . stderr . flush ( ) else : log_file . write ( out . read ( ) ) log_file . flush ( ) out . close ( ) | Prints a message from the server to the log file . | 332 | 12 |
14,445 | def setup_restart ( ) : exit_code = os . environ . get ( 'QUICK_SERVER_RESTART' , None ) if exit_code is None : try : atexit . unregister ( _on_exit ) except AttributeError : atexit . _exithandlers = filter ( lambda exit_hnd : exit_hnd [ 0 ] != _on_exit , atexit . _exithandlers ) _start_restart_loop ( None , in_atexit = False ) | Sets up restart functionality that doesn t keep the first process alive . The function needs to be called before the actual process starts but after loading the program . It will restart the program in a child process and immediately returns in the child process . The call in the parent process never returns . Calling this function is not necessary for using restart functionality but avoids potential errors originating from rogue threads . | 114 | 76 |
14,446 | def convert_argmap ( self , query ) : res = { } if isinstance ( query , bytes ) : query = query . decode ( 'utf8' ) for section in query . split ( '&' ) : eqs = section . split ( '=' , 1 ) name = urlparse_unquote ( eqs [ 0 ] ) if len ( eqs ) > 1 : res [ name ] = urlparse_unquote ( eqs [ 1 ] ) else : res [ name ] = True return res | Converts the query string of an URL to a map . | 109 | 12 |
14,447 | def convert_args ( self , rem_path , args ) : fragment_split = rem_path . split ( '#' , 1 ) query_split = fragment_split [ 0 ] . split ( '?' , 1 ) segs = filter ( lambda p : len ( p ) and p != '.' , os . path . normpath ( query_split [ 0 ] ) . split ( '/' ) ) paths = [ urlparse_unquote ( p ) for p in segs ] query = self . convert_argmap ( query_split [ 1 ] ) if len ( query_split ) > 1 else { } args [ 'paths' ] = paths args [ 'query' ] = query args [ 'fragment' ] = urlparse_unquote ( fragment_split [ 1 ] ) . decode ( 'utf8' ) if len ( fragment_split ) > 1 else '' return args | Splits the rest of a URL into its argument parts . The URL is assumed to start with the dynamic request prefix already removed . | 192 | 26 |
14,448 | def handle_special ( self , send_body , method_str ) : ongoing = True if self . server . report_slow_requests : path = self . path def do_report ( ) : if not ongoing : return msg ( "request takes longer than expected: \"{0} {1}\"" , method_str , path ) alarm = threading . Timer ( 5.0 , do_report ) alarm . start ( ) else : alarm = None try : return self . _handle_special ( send_body , method_str ) finally : if alarm is not None : alarm . cancel ( ) ongoing = False | Handles a dynamic request . If this method returns False the request is interpreted as static file request . Methods can be registered using the add_TYPE_METHOD_mask methods of QuickServer . | 133 | 38 |
14,449 | def check_cache ( self , e_tag , match ) : if e_tag != match : return False self . send_response ( 304 ) self . send_header ( "ETag" , e_tag ) self . send_header ( "Cache-Control" , "max-age={0}" . format ( self . server . max_age ) ) self . end_headers ( ) thread_local . size = 0 return True | Checks the ETag and sends a cache match response if it matches . | 93 | 15 |
14,450 | def handle_error ( self ) : if self . server . can_ignore_error ( self ) : return if thread_local . status_code is None : msg ( "ERROR: Cannot send error status code! " + "Header already sent!\n{0}" , traceback . format_exc ( ) ) else : msg ( "ERROR: Error while processing request:\n{0}" , traceback . format_exc ( ) ) try : self . send_error ( 500 , "Internal Error" ) except : # nopep8 if self . server . can_ignore_error ( self ) : return msg ( "ERROR: Cannot send error status code:\n{0}" , traceback . format_exc ( ) ) | Tries to send an 500 error after encountering an exception . | 155 | 12 |
14,451 | def cross_origin_headers ( self ) : if not self . is_cross_origin ( ) : return False # we allow everything self . send_header ( "Access-Control-Allow-Methods" , "GET, POST, PUT, DELETE, HEAD" ) allow_headers = _getheader ( self . headers , 'access-control-request-headers' ) if allow_headers is not None : self . send_header ( "Access-Control-Allow-Headers" , allow_headers ) self . send_header ( "Access-Control-Allow-Origin" , "*" ) self . send_header ( "Access-Control-Allow-Credentials" , "true" ) return allow_headers is not None | Sends cross origin headers . | 159 | 6 |
14,452 | def do_OPTIONS ( self ) : thread_local . clock_start = get_time ( ) thread_local . status_code = 200 thread_local . message = None thread_local . headers = [ ] thread_local . end_headers = [ ] thread_local . size = - 1 thread_local . method = 'OPTIONS' self . send_response ( 200 ) if self . is_cross_origin ( ) : no_caching = self . cross_origin_headers ( ) # ten minutes if no custom headers requested self . send_header ( "Access-Control-Max-Age" , 0 if no_caching else 10 * 60 ) self . send_header ( "Content-Length" , 0 ) self . end_headers ( ) thread_local . size = 0 | Handles an OPTIONS request . | 172 | 7 |
14,453 | def do_GET ( self ) : thread_local . clock_start = get_time ( ) thread_local . status_code = 200 thread_local . message = None thread_local . headers = [ ] thread_local . end_headers = [ ] thread_local . size = - 1 thread_local . method = 'GET' try : self . cross_origin_headers ( ) if self . handle_special ( True , 'GET' ) : return SimpleHTTPRequestHandler . do_GET ( self ) except PreventDefaultResponse as pdr : if pdr . code : self . send_error ( pdr . code , pdr . msg ) except ( KeyboardInterrupt , SystemExit ) : raise except Exception : self . handle_error ( ) | Handles a GET request . | 160 | 6 |
14,454 | def log_request ( self , code = '-' , size = '-' ) : print_size = getattr ( thread_local , 'size' , - 1 ) if size != '-' : size_str = ' (%s)' % size elif print_size >= 0 : size_str = self . log_size_string ( print_size ) + ' ' else : size_str = '' if not self . server . suppress_noise or ( code != 200 and code != 304 ) : self . log_message ( '%s"%s" %s' , size_str , self . requestline , str ( code ) ) if print_size >= 0 : thread_local . size = - 1 | Logs the current request . | 153 | 6 |
14,455 | def _process_request ( self , request , client_address ) : try : self . finish_request ( request , client_address ) except Exception : self . handle_error ( request , client_address ) finally : self . shutdown_request ( request ) | Actually processes the request . | 54 | 5 |
14,456 | def process_request ( self , request , client_address ) : if not self . _parallel : self . _process_request ( request , client_address ) return t = self . _thread_factory ( target = self . _process_request , args = ( request , client_address ) ) t . daemon = True t . start ( ) | Processes the request by delegating to _process_request . | 75 | 13 |
14,457 | def add_file_patterns ( self , patterns , blacklist ) : bl = self . _pattern_black if blacklist else self . _pattern_white for pattern in patterns : bl . append ( pattern ) | Adds a list of file patterns to either the black - or white - list . Note that this pattern is applied to the absolute path of the file that will be delivered . For including or excluding folders use add_folder_mask or add_folder_fallback . | 43 | 53 |
14,458 | def bind_path ( self , name , folder ) : if not len ( name ) or name [ 0 ] != '/' or name [ - 1 ] != '/' : raise ValueError ( "name must start and end with '/': {0}" . format ( name ) ) self . _folder_masks . insert ( 0 , ( name , folder ) ) | Adds a mask that maps to a given folder relative to base_path . | 76 | 15 |
14,459 | def bind_path_fallback ( self , name , folder ) : if not len ( name ) or name [ 0 ] != '/' or name [ - 1 ] != '/' : raise ValueError ( "name must start and end with '/': {0}" . format ( name ) ) self . _folder_masks . append ( ( name , folder ) ) | Adds a fallback for a given folder relative to base_path . | 77 | 14 |
14,460 | def bind_proxy ( self , name , proxy ) : if not len ( name ) or name [ 0 ] != '/' or name [ - 1 ] != '/' : raise ValueError ( "name must start and end with '/': {0}" . format ( name ) ) self . _folder_proxys . insert ( 0 , ( name , proxy ) ) | Adds a mask that maps to a given proxy . | 77 | 10 |
14,461 | def add_cmd_method ( self , name , method , argc = None , complete = None ) : if ' ' in name : raise ValueError ( "' ' cannot be in command name {0}" . format ( name ) ) self . _cmd_methods [ name ] = method self . _cmd_argc [ name ] = argc self . _cmd_complete [ name ] = complete | Adds a command to the command line interface loop . | 85 | 10 |
14,462 | def _add_file_mask ( self , start , method_str , method ) : fm = self . _f_mask . get ( method_str , [ ] ) fm . append ( ( start , method ) ) fm . sort ( key = lambda k : len ( k [ 0 ] ) , reverse = True ) self . _f_mask [ method_str ] = fm self . _f_argc [ method_str ] = None | Adds a raw file mask for dynamic requests . | 99 | 9 |
14,463 | def add_json_mask ( self , start , method_str , json_producer ) : def send_json ( drh , rem_path ) : obj = json_producer ( drh , rem_path ) if not isinstance ( obj , Response ) : obj = Response ( obj ) ctype = obj . get_ctype ( "application/json" ) code = obj . code obj = obj . response if obj is None : drh . send_error ( 404 , "File not found" ) return None f = BytesIO ( ) json_str = json_dumps ( obj ) if isinstance ( json_str , ( str , unicode ) ) : try : json_str = json_str . decode ( 'utf8' ) except AttributeError : pass json_str = json_str . encode ( 'utf8' ) f . write ( json_str ) f . flush ( ) size = f . tell ( ) f . seek ( 0 ) # handle ETag caching if drh . request_version >= "HTTP/1.1" : e_tag = "{0:x}" . format ( zlib . crc32 ( f . read ( ) ) & 0xFFFFFFFF ) f . seek ( 0 ) match = _getheader ( drh . headers , 'if-none-match' ) if match is not None : if drh . check_cache ( e_tag , match ) : f . close ( ) return None drh . send_header ( "ETag" , e_tag , end_header = True ) drh . send_header ( "Cache-Control" , "max-age={0}" . format ( self . max_age ) , end_header = True ) drh . send_response ( code ) drh . send_header ( "Content-Type" , ctype ) drh . send_header ( "Content-Length" , size ) drh . end_headers ( ) return f self . _add_file_mask ( start , method_str , send_json ) | Adds a handler that produces a JSON response . | 442 | 9 |
14,464 | def add_text_mask ( self , start , method_str , text_producer ) : def send_text ( drh , rem_path ) : text = text_producer ( drh , rem_path ) if not isinstance ( text , Response ) : text = Response ( text ) ctype = text . get_ctype ( "text/plain" ) code = text . code text = text . response if text is None : drh . send_error ( 404 , "File not found" ) return None f = BytesIO ( ) if isinstance ( text , ( str , unicode ) ) : try : text = text . decode ( 'utf8' ) except AttributeError : pass text = text . encode ( 'utf8' ) f . write ( text ) f . flush ( ) size = f . tell ( ) f . seek ( 0 ) # handle ETag caching if drh . request_version >= "HTTP/1.1" : e_tag = "{0:x}" . format ( zlib . crc32 ( f . read ( ) ) & 0xFFFFFFFF ) f . seek ( 0 ) match = _getheader ( drh . headers , 'if-none-match' ) if match is not None : if drh . check_cache ( e_tag , match ) : f . close ( ) return None drh . send_header ( "ETag" , e_tag , end_header = True ) drh . send_header ( "Cache-Control" , "max-age={0}" . format ( self . max_age ) , end_header = True ) drh . send_response ( code ) drh . send_header ( "Content-Type" , ctype ) drh . send_header ( "Content-Length" , size ) drh . end_headers ( ) return f self . _add_file_mask ( start , method_str , send_text ) | Adds a handler that produces a plain text response . | 419 | 10 |
14,465 | def add_special_file ( self , mask , path , from_quick_server , ctype = None ) : full_path = path if not from_quick_server else os . path . join ( os . path . dirname ( __file__ ) , path ) def read_file ( _req , _args ) : with open ( full_path , 'rb' ) as f_out : return Response ( f_out . read ( ) , ctype = ctype ) self . add_text_get_mask ( mask , read_file ) self . set_file_argc ( mask , 0 ) | Adds a special file that might have a different actual path than its address . | 132 | 15 |
14,466 | def mirror_file ( self , path_to , path_from , from_quick_server = True ) : full_path = path_from if not from_quick_server else os . path . join ( os . path . dirname ( __file__ ) , path_from ) if self . _mirror is None : if not self . _symlink_mirror ( path_to , full_path , init = True ) : self . _poll_mirror ( path_to , full_path , init = True ) return impl = self . _mirror [ "impl" ] if impl == "symlink" : self . _symlink_mirror ( path_to , full_path , init = False ) elif impl == "poll" : self . _poll_mirror ( path_to , full_path , init = False ) else : raise ValueError ( "unknown mirror implementation: {0}" . format ( impl ) ) | Mirrors a file to a different location . Each time the file changes while the process is running it will be copied to path_to overwriting the destination . | 207 | 33 |
14,467 | def link_empty_favicon_fallback ( self ) : self . favicon_fallback = os . path . join ( os . path . dirname ( __file__ ) , 'favicon.ico' ) | Links the empty favicon as default favicon . | 49 | 10 |
14,468 | def get_token_obj ( self , token , expire = _token_default ) : if expire == _token_default : expire = self . get_default_token_expiration ( ) now = get_time ( ) until = now + expire if expire is not None else None with self . _token_lock : # _token_timings is keys sorted by time first_valid = None for ( pos , k ) in enumerate ( self . _token_timings ) : t = self . _token_map [ k ] [ 0 ] if t is None or t > now : first_valid = pos break if first_valid is None : self . _token_map = { } self . _token_timings = [ ] else : for k in self . _token_timings [ : first_valid ] : del self . _token_map [ k ] self . _token_timings = self . _token_timings [ first_valid : ] if until is None or until > now : if token not in self . _token_map : self . _token_map [ token ] = ( until , { } ) self . _token_timings . append ( token ) else : self . _token_map [ token ] = ( until , self . _token_map [ token ] [ 1 ] ) self . _token_timings . sort ( key = lambda k : ( 1 if self . _token_map [ k ] [ 0 ] is None else 0 , self . _token_map [ k ] [ 0 ] ) ) return self . _token_map [ token ] [ 1 ] else : if token in self . _token_map : self . _token_timings = [ k for k in self . _token_timings if k != token ] del self . _token_map [ token ] return { } | Returns or creates the object associaten with the given token . | 396 | 12 |
14,469 | def handle_cmd ( self , cmd ) : cmd = cmd . strip ( ) segments = [ ] for s in cmd . split ( ) : # remove bash-like comments if s . startswith ( '#' ) : break # TODO implement escape sequences (also for \#) segments . append ( s ) args = [ ] if not len ( segments ) : return # process more specific commands first while segments : cur_cmd = "_" . join ( segments ) if cur_cmd in self . _cmd_methods : argc = self . _cmd_argc [ cur_cmd ] if argc is not None and len ( args ) != argc : msg ( 'command {0} expects {1} argument(s), got {2}' , " " . join ( segments ) , argc , len ( args ) ) return self . _cmd_methods [ cur_cmd ] ( args ) return args . insert ( 0 , segments . pop ( ) ) # invalid command prefix = '_' . join ( args ) + '_' matches = filter ( lambda cmd : cmd . startswith ( prefix ) , self . _cmd_methods . keys ( ) ) candidates = set ( [ ] ) for m in matches : if len ( m ) <= len ( prefix ) : continue m = m [ len ( prefix ) : ] if '_' in m : m = m [ : m . index ( '_' ) ] candidates . add ( m ) if len ( candidates ) : msg ( 'command "{0}" needs more arguments:' , ' ' . join ( args ) ) for c in candidates : msg ( ' {0}' , c ) else : msg ( 'command "{0}" invalid; type ' + 'help or use <TAB> for a list of commands' , ' ' . join ( args ) ) | Handles a single server command . | 392 | 7 |
14,470 | def handle_request ( self ) : timeout = self . socket . gettimeout ( ) if timeout is None : timeout = self . timeout elif self . timeout is not None : timeout = min ( timeout , self . timeout ) ctime = get_time ( ) done_req = False shutdown_latency = self . shutdown_latency if timeout is not None : shutdown_latency = min ( shutdown_latency , timeout ) if shutdown_latency is not None else timeout while not ( self . done or done_req ) and ( timeout is None or timeout == 0 or ( get_time ( ) - ctime ) < timeout ) : try : fd_sets = select . select ( [ self ] , [ ] , [ ] , shutdown_latency ) except ( OSError , select . error ) as e : if e . args [ 0 ] != errno . EINTR : raise # treat EINTR as shutdown_latency timeout fd_sets = [ [ ] , [ ] , [ ] ] for _fd in fd_sets [ 0 ] : done_req = True self . _handle_request_noblock ( ) if timeout == 0 : break if not ( self . done or done_req ) : # don't handle timeouts if we should shut down the server instead self . handle_timeout ( ) | Handles an HTTP request . The actual HTTP request is handled using a different thread . | 285 | 17 |
14,471 | def serve_forever ( self ) : self . start_cmd_loop ( ) try : while not self . done : self . handle_request ( ) except KeyboardInterrupt : # clean error output if log file is STD_ERR if log_file == sys . stderr : log_file . write ( "\n" ) finally : if self . _clean_up_call is not None : self . _clean_up_call ( ) self . done = True | Starts the server handling commands and HTTP requests . The server will loop until done is True or a KeyboardInterrupt is received . | 101 | 26 |
14,472 | def can_ignore_error ( self , reqhnd = None ) : value = sys . exc_info ( ) [ 1 ] try : if isinstance ( value , BrokenPipeError ) or isinstance ( value , ConnectionResetError ) : return True except NameError : pass if not self . done : return False if not isinstance ( value , socket . error ) : return False need_close = value . errno == 9 if need_close and reqhnd is not None : reqhnd . close_connection = 1 return need_close | Tests if the error is worth reporting . | 117 | 9 |
14,473 | def handle_error ( self , request , client_address ) : if self . can_ignore_error ( ) : return thread = threading . current_thread ( ) msg ( "Error in request ({0}): {1} in {2}\n{3}" , client_address , repr ( request ) , thread . name , traceback . format_exc ( ) ) | Handle an error gracefully . | 80 | 6 |
14,474 | def _findRow ( subNo , model ) : items = model . findItems ( str ( subNo ) ) if len ( items ) == 0 : return None if len ( items ) > 1 : raise IndexError ( "Too many items with sub number %s" % subNo ) return items [ 0 ] . row ( ) | Finds a row in a given model which has a column with a given number . | 69 | 17 |
14,475 | def _subtitlesAdded ( self , path , subNos ) : def action ( current , count , model , row ) : _setSubNo ( current + count , model , row ) def count ( current , nos ) : ret = 0 for no in nos : if current >= no : ret += 1 # consider: current = 0, nos = [0, 1, 2, 3] # in that case, current should be prepended by all nos current += 1 return ret self . _changeSubNos ( path , subNos , count , action ) | When subtitle is added all syncPoints greater or equal than a new subtitle are incremented . | 119 | 18 |
14,476 | def _subtitlesRemoved ( self , path , subNos ) : def action ( current , count , model , row ) : if count . equal > 0 : model . removeRow ( row ) else : _setSubNo ( current - count . greater_equal , model , row ) def count ( current , nos ) : return _GtEqCount ( current , nos ) self . _changeSubNos ( path , subNos , count , action ) | When subtitle is removed all syncPoints greater than removed subtitle are decremented . SyncPoint equal to removed subtitle is also removed . | 99 | 25 |
14,477 | def _get_csv_fieldnames ( csv_reader ) : fieldnames = [ ] for row in csv_reader : for col in row : field = ( col . strip ( ) . replace ( '"' , "" ) . replace ( " " , "" ) . replace ( "(" , "" ) . replace ( ")" , "" ) . lower ( ) ) fieldnames . append ( field ) if "id" in fieldnames : break else : # this is not a row with fieldnames del fieldnames [ : ] if not fieldnames : return None # remove trailing unannotated fields while True : field = fieldnames . pop ( ) if field : fieldnames . append ( field ) break # name unannotated fields suffix = 1 for index , field in enumerate ( fieldnames ) : if not field : fieldnames [ index ] = "field{}" . format ( suffix ) suffix += 1 return fieldnames | Finds fieldnames in Polarion exported csv file . | 193 | 12 |
14,478 | def _get_results ( csv_reader , fieldnames ) : fieldnames_count = len ( fieldnames ) results = [ ] for row in csv_reader : for col in row : if col : break else : # empty row, skip it continue record = OrderedDict ( list ( zip ( fieldnames , row ) ) ) # skip rows that were already exported if record . get ( "exported" ) == "yes" : continue row_len = len ( row ) if fieldnames_count > row_len : for key in fieldnames [ row_len : ] : record [ key ] = None results . append ( record ) return results | Maps data to fieldnames . | 140 | 6 |
14,479 | def get_imported_data ( csv_file , * * kwargs ) : open_args = [ ] open_kwargs = { } try : # pylint: disable=pointless-statement unicode open_args . append ( "rb" ) except NameError : open_kwargs [ "encoding" ] = "utf-8" with open ( os . path . expanduser ( csv_file ) , * open_args , * * open_kwargs ) as input_file : reader = _get_csv_reader ( input_file ) fieldnames = _get_csv_fieldnames ( reader ) if not fieldnames : raise Dump2PolarionException ( "Cannot find field names in CSV file '{}'" . format ( csv_file ) ) results = _get_results ( reader , fieldnames ) if not results : raise Dump2PolarionException ( "No results read from CSV file '{}'" . format ( csv_file ) ) testrun = _get_testrun_from_csv ( input_file , reader ) return xunit_exporter . ImportedData ( results = results , testrun = testrun ) | Reads the content of the Polarion exported csv file and returns imported data . | 258 | 17 |
14,480 | def import_csv ( csv_file , * * kwargs ) : records = get_imported_data ( csv_file , * * kwargs ) _check_required_columns ( csv_file , records . results ) return records | Imports data and checks that all required columns are there . | 56 | 12 |
14,481 | def load_config ( filename ) : if filename is None : filename = '' abs_filename = os . path . join ( os . getcwd ( ) , filename ) global FILE # find the config file if os . path . isfile ( filename ) : FILE = filename elif os . path . isfile ( abs_filename ) : FILE = abs_filename elif os . path . isfile ( FILE ) : pass else : if os . path . dirname ( filename ) : file_not_found = filename else : file_not_found = abs_filename file_not_found_message ( file_not_found ) # load config init ( FILE ) | Load data from config file to cfg that can be accessed by get set afterwards . | 141 | 17 |
14,482 | def init ( FILE ) : try : cfg . read ( FILE ) global _loaded _loaded = True except : file_not_found_message ( FILE ) | Read config file | 34 | 3 |
14,483 | def get ( section , key ) : # FILE = 'config_misc' if not _loaded : init ( FILE ) try : return cfg . getfloat ( section , key ) except Exception : try : return cfg . getint ( section , key ) except : try : return cfg . getboolean ( section , key ) except : return cfg . get ( section , key ) | returns the value of a given key of a given section of the main config file . | 82 | 18 |
14,484 | def to_internal_value ( self , data ) : if "session_event" in data : data [ "helper_metadata" ] [ "session_event" ] = data [ "session_event" ] return super ( InboundSerializer , self ) . to_internal_value ( data ) | Adds extra data to the helper_metadata field . | 65 | 10 |
14,485 | def acceptAlias ( decoratedFunction ) : def wrapper ( self , * args , * * kwargs ) : SubAssert ( isinstance ( self , AliasBase ) ) if len ( args ) > 0 : key = args [ 0 ] if args [ 0 ] in self . _aliases . keys ( ) : key = self . _aliases [ args [ 0 ] ] return decoratedFunction ( self , key , * args [ 1 : ] , * * kwargs ) return decoratedFunction ( self , * args , * * kwargs ) return wrapper | This function should be used as a decorator . Each class method that is decorated will be able to accept alias or original names as a first function positional parameter . | 118 | 32 |
14,486 | def h ( values ) : ent = np . true_divide ( values , np . sum ( values ) ) return - np . sum ( np . multiply ( ent , np . log2 ( ent ) ) ) | Function calculates entropy . | 45 | 4 |
14,487 | def info_gain_nominal ( x , y , separate_max ) : x_vals = np . unique ( x ) # unique values if len ( x_vals ) < 3 : # if there is just one unique value return None y_dist = Counter ( y ) # label distribution h_y = h ( y_dist . values ( ) ) # class entropy # calculate distributions and splits in accordance with feature type dist , splits = nominal_splits ( x , y , x_vals , y_dist , separate_max ) indices , repeat = ( range ( 1 , len ( dist ) ) , 1 ) if len ( dist ) < 50 else ( range ( 1 , len ( dist ) , len ( dist ) / 10 ) , 3 ) interval = len ( dist ) / 10 max_ig , max_i , iteration = 0 , 1 , 0 while iteration < repeat : for i in indices : dist0 = np . sum ( [ el for el in dist [ : i ] ] ) # iter 0: take first distribution dist1 = np . sum ( [ el for el in dist [ i : ] ] ) # iter 0: take the other distributions without first coef = np . true_divide ( [ np . sum ( dist0 . values ( ) ) , np . sum ( dist1 . values ( ) ) ] , len ( y ) ) ig = h_y - np . dot ( coef , [ h ( dist0 . values ( ) ) , h ( dist1 . values ( ) ) ] ) # calculate information gain if ig > max_ig : max_ig , max_i = ig , i # store index and value of maximal information gain iteration += 1 if repeat > 1 : interval = int ( interval * 0.5 ) if max_i in indices and interval > 0 : middle_index = indices . index ( max_i ) else : break min_index = middle_index if middle_index == 0 else middle_index - 1 max_index = middle_index if middle_index == len ( indices ) - 1 else middle_index + 1 indices = range ( indices [ min_index ] , indices [ max_index ] , interval ) # store splits of maximal information gain in accordance with feature type return float ( max_ig ) , [ splits [ : max_i ] , splits [ max_i : ] ] | Function calculates information gain for discrete features . If feature is continuous it is firstly discretized . | 497 | 20 |
14,488 | def multinomLog2 ( selectors ) : ln2 = 0.69314718055994528622 noAll = sum ( selectors ) lgNf = math . lgamma ( noAll + 1.0 ) / ln2 # log2(N!) lgnFac = [ ] for selector in selectors : if selector == 0 or selector == 1 : lgnFac . append ( 0.0 ) elif selector == 2 : lgnFac . append ( 1.0 ) elif selector == noAll : lgnFac . append ( lgNf ) else : lgnFac . append ( math . lgamma ( selector + 1.0 ) / ln2 ) return lgNf - sum ( lgnFac ) | Function calculates logarithm 2 of a kind of multinom . | 163 | 15 |
14,489 | def calc_mdl ( yx_dist , y_dist ) : prior = multinomLog2 ( y_dist . values ( ) ) prior += multinomLog2 ( [ len ( y_dist . keys ( ) ) - 1 , sum ( y_dist . values ( ) ) ] ) post = 0 for x_val in yx_dist : post += multinomLog2 ( [ x_val . get ( c , 0 ) for c in y_dist . keys ( ) ] ) post += multinomLog2 ( [ len ( y_dist . keys ( ) ) - 1 , sum ( x_val . values ( ) ) ] ) return ( prior - post ) / float ( sum ( y_dist . values ( ) ) ) | Function calculates mdl with given label distributions . | 164 | 9 |
14,490 | def mdl_nominal ( x , y , separate_max ) : x_vals = np . unique ( x ) # unique values if len ( x_vals ) == 1 : # if there is just one unique value return None y_dist = Counter ( y ) # label distribution # calculate distributions and splits in accordance with feature type dist , splits = nominal_splits ( x , y , x_vals , y_dist , separate_max ) prior_mdl = calc_mdl ( dist , y_dist ) max_mdl , max_i = 0 , 1 for i in range ( 1 , len ( dist ) ) : # iter 0: take first distribution dist0_x = [ el for el in dist [ : i ] ] dist0_y = np . sum ( dist0_x ) post_mdl0 = calc_mdl ( dist0_x , dist0_y ) # iter 0: take the other distributions without first dist1_x = [ el for el in dist [ i : ] ] dist1_y = np . sum ( dist1_x ) post_mdl1 = calc_mdl ( dist1_x , dist1_y ) coef = np . true_divide ( [ sum ( dist0_y . values ( ) ) , sum ( dist1_y . values ( ) ) ] , len ( x ) ) mdl_val = prior_mdl - np . dot ( coef , [ post_mdl0 , post_mdl1 ] ) # calculate mdl if mdl_val > max_mdl : max_mdl , max_i = mdl_val , i # store splits of maximal mdl in accordance with feature type split = [ splits [ : max_i ] , splits [ max_i : ] ] return ( max_mdl , split ) | Function calculates minimum description length for discrete features . If feature is continuous it is firstly discretized . | 397 | 21 |
14,491 | def url ( section = "postGIS" , config_file = None ) : cfg . load_config ( config_file ) try : pw = keyring . get_password ( cfg . get ( section , "database" ) , cfg . get ( section , "username" ) ) except NoSectionError as e : print ( "There is no section {section} in your config file. Please " "choose one available section from your config file or " "specify a new one!" . format ( section = section ) ) exit ( - 1 ) if pw is None : try : pw = cfg . get ( section , "pw" ) except option : pw = getpass . getpass ( prompt = "No password available in your " "keyring for database {database}. " "\n\nEnter your password to " "store it in " "keyring:" . format ( database = section ) ) keyring . set_password ( section , cfg . get ( section , "username" ) , pw ) except NoSectionError : print ( "Unable to find the 'postGIS' section in oemof's config." + "\nExiting." ) exit ( - 1 ) return "postgresql+psycopg2://{user}:{passwd}@{host}:{port}/{db}" . format ( user = cfg . get ( section , "username" ) , passwd = pw , host = cfg . get ( section , "host" ) , db = cfg . get ( section , "database" ) , port = int ( cfg . get ( section , "port" ) ) ) | Retrieve the URL used to connect to the database . | 359 | 11 |
14,492 | def get_endpoints_using_raw_json_emission ( domain ) : uri = "http://{0}/data.json" . format ( domain ) r = requests . get ( uri ) r . raise_for_status ( ) return r . json ( ) | Implements a raw HTTP GET against the entire Socrata portal for the domain in question . This method uses the first of the two ways of getting this information the raw JSON endpoint . | 61 | 38 |
14,493 | def get_endpoints_using_catalog_api ( domain , token ) : # Token required for all requests. Providing login info instead is also possible but I didn't implement it. headers = { "X-App-Token" : token } # The API will return only 100 requests at a time by default. We can ask for more, but the server seems to start # to lag after a certain N requested. Instead, let's pick a less conservative pagination limit and spool up with # offsets. # # At the time this library was written, Socrata would return all of its results in a contiguous list. Once you # maxed out, you wouldn't get any more list items. Later on this was changed so that now if you exhaust portal # entities, it will actually take you back to the beginning of the list again! # # As a result we need to perform our own set-wise check to make sure that what we get isn't just a bit of the # same list all over again. uri = "http://api.us.socrata.com/api/catalog/v1?domains={0}&offset={1}&limit=1000" ret = [ ] endpoints_thus_far = set ( ) offset = 0 while True : try : r = requests . get ( uri . format ( domain , offset ) , headers = headers ) r . raise_for_status ( ) except requests . HTTPError : raise requests . HTTPError ( "An HTTP error was raised during Socrata API ingestion." . format ( domain ) ) data = r . json ( ) endpoints_returned = { r [ 'resource' ] [ 'id' ] for r in data [ 'results' ] } new_endpoints = endpoints_returned . difference ( endpoints_thus_far ) if len ( new_endpoints ) >= 999 : # we are continuing to stream # TODO: 999 not 1000 b/c the API suffers off-by-one errors. Can also do worse, however. Compensate? # cf. https://github.com/ResidentMario/pysocrata/issues/1 ret += data [ 'results' ] endpoints_thus_far . update ( new_endpoints ) offset += 1000 continue else : # we are ending on a stream with some old endpoints on it ret += [ r for r in data [ 'results' ] if r [ 'resource' ] [ 'id' ] in new_endpoints ] break return ret | Implements a raw HTTP GET against the entire Socrata portal for the domain in question . This method uses the second of the two ways of getting this information the catalog API . | 533 | 37 |
14,494 | def count_resources ( domain , token ) : resources = get_resources ( domain , token ) return dict ( Counter ( [ r [ 'resource' ] [ 'type' ] for r in resources if r [ 'resource' ] [ 'type' ] != 'story' ] ) ) | Given the domain in question generates counts for that domain of each of the different data types . | 60 | 18 |
14,495 | def stratify_by_features ( features , n_strata , * * kwargs ) : n_items = features . shape [ 0 ] km = KMeans ( n_clusters = n_strata , * * kwargs ) allocations = km . fit_predict ( X = features ) return Strata ( allocations ) | Stratify by clustering the items in feature space | 73 | 11 |
14,496 | def _heuristic_bin_width ( obs ) : IQR = sp . percentile ( obs , 75 ) - sp . percentile ( obs , 25 ) N = len ( obs ) return 2 * IQR * N ** ( - 1 / 3 ) | Optimal histogram bin width based on the Freedman - Diaconis rule | 52 | 16 |
14,497 | def auto_stratify ( scores , * * kwargs ) : if 'stratification_method' in kwargs : method = kwargs [ 'stratification_method' ] else : method = 'cum_sqrt_F' if 'stratification_n_strata' in kwargs : n_strata = kwargs [ 'stratification_n_strata' ] else : n_strata = 'auto' if 'stratification_n_bins' in kwargs : n_bins = kwargs [ 'stratification_n_bins' ] strata = stratify_by_scores ( scores , n_strata , method = method , n_bins = n_bins ) else : strata = stratify_by_scores ( scores , n_strata , method = method ) return strata | Generate Strata instance automatically | 196 | 6 |
14,498 | def _sample_stratum ( self , pmf = None , replace = True ) : if pmf is None : # Use weights pmf = self . weights_ if not replace : # Find strata which have been fully sampled (i.e. are now empty) empty = ( self . _n_sampled >= self . sizes_ ) if np . any ( empty ) : pmf = copy . copy ( pmf ) pmf [ empty ] = 0 if np . sum ( pmf ) == 0 : raise ( RuntimeError ) pmf /= np . sum ( pmf ) return np . random . choice ( self . indices_ , p = pmf ) | Sample a stratum | 142 | 4 |
14,499 | def _sample_in_stratum ( self , stratum_idx , replace = True ) : if replace : stratum_loc = np . random . choice ( self . sizes_ [ stratum_idx ] ) else : # Extract only the unsampled items stratum_locs = np . where ( ~ self . _sampled [ stratum_idx ] ) [ 0 ] stratum_loc = np . random . choice ( stratum_locs ) # Record that item has been sampled self . _sampled [ stratum_idx ] [ stratum_loc ] = True self . _n_sampled [ stratum_idx ] += 1 # Get generic location loc = self . allocations_ [ stratum_idx ] [ stratum_loc ] return loc | Sample an item uniformly from a stratum | 170 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.