idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
245,400
def process_config ( ctx , configfile ) : from honeycomb . commands . service . run import run as service_run # from honeycomb.commands.service.logs import logs as service_logs from honeycomb . commands . service . install import install as service_install from honeycomb . commands . integration . install import instal...
Process a yaml config with instructions .
655
8
245,401
def get_plugin_path ( home , plugin_type , plugin_name , editable = False ) : if editable : plugin_path = plugin_name else : plugin_path = os . path . join ( home , plugin_type , plugin_name ) return os . path . realpath ( plugin_path )
Return path to plugin .
68
5
245,402
def install_plugin ( pkgpath , plugin_type , install_path , register_func ) : service_name = os . path . basename ( pkgpath ) if os . path . exists ( os . path . join ( install_path , service_name ) ) : raise exceptions . PluginAlreadyInstalled ( pkgpath ) if os . path . exists ( pkgpath ) : logger . debug ( "%s exists...
Install specified plugin .
282
4
245,403
def install_deps ( pkgpath ) : if os . path . exists ( os . path . join ( pkgpath , "requirements.txt" ) ) : logger . debug ( "installing dependencies" ) click . secho ( "[*] Installing dependencies" ) pipargs = [ "install" , "--target" , os . path . join ( pkgpath , defs . DEPS_DIR ) , "--ignore-installed" , "-r" , os...
Install plugin dependencies using pip .
163
6
245,404
def copy_file ( src , dst ) : try : fin = os . open ( src , READ_FLAGS ) stat = os . fstat ( fin ) fout = os . open ( dst , WRITE_FLAGS , stat . st_mode ) for x in iter ( lambda : os . read ( fin , BUFFER_SIZE ) , b"" ) : os . write ( fout , x ) finally : try : os . close ( fin ) except Exception as exc : logger . debu...
Copy a single file .
159
5
245,405
def copy_tree ( src , dst , symlinks = False , ignore = [ ] ) : names = os . listdir ( src ) if not os . path . exists ( dst ) : os . makedirs ( dst ) errors = [ ] for name in names : if name in ignore : continue srcname = os . path . join ( src , name ) dstname = os . path . join ( dst , name ) try : if symlinks and o...
Copy a full directory structure .
221
6
245,406
def install_dir ( pkgpath , install_path , register_func , delete_after_install = False ) : logger . debug ( "%s is a directory, attempting to validate" , pkgpath ) plugin = register_func ( pkgpath ) logger . debug ( "%s looks good, copying to %s" , pkgpath , install_path ) try : copy_tree ( pkgpath , os . path . join ...
Install plugin from specified directory .
219
6
245,407
def install_from_zip ( pkgpath , install_path , register_func , delete_after_install = False ) : logger . debug ( "%s is a file, attempting to load zip" , pkgpath ) pkgtempdir = tempfile . mkdtemp ( prefix = "honeycomb_" ) try : with zipfile . ZipFile ( pkgpath ) as pkgzip : pkgzip . extractall ( pkgtempdir ) except zi...
Install plugin from zipfile .
207
6
245,408
def install_from_repo ( pkgname , plugin_type , install_path , register_func ) : rsession = requests . Session ( ) rsession . mount ( "https://" , HTTPAdapter ( max_retries = 3 ) ) logger . debug ( "trying to install %s from online repo" , pkgname ) pkgurl = "{}/{}s/{}.zip" . format ( defs . GITHUB_RAW , plugin_type , ...
Install plugin from online repo .
403
6
245,409
def uninstall_plugin ( pkgpath , force ) : pkgname = os . path . basename ( pkgpath ) if os . path . exists ( pkgpath ) : if not force : click . confirm ( "[?] Are you sure you want to delete `{}` from honeycomb?" . format ( pkgname ) , abort = True ) try : shutil . rmtree ( pkgpath ) logger . debug ( "successfully uni...
Uninstall a plugin .
181
5
245,410
def list_remote_plugins ( installed_plugins , plugin_type ) : click . secho ( "\n[*] Additional plugins from online repository:" ) try : rsession = requests . Session ( ) rsession . mount ( "https://" , HTTPAdapter ( max_retries = 3 ) ) r = rsession . get ( "{0}/{1}s/{1}s.txt" . format ( defs . GITHUB_RAW , plugin_type...
List remote plugins from online repo .
209
7
245,411
def list_local_plugins ( plugin_type , plugins_path , plugin_details ) : installed_plugins = list ( ) for plugin in next ( os . walk ( plugins_path ) ) [ 1 ] : s = plugin_details ( plugin ) installed_plugins . append ( plugin ) click . secho ( s ) if not installed_plugins : click . secho ( "[*] You do not have any {0}s...
List local plugins with details .
121
6
245,412
def parse_plugin_args ( command_args , config_args ) : parsed_args = dict ( ) for arg in command_args : kv = arg . split ( "=" ) if len ( kv ) != 2 : raise click . UsageError ( "Invalid parameter '{}', must be in key=value format" . format ( arg ) ) parsed_args [ kv [ 0 ] ] = config_utils . get_truetype ( kv [ 1 ] ) fo...
Parse command line arguments based on the plugin s parameters config .
288
13
245,413
def get_select_items ( items ) : option_items = list ( ) for item in items : if isinstance ( item , dict ) and defs . VALUE in item and defs . LABEL in item : option_items . append ( item [ defs . VALUE ] ) else : raise exceptions . ParametersFieldError ( item , "a dictionary with {} and {}" . format ( defs . LABEL , d...
Return list of possible select items .
103
7
245,414
def print_plugin_args ( plugin_path ) : args = config_utils . get_config_parameters ( plugin_path ) args_format = "{:20} {:10} {:^15} {:^10} {:25}" title = args_format . format ( defs . NAME . upper ( ) , defs . TYPE . upper ( ) , defs . DEFAULT . upper ( ) , defs . REQUIRED . upper ( ) , defs . DESCRIPTION . upper ( )...
Print plugin parameters table .
257
5
245,415
def configure_integration ( path ) : integration = register_integration ( path ) integration_args = { } try : with open ( os . path . join ( path , ARGS_JSON ) ) as f : integration_args = json . loads ( f . read ( ) ) except Exception as exc : logger . debug ( str ( exc ) , exc_info = True ) raise click . ClickExceptio...
Configure and enable an integration .
243
7
245,416
def send_alert_to_subscribed_integrations ( alert ) : valid_configured_integrations = get_valid_configured_integrations ( alert ) for configured_integration in valid_configured_integrations : threading . Thread ( target = create_integration_alert_and_call_send , args = ( alert , configured_integration ) ) . start ( )
Send Alert to relevant integrations .
85
7
245,417
def get_valid_configured_integrations ( alert ) : if not configured_integrations : return [ ] # Collect all integrations that are configured for specific alert_type # or have no specific supported_event_types (i.e., all alert types) valid_configured_integrations = [ _ for _ in configured_integrations if _ . integration...
Return a list of integrations for alert filtered by alert_type .
130
14
245,418
def create_integration_alert_and_call_send ( alert , configured_integration ) : integration_alert = IntegrationAlert ( alert = alert , configured_integration = configured_integration , status = IntegrationAlertStatuses . PENDING . name , retries = configured_integration . integration . max_send_retries ) send_alert_to_...
Create an IntegrationAlert object and send it to Integration .
89
11
245,419
def send_alert_to_configured_integration ( integration_alert ) : try : alert = integration_alert . alert configured_integration = integration_alert . configured_integration integration = configured_integration . integration integration_actions_instance = configured_integration . integration . module alert_fields = dict...
Send IntegrationAlert to configured integration .
662
7
245,420
def poll_integration_alert_data ( integration_alert ) : logger . info ( "Polling information for integration alert %s" , integration_alert ) try : configured_integration = integration_alert . configured_integration integration_actions_instance = configured_integration . integration . module output_data , output_file_co...
Poll for updates on waiting IntegrationAlerts .
329
9
245,421
def wait_until ( func , check_return_value = True , total_timeout = 60 , interval = 0.5 , exc_list = None , error_message = "" , * args , * * kwargs ) : start_function = time . time ( ) while time . time ( ) - start_function < total_timeout : try : logger . debug ( "executing {} with args {} {}" . format ( func , args ...
Run a command in a loop until desired result or timeout occurs .
187
13
245,422
def search_json_log ( filepath , key , value ) : try : with open ( filepath , "r" ) as fh : for line in fh . readlines ( ) : log = json . loads ( line ) if key in log and log [ key ] == value : return log except IOError : pass return False
Search json log file for a key = value pair .
71
11
245,423
def list_commands ( self , ctx ) : rv = [ ] files = [ _ for _ in next ( os . walk ( self . folder ) ) [ 2 ] if not _ . startswith ( "_" ) and _ . endswith ( ".py" ) ] for filename in files : rv . append ( filename [ : - 3 ] ) rv . sort ( ) return rv
List commands from folder .
87
5
245,424
def get_command ( self , ctx , name ) : plugin = os . path . basename ( self . folder ) try : command = importlib . import_module ( "honeycomb.commands.{}.{}" . format ( plugin , name ) ) except ImportError : raise click . UsageError ( "No such command {} {}\n\n{}" . format ( plugin , name , self . get_help ( ctx ) ) )...
Fetch command from folder .
105
6
245,425
def cli ( ctx , home , iamroot , config , verbose ) : _mkhome ( home ) setup_logging ( home , verbose ) logger . debug ( "Honeycomb v%s" , __version__ , extra = { "version" : __version__ } ) logger . debug ( "running command %s (%s)" , ctx . command . name , ctx . params , extra = { "command" : ctx . command . name , "...
Honeycomb is a honeypot framework .
283
9
245,426
def setup_logging ( home , verbose ) : logging . setLoggerClass ( MyLogger ) logging . config . dictConfig ( { "version" : 1 , "disable_existing_loggers" : False , "formatters" : { "console" : { "format" : "%(levelname)-8s [%(asctime)s %(name)s] %(filename)s:%(lineno)s %(funcName)s: %(message)s" , } , "json" : { "()" :...
Configure logging for honeycomb .
335
7
245,427
def makeRecord ( self , name , level , fn , lno , msg , args , exc_info , func = None , extra = None , sinfo = None ) : # See below commented section for a simple example of what the docstring refers to if six . PY2 : rv = logging . LogRecord ( name , level , fn , lno , msg , args , exc_info , func ) else : rv = loggin...
Override default logger to allow overriding of internal attributes .
247
10
245,428
def stop ( ctx , service , editable ) : logger . debug ( "running command %s (%s)" , ctx . command . name , ctx . params , extra = { "command" : ctx . command . name , "params" : ctx . params } ) home = ctx . obj [ "HOME" ] service_path = plugin_utils . get_plugin_path ( home , SERVICES , service , editable ) logger . ...
Stop a running service daemon .
408
6
245,429
def logs ( ctx , services , num , follow ) : logger . debug ( "running command %s (%s)" , ctx . command . name , ctx . params , extra = { "command" : ctx . command . name , "params" : ctx . params } ) home = ctx . obj [ "HOME" ] services_path = os . path . join ( home , SERVICES ) tail_threads = [ ] for service in serv...
Show logs of daemonized service .
260
7
245,430
def get_integration_module ( integration_path ) : # add custom paths so imports would work paths = [ os . path . join ( __file__ , ".." , ".." ) , # to import integrationmanager os . path . join ( integration_path , ".." ) , # to import integration itself os . path . join ( integration_path , DEPS_DIR ) , # to import i...
Add custom paths to sys and import integration module .
205
10
245,431
def register_integration ( package_folder ) : logger . debug ( "registering integration %s" , package_folder ) package_folder = os . path . realpath ( package_folder ) if not os . path . exists ( package_folder ) : raise IntegrationNotFound ( os . path . basename ( package_folder ) ) json_config_path = os . path . join...
Register a honeycomb integration .
253
6
245,432
def list ( ctx , remote ) : logger . debug ( "running command %s (%s)" , ctx . command . name , ctx . params , extra = { "command" : ctx . command . name , "params" : ctx . params } ) click . secho ( "[*] Installed integrations:" ) home = ctx . obj [ "HOME" ] integrations_path = os . path . join ( home , INTEGRATIONS )...
List integrations .
305
4
245,433
def run ( ctx , service , args , show_args , daemon , editable , integration ) : home = ctx . obj [ "HOME" ] service_path = plugin_utils . get_plugin_path ( home , SERVICES , service , editable ) service_log_path = os . path . join ( service_path , LOGS_DIR ) logger . debug ( "running command %s (%s)" , ctx . command ....
Load and run a specific service .
733
7
245,434
def read_lines ( self , file_path , empty_lines = False , signal_ready = True ) : file_handler , file_id = self . _get_file ( file_path ) file_handler . seek ( 0 , os . SEEK_END ) if signal_ready : self . signal_ready ( ) while self . thread_server . is_alive ( ) : line = six . text_type ( file_handler . readline ( ) ,...
Fetch lines from file .
184
6
245,435
def on_server_start ( self ) : self . _container = self . _docker_client . containers . run ( self . docker_image_name , detach = True , * * self . docker_params ) self . signal_ready ( ) for log_line in self . get_lines ( ) : try : alert_dict = self . parse_line ( log_line ) if alert_dict : self . add_alert_to_queue (...
Service run loop function .
112
5
245,436
def on_server_shutdown ( self ) : if not self . _container : return self . _container . stop ( ) self . _container . remove ( v = True , force = True )
Stop the container before shutting down .
42
7
245,437
def uninstall ( ctx , yes , integrations ) : logger . debug ( "running command %s (%s)" , ctx . command . name , ctx . params , extra = { "command" : ctx . command . name , "params" : ctx . params } ) home = ctx . obj [ "HOME" ] for integration in integrations : integration_path = plugin_utils . get_plugin_path ( home ...
Uninstall a integration .
115
5
245,438
def install ( ctx , services , delete_after_install = False ) : logger . debug ( "running command %s (%s)" , ctx . command . name , ctx . params , extra = { "command" : ctx . command . name , "params" : ctx . params } ) home = ctx . obj [ "HOME" ] services_path = os . path . join ( home , SERVICES ) installed_all_plugi...
Install a honeypot service from the online library local path or zipfile .
169
15
245,439
def uninstall ( ctx , yes , services ) : logger . debug ( "running command %s (%s)" , ctx . command . name , ctx . params , extra = { "command" : ctx . command . name , "params" : ctx . params } ) home = ctx . obj [ "HOME" ] for service in services : service_path = plugin_utils . get_plugin_path ( home , SERVICES , ser...
Uninstall a service .
110
5
245,440
def get_service_module ( service_path ) : # add custom paths so imports would work paths = [ os . path . dirname ( __file__ ) , # this folder, to catch base_service os . path . realpath ( os . path . join ( service_path , ".." ) ) , # service's parent folder for import os . path . realpath ( os . path . join ( service_...
Add custom paths to sys and import service module .
234
10
245,441
def register_service ( package_folder ) : logger . debug ( "registering service %s" , package_folder ) package_folder = os . path . realpath ( package_folder ) if not os . path . exists ( package_folder ) : raise ServiceNotFound ( os . path . basename ( package_folder ) ) json_config_path = os . path . join ( package_f...
Register a honeycomb service .
343
6
245,442
def install ( ctx , integrations , delete_after_install = False ) : logger . debug ( "running command %s (%s)" , ctx . command . name , ctx . params , extra = { "command" : ctx . command . name , "params" : ctx . params } ) home = ctx . obj [ "HOME" ] integrations_path = os . path . join ( home , INTEGRATIONS ) install...
Install a honeycomb integration from the online library local path or zipfile .
180
15
245,443
def configure ( ctx , integration , args , show_args , editable ) : home = ctx . obj [ "HOME" ] integration_path = plugin_utils . get_plugin_path ( home , defs . INTEGRATIONS , integration , editable ) logger . debug ( "running command %s (%s)" , ctx . command . name , ctx . params , extra = { "command" : ctx . command...
Configure an integration with default parameters .
314
8
245,444
def get_match_history ( self , account_id = None , * * kwargs ) : if 'account_id' not in kwargs : kwargs [ 'account_id' ] = account_id url = self . __build_url ( urls . GET_MATCH_HISTORY , * * kwargs ) req = self . executor ( url ) if self . logger : self . logger . info ( 'URL: {0}' . format ( url ) ) if not self . __...
Returns a dictionary containing a list of the most recent Dota matches
140
12
245,445
def get_match_history_by_seq_num ( self , start_at_match_seq_num = None , * * kwargs ) : if 'start_at_match_seq_num' not in kwargs : kwargs [ 'start_at_match_seq_num' ] = start_at_match_seq_num url = self . __build_url ( urls . GET_MATCH_HISTORY_BY_SEQ_NUM , * * kwargs ) req = self . executor ( url ) if self . logger :...
Returns a dictionary containing a list of Dota matches in the order they were recorded
177
15
245,446
def get_match_details ( self , match_id = None , * * kwargs ) : if 'match_id' not in kwargs : kwargs [ 'match_id' ] = match_id url = self . __build_url ( urls . GET_MATCH_DETAILS , * * kwargs ) req = self . executor ( url ) if self . logger : self . logger . info ( 'URL: {0}' . format ( url ) ) if not self . __check_ht...
Returns a dictionary containing the details for a Dota 2 match
141
11
245,447
def get_league_listing ( self ) : url = self . __build_url ( urls . GET_LEAGUE_LISTING ) req = self . executor ( url ) if self . logger : self . logger . info ( 'URL: {0}' . format ( url ) ) if not self . __check_http_err ( req . status_code ) : return response . build ( req , url , self . raw_mode )
Returns a dictionary containing a list of all ticketed leagues
98
11
245,448
def get_live_league_games ( self ) : url = self . __build_url ( urls . GET_LIVE_LEAGUE_GAMES ) req = self . executor ( url ) if self . logger : self . logger . info ( 'URL: {0}' . format ( url ) ) if not self . __check_http_err ( req . status_code ) : return response . build ( req , url , self . raw_mode )
Returns a dictionary containing a list of ticked games in progress
102
12
245,449
def get_team_info_by_team_id ( self , start_at_team_id = None , * * kwargs ) : if 'start_at_team_id' not in kwargs : kwargs [ 'start_at_team_id' ] = start_at_team_id url = self . __build_url ( urls . GET_TEAM_INFO_BY_TEAM_ID , * * kwargs ) req = self . executor ( url ) if self . logger : self . logger . info ( 'URL: {0...
Returns a dictionary containing a in - game teams
168
9
245,450
def get_player_summaries ( self , steamids = None , * * kwargs ) : if not isinstance ( steamids , collections . Iterable ) : steamids = [ steamids ] base64_ids = list ( map ( convert_to_64_bit , filter ( lambda x : x is not None , steamids ) ) ) if 'steamids' not in kwargs : kwargs [ 'steamids' ] = base64_ids url = sel...
Returns a dictionary containing a player summaries
195
8
245,451
def get_heroes ( self , * * kwargs ) : url = self . __build_url ( urls . GET_HEROES , language = self . language , * * kwargs ) req = self . executor ( url ) if self . logger : self . logger . info ( 'URL: {0}' . format ( url ) ) if not self . __check_http_err ( req . status_code ) : return response . build ( req , url...
Returns a dictionary of in - game heroes used to parse ids into localised names
111
17
245,452
def get_tournament_prize_pool ( self , leagueid = None , * * kwargs ) : if 'leagueid' not in kwargs : kwargs [ 'leagueid' ] = leagueid url = self . __build_url ( urls . GET_TOURNAMENT_PRIZE_POOL , * * kwargs ) req = self . executor ( url ) if self . logger : self . logger . info ( 'URL: {0}' . format ( url ) ) if not s...
Returns a dictionary that includes community funded tournament prize pools
146
10
245,453
def get_top_live_games ( self , partner = '' , * * kwargs ) : if 'partner' not in kwargs : kwargs [ 'partner' ] = partner url = self . __build_url ( urls . GET_TOP_LIVE_GAME , * * kwargs ) req = self . executor ( url ) if self . logger : self . logger . info ( 'URL: {0}' . format ( url ) ) if not self . __check_http_er...
Returns a dictionary that includes top MMR live games
137
9
245,454
def __build_url ( self , api_call , * * kwargs ) : kwargs [ 'key' ] = self . api_key if 'language' not in kwargs : kwargs [ 'language' ] = self . language if 'format' not in kwargs : kwargs [ 'format' ] = self . __format api_query = urlencode ( kwargs ) return "{0}{1}?{2}" . format ( urls . BASE_URL , api_call , api_qu...
Builds the api query
118
5
245,455
def __check_http_err ( self , status_code ) : if status_code == 403 : raise exceptions . APIAuthenticationError ( self . api_key ) elif status_code == 503 : raise exceptions . APITimeoutError ( ) else : return False
Raises an exception if we get a http error
60
10
245,456
def item_id ( response ) : dict_keys = [ 'item_0' , 'item_1' , 'item_2' , 'item_3' , 'item_4' , 'item_5' ] new_keys = [ 'item_0_name' , 'item_1_name' , 'item_2_name' , 'item_3_name' , 'item_4_name' , 'item_5_name' ] for player in response [ 'players' ] : for key , new_key in zip ( dict_keys , new_keys ) : for item in i...
Parse the item ids will be available as item_0_name item_1_name item_2_name and so on
171
28
245,457
def get_reviews ( obj ) : ctype = ContentType . objects . get_for_model ( obj ) return models . Review . objects . filter ( content_type = ctype , object_id = obj . id )
Simply returns the reviews for an object .
49
8
245,458
def get_review_average ( obj ) : total = 0 reviews = get_reviews ( obj ) if not reviews : return False for review in reviews : average = review . get_average_rating ( ) if average : total += review . get_average_rating ( ) if total > 0 : return total / reviews . count ( ) return False
Returns the review average for an object .
73
8
245,459
def render_category_averages ( obj , normalize_to = 100 ) : context = { 'reviewed_item' : obj } ctype = ContentType . objects . get_for_model ( obj ) reviews = models . Review . objects . filter ( content_type = ctype , object_id = obj . id ) category_averages = { } for review in reviews : review_category_averages = re...
Renders all the sub - averages for each category .
320
11
245,460
def total_review_average ( obj , normalize_to = 100 ) : ctype = ContentType . objects . get_for_model ( obj ) total_average = 0 reviews = models . Review . objects . filter ( content_type = ctype , object_id = obj . id ) for review in reviews : total_average += review . get_average_rating ( normalize_to ) if reviews : ...
Returns the average for all reviews of the given object .
102
11
245,461
def user_has_reviewed ( obj , user ) : ctype = ContentType . objects . get_for_model ( obj ) try : models . Review . objects . get ( user = user , content_type = ctype , object_id = obj . id ) except models . Review . DoesNotExist : return False return True
Returns True if the user has already reviewed the object .
71
11
245,462
def str_to_bytes ( value : str , expected_length : int ) -> bytes : length = len ( value ) if length != expected_length : raise ValueError ( 'Expects {} characters for decoding; got {}' . format ( expected_length , length ) ) try : encoded = value . encode ( 'ascii' ) except UnicodeEncodeError as ex : raise ValueError ...
Convert the given string to bytes and validate it is within the Base32 character set .
176
18
245,463
def package_version ( ) : version_path = os . path . join ( os . path . dirname ( __file__ ) , 'version.py' ) version = read_version ( version_path ) write_version ( version_path , version ) return version
Get the package version via Git Tag .
57
8
245,464
def synchronized ( * args ) : if callable ( args [ 0 ] ) : return decorate_synchronized ( args [ 0 ] , _synchronized_lock ) else : def wrap ( function ) : return decorate_synchronized ( function , args [ 0 ] ) return wrap
A synchronized function prevents two or more callers to interleave its execution preventing race conditions .
62
18
245,465
def worker_thread ( context ) : queue = context . task_queue parameters = context . worker_parameters if parameters . initializer is not None : if not run_initializer ( parameters . initializer , parameters . initargs ) : context . state = ERROR return for task in get_next_task ( context , parameters . max_tasks ) : ex...
The worker thread routines .
90
5
245,466
def stop_process ( process ) : process . terminate ( ) process . join ( 3 ) if process . is_alive ( ) and os . name != 'nt' : try : os . kill ( process . pid , signal . SIGKILL ) process . join ( ) except OSError : return if process . is_alive ( ) : raise RuntimeError ( "Unable to terminate PID %d" % os . getpid ( ) )
Does its best to stop the process .
96
8
245,467
def send_result ( pipe , data ) : try : pipe . send ( data ) except ( pickle . PicklingError , TypeError ) as error : error . traceback = format_exc ( ) pipe . send ( RemoteException ( error , error . traceback ) )
Send result handling pickling and communication errors .
58
9
245,468
def process ( * args , * * kwargs ) : timeout = kwargs . get ( 'timeout' ) # decorator without parameters if len ( args ) == 1 and len ( kwargs ) == 0 and callable ( args [ 0 ] ) : return _process_wrapper ( args [ 0 ] , timeout ) else : # decorator with parameters if timeout is not None and not isinstance ( timeout , (...
Runs the decorated function in a concurrent process taking care of the result and error management .
135
18
245,469
def _worker_handler ( future , worker , pipe , timeout ) : result = _get_result ( future , pipe , timeout ) if isinstance ( result , BaseException ) : if isinstance ( result , ProcessExpired ) : result . exitcode = worker . exitcode future . set_exception ( result ) else : future . set_result ( result ) if worker . is_...
Worker lifecycle manager .
93
6
245,470
def _function_handler ( function , args , kwargs , pipe ) : signal . signal ( signal . SIGINT , signal . SIG_IGN ) result = process_execute ( function , * args , * * kwargs ) send_result ( pipe , result )
Runs the actual function in separate process and returns its result .
57
13
245,471
def _get_result ( future , pipe , timeout ) : counter = count ( step = SLEEP_UNIT ) try : while not pipe . poll ( SLEEP_UNIT ) : if timeout is not None and next ( counter ) >= timeout : return TimeoutError ( 'Task Timeout' , timeout ) elif future . cancelled ( ) : return CancelledError ( ) return pipe . recv ( ) except...
Waits for result and handles communication errors .
119
9
245,472
def _trampoline ( name , module , * args , * * kwargs ) : function = _function_lookup ( name , module ) return function ( * args , * * kwargs )
Trampoline function for decorators .
44
8
245,473
def _function_lookup ( name , module ) : try : return _registered_functions [ name ] except KeyError : # force function registering __import__ ( module ) mod = sys . modules [ module ] getattr ( mod , name ) return _registered_functions [ name ]
Searches the function between the registered ones . If not found it imports the module forcing its registration .
61
21
245,474
def worker_process ( params , channel ) : signal ( SIGINT , SIG_IGN ) if params . initializer is not None : if not run_initializer ( params . initializer , params . initargs ) : os . _exit ( 1 ) try : for task in worker_get_next_task ( channel , params . max_tasks ) : payload = task . payload result = process_execute (...
The worker process routines .
164
5
245,475
def task_transaction ( channel ) : with channel . lock : if channel . poll ( 0 ) : task = channel . recv ( ) channel . send ( Acknowledgement ( os . getpid ( ) , task . id ) ) else : raise RuntimeError ( "Race condition between workers" ) return task
Ensures a task is fetched and acknowledged atomically .
65
13
245,476
def schedule ( self , task ) : self . task_manager . register ( task ) self . worker_manager . dispatch ( task )
Schedules a new Task in the PoolManager .
28
11
245,477
def process_next_message ( self , timeout ) : message = self . worker_manager . receive ( timeout ) if isinstance ( message , Acknowledgement ) : self . task_manager . task_start ( message . task , message . worker ) elif isinstance ( message , Result ) : self . task_manager . task_done ( message . task , message . res...
Processes the next message coming from the workers .
81
10
245,478
def update_tasks ( self ) : for task in self . task_manager . timeout_tasks ( ) : self . task_manager . task_done ( task . id , TimeoutError ( "Task timeout" , task . timeout ) ) self . worker_manager . stop_worker ( task . worker_id ) for task in self . task_manager . cancelled_tasks ( ) : self . task_manager . task_d...
Handles timing out Tasks .
121
7
245,479
def update_workers ( self ) : for expiration in self . worker_manager . inspect_workers ( ) : self . handle_worker_expiration ( expiration ) self . worker_manager . create_workers ( )
Handles unexpected processes termination .
45
6
245,480
def task_done ( self , task_id , result ) : try : task = self . tasks . pop ( task_id ) except KeyError : return # result of previously timeout Task else : if task . future . cancelled ( ) : task . set_running_or_notify_cancel ( ) elif isinstance ( result , BaseException ) : task . future . set_exception ( result ) els...
Set the tasks result and run the callback .
108
9
245,481
def inspect_workers ( self ) : workers = tuple ( self . workers . values ( ) ) expired = tuple ( w for w in workers if not w . is_alive ( ) ) for worker in expired : self . workers . pop ( worker . pid ) return ( ( w . pid , w . exitcode ) for w in expired if w . exitcode != 0 )
Updates the workers status .
79
6
245,482
def iter_chunks ( chunksize , * iterables ) : iterables = iter ( zip ( * iterables ) ) while 1 : chunk = tuple ( islice ( iterables , chunksize ) ) if not chunk : return yield chunk
Iterates over zipped iterables in chunks .
51
10
245,483
def run_initializer ( initializer , initargs ) : try : initializer ( * initargs ) return True except Exception as error : logging . exception ( error ) return False
Runs the Pool initializer dealing with errors .
37
10
245,484
def join ( self , timeout = None ) : if self . _context . state == RUNNING : raise RuntimeError ( 'The Pool is still running' ) if self . _context . state == CLOSED : self . _wait_queue_depletion ( timeout ) self . stop ( ) self . join ( ) else : self . _context . task_queue . put ( None ) self . _stop_pool ( )
Joins the pool waiting until all workers exited .
90
10
245,485
def thread ( function ) : @ wraps ( function ) def wrapper ( * args , * * kwargs ) : future = Future ( ) launch_thread ( _function_handler , function , args , kwargs , future ) return future return wrapper
Runs the decorated function within a concurrent thread taking care of the result and error management .
52
18
245,486
def _function_handler ( function , args , kwargs , future ) : future . set_running_or_notify_cancel ( ) try : result = function ( * args , * * kwargs ) except BaseException as error : error . traceback = format_exc ( ) future . set_exception ( error ) else : future . set_result ( result )
Runs the actual function in separate thread and returns its result .
82
13
245,487
def create_cities_csv ( filename = "places2k.txt" , output = "cities.csv" ) : with open ( filename , 'r' ) as city_file : with open ( output , 'w' ) as out : for line in city_file : # Drop Puerto Rico (just looking for the 50 states) if line [ 0 : 2 ] == "PR" : continue # Per census.gov, characters 9-72 are the name of...
Takes the places2k . txt from USPS and creates a simple file of all cities .
169
20
245,488
def parse_address ( self , address , line_number = - 1 ) : return Address ( address , self , line_number , self . logger )
Return an Address object from the given address . Passes itself to the Address constructor to use all the custom loaded suffixes cities etc .
32
27
245,489
def load_cities ( self , filename ) : with open ( filename , 'r' ) as f : for line in f : self . cities . append ( line . strip ( ) . lower ( ) )
Load up all cities in lowercase for easier matching . The file should have one city per line with no extra characters . This isn t strictly required but will vastly increase the accuracy .
44
36
245,490
def load_streets ( self , filename ) : with open ( filename , 'r' ) as f : for line in f : self . streets . append ( line . strip ( ) . lower ( ) )
Load up all streets in lowercase for easier matching . The file should have one street per line with no extra characters . This isn t strictly required but will vastly increase the accuracy .
44
36
245,491
def preprocess_address ( self , address ) : # Run some basic cleaning address = address . replace ( "# " , "#" ) address = address . replace ( " & " , "&" ) # Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now. if re . search ( r"-?-?\w+ units" , address , re...
Takes a basic address and attempts to clean it up extract reasonably assured bits that may throw off the rest of the parsing and return the cleaned address .
551
30
245,492
def check_state ( self , token ) : # print "zip", self.zip if len ( token ) == 2 and self . state is None : if token . capitalize ( ) in self . parser . states . keys ( ) : self . state = self . _clean ( self . parser . states [ token . capitalize ( ) ] ) return True elif token . upper ( ) in self . parser . states . v...
Check if state is in either the keys or values of our states list . Must come before the suffix .
216
21
245,493
def check_city ( self , token ) : shortened_cities = { 'saint' : 'st.' } if self . city is None and self . state is not None and self . street_suffix is None : if token . lower ( ) in self . parser . cities : self . city = self . _clean ( token . capitalize ( ) ) return True return False # Check that we're in the corre...
Check if there is a known city from our city list . Must come before the suffix .
381
18
245,494
def check_street_suffix ( self , token ) : # Suffix must come before street # print "Suffix check", token, "suffix", self.street_suffix, "street", self.street if self . street_suffix is None and self . street is None : # print "upper", token.upper() if token . upper ( ) in self . parser . suffixes . keys ( ) : suffix =...
Attempts to match a street suffix . If found it will return the abbreviation with the first letter capitalized and a period after it . E . g . St . or Ave .
172
36
245,495
def check_street ( self , token ) : # First check for single word streets between a prefix and a suffix if self . street is None and self . street_suffix is not None and self . street_prefix is None and self . house_number is None : self . street = self . _clean ( token . capitalize ( ) ) return True # Now check for mu...
Let s assume a street comes before a prefix and after a suffix . This isn t always the case but we ll deal with that in our guessing game . Also two word street names ... well ...
200
39
245,496
def check_street_prefix ( self , token ) : if self . street and not self . street_prefix and token . lower ( ) . replace ( '.' , '' ) in self . parser . prefixes . keys ( ) : self . street_prefix = self . _clean ( self . parser . prefixes [ token . lower ( ) . replace ( '.' , '' ) ] ) return True return False
Finds street prefixes such as N . or Northwest before a street name . Standardizes to 1 or two letters followed by a period .
86
28
245,497
def check_house_number ( self , token ) : if self . street and self . house_number is None and re . match ( street_num_regex , token . lower ( ) ) : if '/' in token : token = token . split ( '/' ) [ 0 ] if '-' in token : token = token . split ( '-' ) [ 0 ] self . house_number = self . _clean ( str ( token ) ) return Tr...
Attempts to find a house number generally the first thing in an address . If anything is in front of it we assume it is a building name .
99
29
245,498
def check_building ( self , token ) : if self . street and self . house_number : if not self . building : self . building = self . _clean ( token ) else : self . building = self . _clean ( token + ' ' + self . building ) return True return False
Building name check . If we have leftover and everything else is set probably building names . Allows for multi word building names .
62
24
245,499
def guess_unmatched ( self , token ) : # Check if this is probably an apartment: if token . lower ( ) in [ 'apt' , 'apartment' ] : return False # Stray dashes are likely useless if token . strip ( ) == '-' : return True # Almost definitely not a street if it is one or two characters long. if len ( token ) <= 2 : return...
When we find something that doesn t match we can make an educated guess and log it as such .
218
20