idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
1,600
def _parse_args ( self , args ) : parser = ArgumentParser ( description = "Runs pylint recursively on a directory" ) parser . add_argument ( "-v" , "--verbose" , dest = "verbose" , action = "store_true" , default = False , help = "Verbose mode (report which files were found for testing)." , ) parser . add_argument ( "-...
Parses any supplied command - line args and provides help text .
282
14
1,601
def _parse_ignores ( self ) : error_message = ( colorama . Fore . RED + "{} does not appear to be a valid pylintrc file" . format ( self . rcfile ) + colorama . Fore . RESET ) if not os . path . isfile ( self . rcfile ) : if not self . _is_using_default_rcfile ( ) : print ( error_message ) sys . exit ( 1 ) else : retur...
Parse the ignores setting from the pylintrc file if available .
194
15
1,602
def run ( self , output = None , error = None ) : pylint_output = output if output is not None else sys . stdout pylint_error = error if error is not None else sys . stderr savedout , savederr = sys . __stdout__ , sys . __stderr__ sys . stdout = pylint_output sys . stderr = pylint_error pylint_files = self . get_files_...
Runs pylint on all python files in the current directory
423
13
1,603
def strict ( * types ) : def decorate ( func ) : @ wraps ( func ) def wrapper ( self , p ) : func ( self , p ) if not isinstance ( p [ 0 ] , types ) : raise YAMLStrictTypeError ( p [ 0 ] , types , func ) wrapper . co_firstlineno = func . __code__ . co_firstlineno return wrapper return decorate
Decorator type check production rule output
88
8
1,604
def find_column ( t ) : pos = t . lexer . lexpos data = t . lexer . lexdata last_cr = data . rfind ( '\n' , 0 , pos ) if last_cr < 0 : last_cr = - 1 column = pos - last_cr return column
Get cursor position based on previous newline
66
8
1,605
def no_sleep ( ) : mode = power . ES . continuous | power . ES . system_required handle_nonzero_success ( power . SetThreadExecutionState ( mode ) ) try : yield finally : handle_nonzero_success ( power . SetThreadExecutionState ( power . ES . continuous ) )
Context that prevents the computer from going to sleep .
67
10
1,606
def selfoss ( reset_password = False ) : hostname = re . sub ( r'^[^@]+@' , '' , env . host ) # without username if any sitename = query_input ( question = '\nEnter site-name of Your trac web service' , default = flo ( 'selfoss.{hostname}' ) ) username = env . user site_dir = flo ( '/home/{username}/sites/{sitename}' )...
Install update and set up selfoss .
233
8
1,607
def get_cache_path ( filename ) : cwd = os . path . dirname ( os . path . realpath ( __file__ ) ) return os . path . join ( cwd , filename )
get file path
44
3
1,608
def get_process_token ( ) : token = wintypes . HANDLE ( ) res = process . OpenProcessToken ( process . GetCurrentProcess ( ) , process . TOKEN_ALL_ACCESS , token ) if not res > 0 : raise RuntimeError ( "Couldn't get process token" ) return token
Get the current process token
69
5
1,609
def get_symlink_luid ( ) : symlink_luid = privilege . LUID ( ) res = privilege . LookupPrivilegeValue ( None , "SeCreateSymbolicLinkPrivilege" , symlink_luid ) if not res > 0 : raise RuntimeError ( "Couldn't lookup privilege value" ) return symlink_luid
Get the LUID for the SeCreateSymbolicLinkPrivilege
81
14
1,610
def get_privilege_information ( ) : # first call with zero length to determine what size buffer we need return_length = wintypes . DWORD ( ) params = [ get_process_token ( ) , privilege . TOKEN_INFORMATION_CLASS . TokenPrivileges , None , 0 , return_length , ] res = privilege . GetTokenInformation ( * params ) # assume...
Get all privileges associated with the current process .
184
9
1,611
def enable_symlink_privilege ( ) : # create a space in memory for a TOKEN_PRIVILEGES structure # with one element size = ctypes . sizeof ( privilege . TOKEN_PRIVILEGES ) size += ctypes . sizeof ( privilege . LUID_AND_ATTRIBUTES ) buffer = ctypes . create_string_buffer ( size ) tp = ctypes . cast ( buffer , ctypes . POI...
Try to assign the symlink privilege to the current process token . Return True if the assignment is successful .
244
22
1,612
def grant_symlink_privilege ( who , machine = '' ) : flags = security . POLICY_CREATE_ACCOUNT | security . POLICY_LOOKUP_NAMES policy = OpenPolicy ( machine , flags ) return policy
Grant the create symlink privilege to who .
54
10
1,613
def add_tasks_r ( addon_module , package_module , package_name ) : module_dict = package_module . __dict__ for attr_name , attr_val in module_dict . items ( ) : if isinstance ( attr_val , fabric . tasks . WrappedCallableTask ) : addon_module . __dict__ [ attr_name ] = attr_val elif attr_name != package_name and isinsta...
Recursively iterate through package_module and add every fabric task to the addon_module keeping the task hierarchy .
237
24
1,614
def load_addon ( username , package_name , _globals ) : addon_module = get_or_create_module_r ( username ) package_module = __import__ ( package_name ) add_tasks_r ( addon_module , package_module , package_name ) _globals . update ( { username : addon_module } ) del package_module del addon_module
Load an fabsetup addon given by package_name and hook it in the base task namespace username .
87
20
1,615
def load_pip_addons ( _globals ) : for package_name in known_pip_addons : _ , username = package_username ( package_name ) try : load_addon ( username , package_name . replace ( '-' , '_' ) , _globals ) except ImportError : pass
Load all known fabsetup addons which are installed as pypi pip - packages .
70
18
1,616
def find_lib ( lib ) : if isinstance ( lib , str ) : lib = getattr ( ctypes . windll , lib ) size = 1024 result = ctypes . create_unicode_buffer ( size ) library . GetModuleFileName ( lib . _handle , result , size ) return result . value
r Find the DLL for a given library .
67
10
1,617
def getScienceMetadataRDF ( self , pid ) : url = "{url_base}/scimeta/{pid}/" . format ( url_base = self . url_base , pid = pid ) r = self . _request ( 'GET' , url ) if r . status_code != 200 : if r . status_code == 403 : raise HydroShareNotAuthorized ( ( 'GET' , url ) ) elif r . status_code == 404 : raise HydroShareNot...
Get science metadata for a resource in XML + RDF format
142
12
1,618
def getResource ( self , pid , destination = None , unzip = False , wait_for_bag_creation = True ) : stream = self . _getBagStream ( pid , wait_for_bag_creation ) if destination : self . _storeBagOnFilesystem ( stream , pid , destination , unzip ) return None else : return stream
Get a resource in BagIt format
76
7
1,619
def getResourceTypes ( self ) : url = "{url_base}/resource/types" . format ( url_base = self . url_base ) r = self . _request ( 'GET' , url ) if r . status_code != 200 : raise HydroShareHTTPException ( ( url , 'GET' , r . status_code ) ) resource_types = r . json ( ) return set ( [ t [ 'resource_type' ] for t in resour...
Get the list of resource types supported by the HydroShare server
104
12
1,620
def createResource ( self , resource_type , title , resource_file = None , resource_filename = None , abstract = None , keywords = None , edit_users = None , view_users = None , edit_groups = None , view_groups = None , metadata = None , extra_metadata = None , progress_callback = None ) : url = "{url_base}/resource/" ...
Create a new resource .
559
5
1,621
def setAccessRules ( self , pid , public = False ) : url = "{url_base}/resource/accessRules/{pid}/" . format ( url_base = self . url_base , pid = pid ) params = { 'public' : public } r = self . _request ( 'PUT' , url , data = params ) if r . status_code != 200 : if r . status_code == 403 : raise HydroShareNotAuthorized...
Set access rules for a resource . Current only allows for setting the public or private setting .
181
18
1,622
def addResourceFile ( self , pid , resource_file , resource_filename = None , progress_callback = None ) : url = "{url_base}/resource/{pid}/files/" . format ( url_base = self . url_base , pid = pid ) params = { } close_fd = self . _prepareFileForUpload ( params , resource_file , resource_filename ) encoder = MultipartE...
Add a new file to an existing resource
282
8
1,623
def getResourceFile ( self , pid , filename , destination = None ) : url = "{url_base}/resource/{pid}/files/{filename}" . format ( url_base = self . url_base , pid = pid , filename = filename ) if destination : if not os . path . isdir ( destination ) : raise HydroShareArgumentException ( "{0} is not a directory." . fo...
Get a file within a resource .
307
7
1,624
def deleteResourceFile ( self , pid , filename ) : url = "{url_base}/resource/{pid}/files/{filename}" . format ( url_base = self . url_base , pid = pid , filename = filename ) r = self . _request ( 'DELETE' , url ) if r . status_code != 200 : if r . status_code == 403 : raise HydroShareNotAuthorized ( ( 'DELETE' , url ...
Delete a resource file
177
4
1,625
def getResourceFileList ( self , pid ) : url = "{url_base}/resource/{pid}/files/" . format ( url_base = self . url_base , pid = pid ) return resultsListGenerator ( self , url )
Get a listing of files within a resource .
54
9
1,626
def get_ssm_parameter ( parameter_name ) : try : response = boto3 . client ( 'ssm' ) . get_parameters ( Names = [ parameter_name ] , WithDecryption = True ) return response . get ( 'Parameters' , None ) [ 0 ] . get ( 'Value' , '' ) except Exception : pass return ''
Get the decrypted value of an SSM parameter
78
10
1,627
def powerline ( ) : bindings_dir , scripts_dir = install_upgrade_powerline ( ) set_up_powerline_fonts ( ) set_up_powerline_daemon ( scripts_dir ) powerline_for_vim ( bindings_dir ) powerline_for_bash_or_powerline_shell ( bindings_dir ) powerline_for_tmux ( bindings_dir ) powerline_for_i3 ( bindings_dir ) print ( '\nYou...
Install and set up powerline for vim bash tmux and i3 .
118
16
1,628
def ifancestor ( parser , token ) : # Grab the contents between contents = parser . parse ( ( 'endifancestor' , ) ) parser . delete_first_token ( ) # If there is only one argument (2 including tag name) # parse it as a variable bits = token . split_contents ( ) if len ( bits ) == 2 : arg = parser . compile_filter ( bit...
Returns the contents of the tag if the provided path consitutes the base of the current pages path .
133
20
1,629
def exit_statistics ( hostname , start_time , count_sent , count_received , min_time , avg_time , max_time , deviation ) : end_time = datetime . datetime . now ( ) duration = end_time - start_time duration_sec = float ( duration . seconds * 1000 ) duration_ms = float ( duration . microseconds / 1000 ) duration = durati...
Print ping exit statistics
298
4
1,630
def _filtered_walk ( path , file_filter ) : for root , dirs , files in os . walk ( path ) : log . debug ( 'looking in %s' , root ) log . debug ( 'files is %s' , files ) file_filter . set_root ( root ) files = filter ( file_filter , files ) log . debug ( 'filtered files is %s' , files ) yield ( root , dirs , files )
static method that calls os . walk but filters out anything that doesn t match the filter
99
17
1,631
def cache_control_expires ( num_hours ) : num_seconds = int ( num_hours * 60 * 60 ) def decorator ( func ) : @ wraps ( func ) def inner ( request , * args , * * kwargs ) : response = func ( request , * args , * * kwargs ) patch_response_headers ( response , num_seconds ) return response return inner return decorator
Set the appropriate Cache - Control and Expires headers for the given number of hours .
88
17
1,632
def upsert ( self ) : required_parameters = [ ] self . _stackParameters = [ ] try : self . _initialize_upsert ( ) except Exception : return False try : available_parameters = self . _parameters . keys ( ) for parameter_name in self . _template . get ( 'Parameters' , { } ) : required_parameters . append ( str ( paramete...
The main event of the utility . Create or update a Cloud Formation stack . Injecting properties where needed
716
21
1,633
def list ( self ) : self . _initialize_list ( ) interested = True response = self . _cloudFormation . list_stacks ( ) print ( 'Stack(s):' ) while interested : if 'StackSummaries' in response : for stack in response [ 'StackSummaries' ] : stack_status = stack [ 'StackStatus' ] if stack_status != 'DELETE_COMPLETE' : prin...
List the existing stacks in the indicated region
171
8
1,634
def smash ( self ) : self . _initialize_smash ( ) try : stack_name = self . _config . get ( 'environment' , { } ) . get ( 'stack_name' , None ) response = self . _cloudFormation . describe_stacks ( StackName = stack_name ) logging . debug ( 'smash pre-flight returned: {}' . format ( json . dumps ( response , indent = 4...
Smash the given stack
237
5
1,635
def _init_boto3_clients ( self ) : try : profile = self . _config . get ( 'environment' , { } ) . get ( 'profile' ) region = self . _config . get ( 'environment' , { } ) . get ( 'region' ) if profile : self . _b3Sess = boto3 . session . Session ( profile_name = profile ) else : self . _b3Sess = boto3 . session . Sessio...
The utililty requires boto3 clients to Cloud Formation and S3 . Here is where we make them .
229
22
1,636
def _get_ssm_parameter ( self , p ) : try : response = self . _ssm . get_parameter ( Name = p , WithDecryption = True ) return response . get ( 'Parameter' , { } ) . get ( 'Value' , None ) except Exception as ruh_roh : logging . error ( ruh_roh , exc_info = False ) return None
Get parameters from Simple Systems Manager
88
6
1,637
def _fill_parameters ( self ) : self . _parameters = self . _config . get ( 'parameters' , { } ) self . _fill_defaults ( ) for k in self . _parameters . keys ( ) : try : if self . _parameters [ k ] . startswith ( self . SSM ) and self . _parameters [ k ] . endswith ( ']' ) : parts = self . _parameters [ k ] . split ( '...
Fill in the _parameters dict from the properties file .
317
12
1,638
def _read_tags ( self ) : tags = self . _config . get ( 'tags' , { } ) logging . info ( 'Tags:' ) for tag_name in tags . keys ( ) : tag = { } tag [ 'Key' ] = tag_name tag [ 'Value' ] = tags [ tag_name ] self . _tags . append ( tag ) logging . info ( '{} = {}' . format ( tag_name , tags [ tag_name ] ) ) logging . debug ...
Fill in the _tags dict from the tags file .
131
11
1,639
def _set_update ( self ) : try : self . _updateStack = False stack_name = self . _config . get ( 'environment' , { } ) . get ( 'stack_name' , None ) response = self . _cloudFormation . describe_stacks ( StackName = stack_name ) stack = response [ 'Stacks' ] [ 0 ] if stack [ 'StackStatus' ] == 'ROLLBACK_COMPLETE' : logg...
Determine if we are creating a new stack or updating and existing one . The update member is set as you would expect at the end of this query .
288
32
1,640
def _craft_s3_keys ( self ) : now = time . gmtime ( ) stub = "templates/{stack_name}/{version}" . format ( stack_name = self . _config . get ( 'environment' , { } ) . get ( 'stack_name' , None ) , version = self . _config . get ( 'codeVersion' ) ) stub = stub + "/" + str ( now . tm_year ) stub = stub + "/" + str ( '%02...
We are putting stuff into S3 were supplied the bucket . Here we craft the key of the elements we are putting up there in the internet clouds .
262
30
1,641
def poll_stack ( self ) : logging . info ( 'polling stack status, POLL_INTERVAL={}' . format ( POLL_INTERVAL ) ) time . sleep ( POLL_INTERVAL ) completed_states = [ 'CREATE_COMPLETE' , 'UPDATE_COMPLETE' , 'DELETE_COMPLETE' ] stack_name = self . _config . get ( 'environment' , { } ) . get ( 'stack_name' , None ) while T...
Spin in a loop while the Cloud Formation process either fails or succeeds
364
14
1,642
def setup_desktop ( ) : run ( 'sudo apt-get update' ) install_packages ( packages_desktop ) execute ( custom . latex ) execute ( setup . ripping_of_cds ) execute ( setup . regex_repl ) execute ( setup . i3 ) execute ( setup . solarized ) execute ( setup . vim ) execute ( setup . tmux ) execute ( setup . pyenv ) # circu...
Run setup tasks to set up a nicely configured desktop pc .
127
12
1,643
def setup_webserver ( ) : run ( 'sudo apt-get update' ) install_packages ( packages_webserver ) execute ( custom . latex ) execute ( setup . solarized ) execute ( setup . vim ) execute ( setup . tmux ) checkup_git_repo_legacy ( url = 'git@github.com:letsencrypt/letsencrypt.git' ) execute ( setup . service . fdroid ) ex...
Run setup tasks to set up a nicely configured webserver .
148
12
1,644
def start_recv ( sockfile = None ) : if sockfile is not None : SOCKFILE = sockfile else : # default sockfile SOCKFILE = "/tmp/snort_alert" if os . path . exists ( SOCKFILE ) : os . unlink ( SOCKFILE ) unsock = socket . socket ( socket . AF_UNIX , socket . SOCK_DGRAM ) unsock . bind ( SOCKFILE ) logging . warning ( 'Uni...
Open a server on Unix Domain Socket
146
7
1,645
def dump ( obj , fp = None , indent = None , sort_keys = False , * * kw ) : if fp : iterable = YAMLEncoder ( indent = indent , sort_keys = sort_keys , * * kw ) . iterencode ( obj ) for chunk in iterable : fp . write ( chunk ) else : return dumps ( obj , indent = indent , sort_keys = sort_keys , * * kw )
Dump object to a file like object or string .
100
11
1,646
def dumps ( obj , indent = None , default = None , sort_keys = False , * * kw ) : return YAMLEncoder ( indent = indent , default = default , sort_keys = sort_keys , * * kw ) . encode ( obj )
Dump string .
58
4
1,647
def load ( s , * * kwargs ) : try : return loads ( s , * * kwargs ) except TypeError : return loads ( s . read ( ) , * * kwargs )
Load yaml file
44
4
1,648
def address ( self ) : _ = struct . pack ( 'L' , self . address_num ) return struct . unpack ( '!L' , _ ) [ 0 ]
The address in big - endian
38
7
1,649
def validate_currency ( * currencies ) : validated_currency = [ ] if not currencies : raise CurrencyException ( 'My function need something to run, duh' ) for currency in currencies : currency = currency . upper ( ) if not isinstance ( currency , str ) : raise TypeError ( 'Currency code should be a string: ' + repr ( c...
some validation checks before doing anything
131
6
1,650
def validate_price ( price ) : if isinstance ( price , str ) : try : price = int ( price ) except ValueError : # fallback if convert to int failed price = float ( price ) if not isinstance ( price , ( int , float ) ) : raise TypeError ( 'Price should be a number: ' + repr ( price ) ) return price
validation checks for price argument
77
6
1,651
def name ( currency , * , plural = False ) : currency = validate_currency ( currency ) if plural : return _currencies [ currency ] [ 'name_plural' ] return _currencies [ currency ] [ 'name' ]
return name of currency
50
4
1,652
def symbol ( currency , * , native = True ) : currency = validate_currency ( currency ) if native : return _currencies [ currency ] [ 'symbol_native' ] return _currencies [ currency ] [ 'symbol' ]
return symbol of currency
51
4
1,653
def rounding ( price , currency ) : currency = validate_currency ( currency ) price = validate_price ( price ) if decimals ( currency ) == 0 : return round ( int ( price ) , decimals ( currency ) ) return round ( price , decimals ( currency ) )
rounding currency value based on its max decimal digits
61
10
1,654
def check_update ( from_currency , to_currency ) : if from_currency not in ccache : # if currency never get converted before ccache [ from_currency ] = { } if ccache [ from_currency ] . get ( to_currency ) is None : ccache [ from_currency ] [ to_currency ] = { 'last_update' : 0 } last_update = float ( ccache [ from_cur...
check if last update is over 30 mins ago . if so return True to update else False
135
18
1,655
def update_cache ( from_currency , to_currency ) : if check_update ( from_currency , to_currency ) is True : ccache [ from_currency ] [ to_currency ] [ 'value' ] = convert_using_api ( from_currency , to_currency ) ccache [ from_currency ] [ to_currency ] [ 'last_update' ] = time . time ( ) cache . write ( ccache )
update from_currency to_currency pair in cache if last update for that pair is over 30 minutes ago by request API info
94
25
1,656
def convert_using_api ( from_currency , to_currency ) : convert_str = from_currency + '_' + to_currency options = { 'compact' : 'ultra' , 'q' : convert_str } api_url = 'https://free.currencyconverterapi.com/api/v5/convert' result = requests . get ( api_url , params = options ) . json ( ) return result [ convert_str ]
convert from from_currency to to_currency by requesting API
102
13
1,657
def convert ( from_currency , to_currency , from_currency_price = 1 ) : get_cache ( ) from_currency , to_currency = validate_currency ( from_currency , to_currency ) update_cache ( from_currency , to_currency ) return ccache [ from_currency ] [ to_currency ] [ 'value' ] * from_currency_price
convert from from_currency to to_currency using cached info
81
13
1,658
def wait_for_signal ( self , timeout = None ) : timeout_ms = int ( timeout * 1000 ) if timeout else win32event . INFINITE win32event . WaitForSingleObject ( self . signal_event , timeout_ms )
wait for the signal ; return after the signal has occurred or the timeout in seconds elapses .
54
19
1,659
def ip_geoloc ( ip , hit_api = True ) : from . . logs . models import IPInfoCheck try : obj = IPInfoCheck . objects . get ( ip_address = ip ) . ip_info except IPInfoCheck . DoesNotExist : if hit_api : try : obj = IPInfoCheck . check_ip ( ip ) except RateExceededError : return None else : return None return obj . latitu...
Get IP geolocation .
99
6
1,660
def google_maps_geoloc_link ( data ) : if isinstance ( data , str ) : lat_lon = ip_geoloc ( data ) if lat_lon is None : return '' lat , lon = lat_lon else : lat , lon = data loc = '%s,%s' % ( lat , lon ) return 'https://www.google.com/maps/place/@%s,17z/' 'data=!3m1!4b1!4m5!3m4!1s0x0:0x0!8m2!3d%s!4d%s' % ( loc , lat , ...
Get a link to google maps pointing on this IP s geolocation .
151
15
1,661
def open_street_map_geoloc_link ( data ) : if isinstance ( data , str ) : lat_lon = ip_geoloc ( data ) if lat_lon is None : return '' lat , lon = lat_lon else : lat , lon = data return 'https://www.openstreetmap.org/search' '?query=%s%%2C%s#map=7/%s/%s' % ( lat , lon , lat , lon )
Get a link to open street map pointing on this IP s geolocation .
110
16
1,662
def status_codes_chart ( ) : stats = status_codes_stats ( ) chart_options = { 'chart' : { 'type' : 'pie' } , 'title' : { 'text' : '' } , 'subtitle' : { 'text' : '' } , 'tooltip' : { 'formatter' : "return this.y + '/' + this.total + ' (' + " "Highcharts.numberFormat(this.percentage, 1) + '%)';" } , 'legend' : { 'enabled...
Chart for status codes .
328
5
1,663
def most_visited_pages_legend_chart ( ) : return { 'chart' : { 'type' : 'bar' , 'height' : 200 , } , 'title' : { 'text' : _ ( 'Legend' ) } , 'xAxis' : { 'categories' : [ _ ( 'Project URL' ) , _ ( 'Old project URL' ) , _ ( 'Asset URL' ) , _ ( 'Old asset URL' ) , _ ( 'Common asset URL' ) , _ ( 'False-negative project URL...
Chart for most visited pages legend .
430
7
1,664
def add_settings ( mod , allow_extras = True , settings = django_settings ) : extras = { } for setting in dir ( mod ) : if setting == setting . upper ( ) : setting_value = getattr ( mod , setting ) if setting in TUPLE_SETTINGS and type ( setting_value ) == str : setting_value = ( setting_value , ) # In case the user fo...
Adds all settings that are part of mod to the global settings object .
250
14
1,665
def get_urls ( self ) : urls = super ( DashboardSite , self ) . get_urls ( ) custom_urls = [ url ( r'^$' , self . admin_view ( HomeView . as_view ( ) ) , name = 'index' ) , url ( r'^logs/' , include ( logs_urlpatterns ( self . admin_view ) ) ) , ] custom_urls += get_realtime_urls ( self . admin_view ) del urls [ 0 ] re...
Get urls method .
125
5
1,666
def add_form_widget_attr ( field , attr_name , attr_value , replace = 0 ) : if not replace : attr = field . field . widget . attrs . get ( attr_name , '' ) attr += force_text ( attr_value ) field . field . widget . attrs [ attr_name ] = attr return field else : field . field . widget . attrs [ attr_name ] = attr_value ...
Adds widget attributes to a bound form field .
105
9
1,667
def block_anyfilter ( parser , token ) : bits = token . contents . split ( ) nodelist = parser . parse ( ( 'endblockanyfilter' , ) ) parser . delete_first_token ( ) return BlockAnyFilterNode ( nodelist , bits [ 1 ] , * bits [ 2 : ] )
Turn any template filter into a blocktag .
67
9
1,668
def calculate_dimensions ( image , long_side , short_side ) : if image . width >= image . height : return '{0}x{1}' . format ( long_side , short_side ) return '{0}x{1}' . format ( short_side , long_side )
Returns the thumbnail dimensions depending on the images format .
68
10
1,669
def call ( obj , method , * args , * * kwargs ) : function_or_dict_or_member = getattr ( obj , method ) if callable ( function_or_dict_or_member ) : # If it is a function, let's call it return function_or_dict_or_member ( * args , * * kwargs ) if not len ( args ) : # If it is a member, lets return it return function_or...
Allows to call any method of any object with parameters .
138
11
1,670
def concatenate ( * args , * * kwargs ) : divider = kwargs . get ( 'divider' , '' ) result = '' for arg in args : if result == '' : result += arg else : result += '{0}{1}' . format ( divider , arg ) return result
Concatenates the given strings .
68
8
1,671
def get_content_type ( obj , field_name = False ) : content_type = ContentType . objects . get_for_model ( obj ) if field_name : return getattr ( content_type , field_name , '' ) return content_type
Returns the content type of an object .
56
8
1,672
def get_verbose ( obj , field_name = "" ) : if hasattr ( obj , "_meta" ) and hasattr ( obj . _meta , "get_field_by_name" ) : try : return obj . _meta . get_field ( field_name ) . verbose_name except FieldDoesNotExist : pass return ""
Returns the verbose name of an object s field .
76
11
1,673
def get_query_params ( request , * args ) : query = request . GET . copy ( ) index = 1 key = '' for arg in args : if index % 2 != 0 : key = arg else : if arg == "!remove" : try : query . pop ( key ) except KeyError : pass else : query [ key ] = arg index += 1 return query . urlencode ( )
Allows to change one of the URL get parameter while keeping all the others .
85
15
1,674
def navactive ( request , url , exact = 0 , use_resolver = 1 ) : if use_resolver : try : if url == resolve ( request . path ) . url_name : # Checks the url pattern in case a view_name is posted return 'active' elif url == request . path : # Workaround to catch URLs with more than one part, which don't # raise a Resolve...
Returns active if the given URL is in the url path otherwise .
173
13
1,675
def get_range_around ( range_value , current_item , padding ) : total_items = 1 + padding * 2 left_bound = padding right_bound = range_value - padding if range_value <= total_items : range_items = range ( 1 , range_value + 1 ) return { 'range_items' : range_items , 'left_padding' : False , 'right_padding' : False , } i...
Returns a range of numbers around the given number .
293
10
1,676
def sum ( context , key , value , multiplier = 1 ) : if key not in context . dicts [ 0 ] : context . dicts [ 0 ] [ key ] = 0 context . dicts [ 0 ] [ key ] += value * multiplier return ''
Adds the given value to the total value currently held in key .
54
13
1,677
def verbatim ( parser , token ) : text = [ ] while 1 : token = parser . tokens . pop ( 0 ) if token . contents == 'endverbatim' : break if token . token_type == TOKEN_VAR : text . append ( '{{ ' ) elif token . token_type == TOKEN_BLOCK : text . append ( '{%' ) text . append ( token . contents ) if token . token_type ==...
Tag to render x - tmpl templates with Django template code .
178
14
1,678
def append_s ( value ) : if value . endswith ( 's' ) : return u"{0}'" . format ( value ) else : return u"{0}'s" . format ( value )
Adds the possessive s after a string .
48
9
1,679
def logs_urlpatterns ( admin_view = lambda x : x ) : return [ url ( r'^$' , admin_view ( LogsMenu . as_view ( ) ) , name = 'logs' ) , url ( r'^status_codes$' , admin_view ( LogsStatusCodes . as_view ( ) ) , name = 'logs_status_codes' ) , url ( r'^status_codes_by_date$' , admin_view ( LogsStatusCodesByDate . as_view ( )...
Return the URL patterns for the logs views .
187
9
1,680
def _get ( self , ip ) : # Geoloc updated up to once a week: # http://ipinfo.io/developers/data#geolocation-data retries = 10 for retry in range ( retries ) : try : response = requests . get ( 'http://ipinfo.io/%s/json' % ip , verify = False , timeout = 1 ) # nosec if response . status_code == 429 : raise RateExceededE...
Get information about an IP .
125
6
1,681
def parse ( data ) : # convert to string data = data . decode ( "ascii" ) if len ( data ) == 2 and data == "A5" : return AckMessage ( ) # split into bytes raw = [ data [ i : i + 2 ] for i in range ( len ( data ) ) if i % 2 == 0 ] if len ( raw ) != 7 : return UnknownMessage ( raw ) if raw [ 1 ] == "B8" : return StateMes...
Parses a raw datagram and return the right type of message
169
14
1,682
def checksum_bytes ( data ) : int_values = [ int ( x , 16 ) for x in data ] int_xor = reduce ( lambda x , y : x ^ y , int_values ) hex_xor = "{:X}" . format ( int_xor ) if len ( hex_xor ) % 2 != 0 : hex_xor = "0" + hex_xor return str . encode ( hex_xor )
Returns a XOR of all the bytes specified inside of the given list
98
14
1,683
def compose_telegram ( body ) : msg = [ b"A8" ] + body + [ checksum_bytes ( body ) ] + [ b"A3" ] return str . encode ( "" . join ( [ x . decode ( ) for x in msg ] ) )
Compose a SCS message
60
6
1,684
def send_email ( request , context , subject_template , body_template , from_email , recipients , priority = "medium" , reply_to = None , headers = None , cc = None , bcc = None ) : headers = headers or { } if not reply_to : reply_to = from_email # Add additional context if hasattr ( settings , 'DJANGO_LIBS_EMAIL_CONTE...
Sends an email based on templates for subject and body .
503
12
1,685
def url_is_project ( url , default = 'not_a_func' ) : try : u = resolve ( url ) if u and u . func != default : return True except Resolver404 : static_url = settings . STATIC_URL static_url_wd = static_url . lstrip ( '/' ) if url . startswith ( static_url ) : url = url [ len ( static_url ) : ] elif url . startswith ( s...
Check if URL is part of the current project s URLs .
140
12
1,686
def url_is ( white_list ) : def func ( url ) : prefixes = white_list . get ( 'PREFIXES' , ( ) ) for prefix in prefixes : if url . startswith ( prefix ) : return True constants = white_list . get ( 'CONSTANTS' , ( ) ) for exact_url in constants : if url == exact_url : return True return False return func
Function generator .
91
3
1,687
def save_records ( self , records ) : for record in records : if not isinstance ( record , Record ) : record = Record ( * record ) self . save_record ( * record )
Save a collection of records
42
5
1,688
def save_record ( self , agent_id , t_step , key , value ) : value = self . convert ( key , value ) self . _tups . append ( Record ( agent_id = agent_id , t_step = t_step , key = key , value = value ) ) if len ( self . _tups ) > 100 : self . flush_cache ( )
Save a collection of records to the database . Database writes are cached .
84
14
1,689
def convert ( self , key , value ) : if key not in self . _dtypes : self . read_types ( ) if key not in self . _dtypes : name = utils . name ( value ) serializer = utils . serializer ( name ) deserializer = utils . deserializer ( name ) self . _dtypes [ key ] = ( name , serializer , deserializer ) with self . db : self...
Get the serialized value for a given key .
139
10
1,690
def recover ( self , key , value ) : if key not in self . _dtypes : self . read_types ( ) if key not in self . _dtypes : raise ValueError ( "Unknown datatype for {} and {}" . format ( key , value ) ) return self . _dtypes [ key ] [ 2 ] ( value )
Get the deserialized value for a given key and the serialized version .
74
16
1,691
def flush_cache ( self ) : logger . debug ( 'Flushing cache {}' . format ( self . db_path ) ) with self . db : for rec in self . _tups : self . db . execute ( "replace into history(agent_id, t_step, key, value) values (?, ?, ?, ?)" , ( rec . agent_id , rec . t_step , rec . key , rec . value ) ) self . _tups = list ( )
Use a cache to save state changes to avoid opening a session for every change . The cache will be flushed at the end of the simulation and when history is accessed .
105
33
1,692
def records ( ) : import pkg_resources import uuid from dojson . contrib . marc21 import marc21 from dojson . contrib . marc21 . utils import create_record , split_blob from invenio_pidstore import current_pidstore from invenio_records . api import Record # pkg resources the demodata data_path = pkg_resources . resourc...
Load records .
260
3
1,693
def run_trial_exceptions ( self , * args , * * kwargs ) : try : return self . run_trial ( * args , * * kwargs ) except Exception as ex : c = ex . __cause__ c . message = '' . join ( traceback . format_exception ( type ( c ) , c , c . __traceback__ ) [ : ] ) return c
A wrapper for run_trial that catches exceptions and returns them . It is meant for async simulations
86
19
1,694
def search_orcid ( orcid ) : url = 'https://pub.orcid.org/v2.1/{orcid}/person' . format ( orcid = orcid ) r = requests . get ( url , headers = headers ) if r . status_code != 200 : r . raise_for_status ( ) return r . json ( )
Search the ORCID public API
79
7
1,695
def daterange ( start_date , end_date ) : for n in range ( int ( ( end_date - start_date ) . days ) ) : yield start_date + timedelta ( n )
Yield one date per day from starting date to ending date .
45
13
1,696
def get_reference ( root ) : reference = { } elem = root . find ( 'bibliographyLink' ) if elem is None : raise MissingElementError ( 'bibliographyLink' ) # Try to get reference info via DOI, fall back on preferredKey if necessary. ref_doi = elem . get ( 'doi' , None ) ref_key = elem . get ( 'preferredKey' , None ) if r...
Read reference info from root of ReSpecTh XML file .
619
12
1,697
def get_ignition_type ( root ) : properties = { } elem = root . find ( 'ignitionType' ) if elem is None : raise MissingElementError ( 'ignitionType' ) elem = elem . attrib if 'target' in elem : ign_target = elem [ 'target' ] . rstrip ( ';' ) . upper ( ) else : raise MissingAttributeError ( 'target' , 'ignitionType' ) i...
Gets ignition type and target .
419
7
1,698
def ReSpecTh_to_ChemKED ( filename_xml , file_author = '' , file_author_orcid = '' , * , validate = False ) : # get all information from XML file tree = etree . parse ( filename_xml ) root = tree . getroot ( ) # get file metadata properties = get_file_metadata ( root ) # get reference info properties [ 'reference' ] = ...
Convert ReSpecTh XML file to ChemKED - compliant dictionary .
661
15
1,699
def respth2ck ( argv = None ) : parser = ArgumentParser ( description = 'Convert a ReSpecTh XML file to a ChemKED YAML file.' ) parser . add_argument ( '-i' , '--input' , type = str , required = True , help = 'Input filename (e.g., "file1.yaml")' ) parser . add_argument ( '-o' , '--output' , type = str , required = Fal...
Command - line entry point for converting a ReSpecTh XML file to a ChemKED YAML file .
399
23