idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
6,600
def drape ( raster , feature ) : coords = feature [ 'geometry' ] [ 'coordinates' ] geom_type = feature [ 'geometry' ] [ 'type' ] if geom_type == 'Point' : xyz = sample ( raster , [ coords ] ) result = Point ( xyz [ 0 ] ) elif geom_type == 'LineString' : xyz = sample ( raster , coords ) points = [ Point ( x , y , z ) fo...
Convert a 2D feature to a 3D feature by sampling a raster
6,601
def sample ( raster , coords ) : if len ( coords [ 0 ] ) == 3 : logging . info ( 'Input is a 3D geometry, z coordinate will be updated.' ) z = raster . sample ( [ ( x , y ) for x , y , z in coords ] , indexes = raster . indexes ) else : z = raster . sample ( coords , indexes = raster . indexes ) result = [ ( vert [ 0 ]...
Sample a raster at given coordinates
6,602
def cli ( source_f , raster_f , output , verbose ) : with fiona . open ( source_f , 'r' ) as source : source_driver = source . driver source_crs = source . crs sink_schema = source . schema . copy ( ) source_geom = source . schema [ 'geometry' ] if source_geom == 'Point' : sink_schema [ 'geometry' ] = '3D Point' elif s...
Converts 2D geometries to 3D using GEOS sample through fiona .
6,603
def eval ( self , command ) : 'Blocking call, returns the value of the execution in JS' event = threading . Event ( ) import random job_id = str ( random . random ( ) ) server . EVALUATIONS [ job_id ] = event message = '?' + job_id + '=' + command logging . info ( ( 'message:' , [ message ] ) ) for listener in server ....
Blocking call returns the value of the execution in JS
6,604
def launch_exception ( message ) : error_name = message [ 'name' ] error_descr = message [ 'description' ] mapping = { 'ReferenceError' : NameError , } if message [ 'name' ] in mapping : raise mapping [ error_name ] ( error_descr ) else : raise Exception ( '{}: {}' . format ( error_name , error_descr ) )
Launch a Python exception from an error that took place in the browser .
6,605
def unflatten_dct ( obj ) : def reduce_func ( accum , key_string_and_value ) : key_string = key_string_and_value [ 0 ] value = key_string_and_value [ 1 ] item_key_path = key_string_to_lens_path ( key_string ) container_key_path = init ( item_key_path ) container = unless ( both ( always ( length ( container_key_path ) ...
Undoes the work of flatten_dict
6,606
def change_view ( self , request , object_id , form_url = '' , extra_context = None ) : context = { 'has_moderate_tool' : True } if extra_context : context . update ( extra_context ) return super ( AdminModeratorMixin , self ) . change_view ( request = request , object_id = object_id , form_url = form_url , extra_conte...
Override change view to add extra context enabling moderate tool .
6,607
def get_urls ( self ) : from django . conf . urls import url urls = super ( AdminModeratorMixin , self ) . get_urls ( ) info = self . model . _meta . app_label , self . model . _meta . model_name return [ url ( r'^(.+)/moderate/$' , self . admin_site . admin_view ( self . moderate_view ) , name = '%s_%s_moderate' % inf...
Add aditional moderate url .
6,608
def operating_system ( ) : if platform . system ( ) == 'Darwin' : return 'OS X Version %s' % platform . mac_ver ( ) [ 0 ] distribution = ' ' . join ( platform . linux_distribution ( ) ) . strip ( ) os_platform = platform . platform ( True , True ) if distribution : os_platform += ' (%s)' % distribution return os_platfo...
Return a string identifying the operating system the application is running on .
6,609
def start ( self ) : if self . _is_already_running ( ) : LOGGER . error ( 'Is already running' ) sys . exit ( 1 ) try : self . _daemonize ( ) self . controller . start ( ) except Exception as error : sys . stderr . write ( '\nERROR: Startup of %s Failed\n.' % sys . argv [ 0 ] . split ( '/' ) [ - 1 ] ) exception_log = s...
Daemonize if the process is not already running .
6,610
def gid ( self ) : if not self . _gid : if self . controller . config . daemon . group : self . _gid = grp . getgrnam ( self . config . daemon . group ) . gr_gid else : self . _gid = os . getgid ( ) return self . _gid
Return the group id that the daemon will run with
6,611
def uid ( self ) : if not self . _uid : if self . config . daemon . user : self . _uid = pwd . getpwnam ( self . config . daemon . user ) . pw_uid else : self . _uid = os . getuid ( ) return self . _uid
Return the user id that the process will run as
6,612
def _get_exception_log_path ( ) : app = sys . argv [ 0 ] . split ( '/' ) [ - 1 ] for exception_log in [ '/var/log/%s.errors' % app , '/var/tmp/%s.errors' % app , '/tmp/%s.errors' % app ] : if os . access ( path . dirname ( exception_log ) , os . W_OK ) : return exception_log return None
Return the normalized path for the connection log raising an exception if it can not written to .
6,613
def _get_pidfile_path ( self ) : if self . config . daemon . pidfile : pidfile = path . abspath ( self . config . daemon . pidfile ) if not os . access ( path . dirname ( pidfile ) , os . W_OK ) : raise ValueError ( 'Cannot write to specified pid file path' ' %s' % pidfile ) return pidfile app = sys . argv [ 0 ] . spli...
Return the normalized path for the pidfile raising an exception if it can not written to .
6,614
def _is_already_running ( self ) : pidfile = self . _get_pidfile_path ( ) if os . path . exists ( pidfile ) : pid = open ( pidfile ) . read ( ) . strip ( ) try : os . kill ( int ( pid ) , 0 ) sys . stderr . write ( 'Process already running as pid # %s\n' % pid ) return True except OSError as error : LOGGER . debug ( 'F...
Check to see if the process is running first looking for a pidfile then shelling out in either case removing a pidfile if it exists but the process is not running .
6,615
def _remove_pidfile ( self ) : LOGGER . debug ( 'Removing pidfile: %s' , self . pidfile_path ) try : os . unlink ( self . pidfile_path ) except OSError : pass
Remove the pid file from the filesystem
6,616
def _write_pidfile ( self ) : LOGGER . debug ( 'Writing pidfile: %s' , self . pidfile_path ) with open ( self . pidfile_path , "w" ) as handle : handle . write ( str ( os . getpid ( ) ) )
Write the pid file out with the process number in the pid file
6,617
def to_camel_case ( snake_case_string ) : parts = snake_case_string . lstrip ( '_' ) . split ( '_' ) return parts [ 0 ] + '' . join ( [ i . title ( ) for i in parts [ 1 : ] ] )
Convert a string from snake case to camel case . For example some_var would become someVar .
6,618
def to_capitalized_camel_case ( snake_case_string ) : parts = snake_case_string . split ( '_' ) return '' . join ( [ i . title ( ) for i in parts ] )
Convert a string from snake case to camel case with the first letter capitalized . For example some_var would become SomeVar .
6,619
def to_snake_case ( camel_case_string ) : first_pass = _first_camel_case_regex . sub ( r'\1_\2' , camel_case_string ) return _second_camel_case_regex . sub ( r'\1_\2' , first_pass ) . lower ( )
Convert a string from camel case to snake case . From example someVar would become some_var .
6,620
def keys_to_snake_case ( camel_case_dict ) : return dict ( ( to_snake_case ( key ) , value ) for ( key , value ) in camel_case_dict . items ( ) )
Make a copy of a dictionary with all keys converted to snake case . This is just calls to_snake_case on each of the keys in the dictionary and returns a new dictionary .
6,621
def list_functions ( awsclient ) : client_lambda = awsclient . get_client ( 'lambda' ) response = client_lambda . list_functions ( ) for function in response [ 'Functions' ] : log . info ( function [ 'FunctionName' ] ) log . info ( '\t' 'Memory: ' + str ( function [ 'MemorySize' ] ) ) log . info ( '\t' 'Timeout: ' + st...
List the deployed lambda functions and print configuration .
6,622
def deploy_lambda ( awsclient , function_name , role , handler_filename , handler_function , folders , description , timeout , memory , subnet_ids = None , security_groups = None , artifact_bucket = None , zipfile = None , fail_deployment_on_unsuccessful_ping = False , runtime = 'python2.7' , settings = None , environm...
Create or update a lambda function .
6,623
def bundle_lambda ( zipfile ) : if not zipfile : return 1 with open ( 'bundle.zip' , 'wb' ) as zfile : zfile . write ( zipfile ) log . info ( 'Finished - a bundle.zip is waiting for you...' ) return 0
Write zipfile contents to file .
6,624
def get_metrics ( awsclient , name ) : metrics = [ 'Duration' , 'Errors' , 'Invocations' , 'Throttles' ] client_cw = awsclient . get_client ( 'cloudwatch' ) for metric in metrics : response = client_cw . get_metric_statistics ( Namespace = 'AWS/Lambda' , MetricName = metric , Dimensions = [ { 'Name' : 'FunctionName' , ...
Print out cloudformation metrics for a lambda function .
6,625
def rollback ( awsclient , function_name , alias_name = ALIAS_NAME , version = None ) : if version : log . info ( 'rolling back to version {}' . format ( version ) ) else : log . info ( 'rolling back to previous version' ) version = _get_previous_version ( awsclient , function_name , alias_name ) if version == '0' : lo...
Rollback a lambda function to a given version .
6,626
def delete_lambda ( awsclient , function_name , events = None , delete_logs = False ) : if events is not None : unwire ( awsclient , events , function_name , alias_name = ALIAS_NAME ) client_lambda = awsclient . get_client ( 'lambda' ) response = client_lambda . delete_function ( FunctionName = function_name ) if delet...
Delete a lambda function .
6,627
def _stop_ec2_instances ( awsclient , ec2_instances , wait = True ) : if len ( ec2_instances ) == 0 : return client_ec2 = awsclient . get_client ( 'ec2' ) running_instances = all_pages ( client_ec2 . describe_instance_status , { 'InstanceIds' : ec2_instances , 'Filters' : [ { 'Name' : 'instance-state-name' , 'Values' :...
Helper to stop ec2 instances . By default it waits for instances to stop .
6,628
def _start_ec2_instances ( awsclient , ec2_instances , wait = True ) : if len ( ec2_instances ) == 0 : return client_ec2 = awsclient . get_client ( 'ec2' ) stopped_instances = all_pages ( client_ec2 . describe_instance_status , { 'InstanceIds' : ec2_instances , 'Filters' : [ { 'Name' : 'instance-state-name' , 'Values' ...
Helper to start ec2 instances
6,629
def _filter_db_instances_by_status ( awsclient , db_instances , status_list ) : client_rds = awsclient . get_client ( 'rds' ) db_instances_with_status = [ ] for db in db_instances : response = client_rds . describe_db_instances ( DBInstanceIdentifier = db ) for entry in response . get ( 'DBInstances' , [ ] ) : if entry...
helper to select dbinstances .
6,630
def stop_stack ( awsclient , stack_name , use_suspend = False ) : exit_code = 0 if not stack_exists ( awsclient , stack_name ) : log . warn ( 'Stack \'%s\' not deployed - nothing to do!' , stack_name ) else : client_cfn = awsclient . get_client ( 'cloudformation' ) client_autoscaling = awsclient . get_client ( 'autosca...
Stop an existing stack on AWS cloud .
6,631
def _get_autoscaling_min_max ( template , parameters , asg_name ) : params = { e [ 'ParameterKey' ] : e [ 'ParameterValue' ] for e in parameters } asg = template . get ( 'Resources' , { } ) . get ( asg_name , None ) if asg : assert asg [ 'Type' ] == 'AWS::AutoScaling::AutoScalingGroup' min = asg . get ( 'Properties' , ...
Helper to extract the configured MinSize MaxSize attributes from the template .
6,632
def _get_service_cluster_desired_count ( template , parameters , service_name ) : params = { e [ 'ParameterKey' ] : e [ 'ParameterValue' ] for e in parameters } service = template . get ( 'Resources' , { } ) . get ( service_name , None ) if service : assert service [ 'Type' ] == 'AWS::ECS::Service' cluster = service . ...
Helper to extract the configured desiredCount attribute from the template .
6,633
def start_stack ( awsclient , stack_name , use_suspend = False ) : exit_code = 0 if not stack_exists ( awsclient , stack_name ) : log . warn ( 'Stack \'%s\' not deployed - nothing to do!' , stack_name ) else : client_cfn = awsclient . get_client ( 'cloudformation' ) client_autoscaling = awsclient . get_client ( 'autosc...
Start an existing stack on AWS cloud .
6,634
def is_running ( self ) : return self . _state in [ self . STATE_ACTIVE , self . STATE_IDLE , self . STATE_INITIALIZING ]
Property method that returns a bool specifying if the process is currently running . This will return true if the state is active idle or initializing .
6,635
def process_signal ( self , signum ) : if signum == signal . SIGTERM : LOGGER . info ( 'Received SIGTERM, initiating shutdown' ) self . stop ( ) elif signum == signal . SIGHUP : LOGGER . info ( 'Received SIGHUP' ) if self . config . reload ( ) : LOGGER . info ( 'Configuration reloaded' ) logging . config . dictConfig (...
Invoked whenever a signal is added to the stack .
6,636
def run ( self ) : LOGGER . info ( '%s v%s started' , self . APPNAME , self . VERSION ) self . setup ( ) while not any ( [ self . is_stopping , self . is_stopped ] ) : self . set_state ( self . STATE_SLEEPING ) try : signum = self . pending_signals . get ( True , self . wake_interval ) except queue . Empty : pass else ...
The core method for starting the application . Will setup logging toggle the runtime state flag block on loop then call shutdown .
6,637
def stop ( self ) : LOGGER . info ( 'Attempting to stop the process' ) self . set_state ( self . STATE_STOP_REQUESTED ) self . shutdown ( ) while self . is_running and self . is_waiting_to_stop : LOGGER . info ( 'Waiting for the process to finish' ) time . sleep ( self . SLEEP_UNIT ) if not self . is_stopping : self . ...
Override to implement shutdown steps .
6,638
def _add_default_arguments ( parser ) : parser . add_argument ( '-c' , '--config' , action = 'store' , dest = 'config' , help = 'Path to the configuration file' ) parser . add_argument ( '-f' , '--foreground' , action = 'store_true' , dest = 'foreground' , help = 'Run the application interactively' )
Add the default arguments to the parser .
6,639
def dump ( pif , fp , ** kwargs ) : return json . dump ( pif , fp , cls = PifEncoder , ** kwargs )
Convert a single Physical Information Object or a list of such objects into a JSON - encoded text file .
6,640
def load ( fp , class_ = None , ** kwargs ) : return loado ( json . load ( fp , ** kwargs ) , class_ = class_ )
Convert content in a JSON - encoded text file to a Physical Information Object or a list of such objects .
6,641
def loads ( s , class_ = None , ** kwargs ) : return loado ( json . loads ( s , ** kwargs ) , class_ = class_ )
Convert content in a JSON - encoded string to a Physical Information Object or a list of such objects .
6,642
def loado ( obj , class_ = None ) : if isinstance ( obj , list ) : return [ _dict_to_pio ( i , class_ = class_ ) for i in obj ] elif isinstance ( obj , dict ) : return _dict_to_pio ( obj , class_ = class_ ) else : raise ValueError ( 'expecting list or dictionary as outermost structure' )
Convert a dictionary or a list of dictionaries into a single Physical Information Object or a list of such objects .
6,643
def _dict_to_pio ( d , class_ = None ) : d = keys_to_snake_case ( d ) if class_ : return class_ ( ** d ) if 'category' not in d : raise ValueError ( 'Dictionary does not contains a category field: ' + ', ' . join ( d . keys ( ) ) ) elif d [ 'category' ] == 'system' : return System ( ** d ) elif d [ 'category' ] == 'sys...
Convert a single dictionary object to a Physical Information Object .
6,644
def get_command ( arguments ) : cmds = list ( filter ( lambda k : not ( k . startswith ( '-' ) or k . startswith ( '<' ) ) and arguments [ k ] , arguments . keys ( ) ) ) if len ( cmds ) != 1 : raise Exception ( 'invalid command line!' ) return cmds [ 0 ]
Utility function to extract command from docopt arguments .
6,645
def dispatch ( cls , arguments , ** kwargs ) : for spec , func in cls . _specs : args = [ ] options = list ( filter ( lambda k : k . startswith ( '-' ) and ( arguments [ k ] or k in spec ) , arguments . keys ( ) ) ) cmds = list ( filter ( lambda k : not ( k . startswith ( '-' ) or k . startswith ( '<' ) ) and arguments...
Dispatch arguments parsed by docopt to the cmd with matching spec .
6,646
def convert_representation ( self , i ) : if self . number_representation == 'unsigned' : return i elif self . number_representation == 'signed' : if i & ( 1 << self . interpreter . _bit_width - 1 ) : return - ( ( ~ i + 1 ) & ( 2 ** self . interpreter . _bit_width - 1 ) ) else : return i elif self . number_representati...
Return the proper representation for the given integer
6,647
def magic_generate_random ( self , line ) : line = line . strip ( ) . lower ( ) if not line or line == 'true' : self . interpreter . generate_random = True elif line == 'false' : self . interpreter . generate_random = False else : stream_content = { 'name' : 'stderr' , 'text' : "unknwon value '{}'" . format ( line ) } ...
Set the generate random flag unset registers and memory will return a random value .
6,648
def magic_postpone_execution ( self , line ) : line = line . strip ( ) . lower ( ) if not line or line == 'true' : self . interpreter . postpone_execution = True elif line == 'false' : self . interpreter . postpone_execution = False else : stream_content = { 'name' : 'stderr' , 'text' : "unknwon value '{}'" . format ( ...
Postpone execution of instructions until explicitly run
6,649
def magic_register ( self , line ) : message = "" for reg in [ i . strip ( ) for i in line . replace ( ',' , '' ) . split ( ) ] : if '-' in reg : r1 , r2 = reg . split ( '-' ) n1 = re . search ( self . interpreter . REGISTER_REGEX , r1 ) . groups ( ) [ 0 ] n2 = re . search ( self . interpreter . REGISTER_REGEX , r2 ) ....
Print out the current value of a register
6,650
def magic_memory ( self , line ) : message = "" for address in [ i . strip ( ) for i in line . replace ( ',' , '' ) . split ( ) ] : if '-' in address : m1 , m2 = address . split ( '-' ) n1 = re . search ( self . interpreter . IMMEDIATE_NUMBER , m1 ) . groups ( ) [ 0 ] n2 = re . search ( self . interpreter . IMMEDIATE_N...
Print out the current value of memory
6,651
def magic_run ( self , line ) : i = float ( 'inf' ) if line . strip ( ) : i = int ( line ) try : with warnings . catch_warnings ( record = True ) as w : self . interpreter . run ( i ) for warning_message in w : stream_content = { 'name' : 'stdout' , 'text' : 'Warning: ' + str ( warning_message . message ) + '\n' } self...
Run the current program
6,652
def magic_help ( self , line ) : line = line . strip ( ) if not line : for magic in self . magics : stream_content = { 'name' : 'stdout' , 'text' : "%{}\n" . format ( magic ) } self . send_response ( self . iopub_socket , 'stream' , stream_content ) elif line in self . magics : stream_content = { 'name' : 'stdout' , 't...
Print out the help for magics
6,653
def list_apis ( awsclient ) : client_api = awsclient . get_client ( 'apigateway' ) apis = client_api . get_rest_apis ( ) [ 'items' ] for api in apis : print ( json2table ( api ) )
List APIs in account .
6,654
def deploy_api ( awsclient , api_name , api_description , stage_name , api_key , lambdas , cache_cluster_enabled , cache_cluster_size , method_settings = None ) : if not _api_exists ( awsclient , api_name ) : if os . path . isfile ( SWAGGER_FILE ) : _import_from_swagger ( awsclient , api_name , api_description , stage_...
Deploy API Gateway to AWS cloud .
6,655
def delete_api ( awsclient , api_name ) : _sleep ( ) client_api = awsclient . get_client ( 'apigateway' ) print ( 'deleting api: %s' % api_name ) api = _api_by_name ( awsclient , api_name ) if api is not None : print ( json2table ( api ) ) response = client_api . delete_rest_api ( restApiId = api [ 'id' ] ) print ( jso...
Delete the API .
6,656
def create_api_key ( awsclient , api_name , api_key_name ) : _sleep ( ) client_api = awsclient . get_client ( 'apigateway' ) print ( 'create api key: %s' % api_key_name ) response = client_api . create_api_key ( name = api_key_name , description = 'Created for ' + api_name , enabled = True ) print ( 'Add this api key \...
Create a new API key as reference for api . conf .
6,657
def delete_api_key ( awsclient , api_key ) : _sleep ( ) client_api = awsclient . get_client ( 'apigateway' ) print ( 'delete api key: %s' % api_key ) response = client_api . delete_api_key ( apiKey = api_key ) print ( json2table ( response ) )
Remove API key .
6,658
def list_api_keys ( awsclient ) : _sleep ( ) client_api = awsclient . get_client ( 'apigateway' ) print ( 'listing api keys' ) response = client_api . get_api_keys ( ) [ 'items' ] for item in response : print ( json2table ( item ) )
Print the defined API keys .
6,659
def deploy_custom_domain ( awsclient , api_name , api_target_stage , api_base_path , domain_name , route_53_record , cert_name , cert_arn , hosted_zone_id , ensure_cname ) : api_base_path = _basepath_to_string_if_null ( api_base_path ) api = _api_by_name ( awsclient , api_name ) if not api : print ( "Api %s does not ex...
Add custom domain to your API .
6,660
def get_lambdas ( awsclient , config , add_arn = False ) : if 'lambda' in config : client_lambda = awsclient . get_client ( 'lambda' ) lambda_entries = config [ 'lambda' ] . get ( 'entries' , [ ] ) lmbdas = [ ] for lambda_entry in lambda_entries : lmbda = { 'name' : lambda_entry . get ( 'name' , None ) , 'alias' : lamb...
Get the list of lambda functions .
6,661
def _update_stage ( awsclient , api_id , stage_name , method_settings ) : client_api = awsclient . get_client ( 'apigateway' ) operations = _convert_method_settings_into_operations ( method_settings ) if operations : print ( 'update method settings for stage' ) _sleep ( ) response = client_api . update_stage ( restApiI...
Helper to apply method_settings to stage
6,662
def _convert_method_settings_into_operations ( method_settings = None ) : operations = [ ] if method_settings : for method in method_settings . keys ( ) : for key , value in method_settings [ method ] . items ( ) : if isinstance ( value , bool ) : if value : value = 'true' else : value = 'false' operations . append ( {...
Helper to handle the conversion of method_settings to operations
6,663
def generate_settings ( ) : conf_file = os . path . join ( os . path . dirname ( base_settings . __file__ ) , 'example' , 'conf.py' ) conf_template = open ( conf_file ) . read ( ) default_url = 'http://salmon.example.com' site_url = raw_input ( "What will be the URL for Salmon? [{0}]" . format ( default_url ) ) site_ur...
This command is run when default_path doesn t exist or init is run and returns a string representing the default data to put into their settings file .
6,664
def configure_app ( ** kwargs ) : sys_args = sys . argv args , command , command_args = parse_args ( sys_args [ 1 : ] ) parser = OptionParser ( ) parser . add_option ( '--config' , metavar = 'CONFIG' ) ( options , logan_args ) = parser . parse_args ( args ) config_path = options . config logan_configure ( config_path =...
Builds up the settings using the same method as logan
6,665
def _reset_changes ( self ) : self . _original = { } if self . last_updated is not None : self . _original [ 'last_updated' ] = self . last_updated
Stores current values for comparison later
6,666
def whisper_filename ( self ) : source_name = self . source_id and self . source . name or '' return get_valid_filename ( "{0}__{1}.wsp" . format ( source_name , self . name ) )
Build a file path to the Whisper database
6,667
def get_value_display ( self ) : if self . display_as == 'percentage' : return '{0}%' . format ( self . latest_value ) if self . display_as == 'boolean' : return bool ( self . latest_value ) if self . display_as == 'byte' : return defaultfilters . filesizeformat ( self . latest_value ) if self . display_as == 'second' ...
Human friendly value output
6,668
def time_between_updates ( self ) : if 'last_updated' not in self . _original : return 0 last_update = self . _original [ 'last_updated' ] this_update = self . last_updated return this_update - last_update
Time between current last_updated and previous last_updated
6,669
def do_counter_conversion ( self ) : if self . is_counter : if self . _previous_counter_value is None : prev_value = self . latest_value else : prev_value = self . _previous_counter_value self . _previous_counter_value = self . latest_value self . latest_value = self . latest_value - prev_value
Update latest value to the diff between it and the previous value
6,670
def replace_variable ( self , variable ) : if variable == 'x' : return self . value if variable == 't' : return self . timedelta raise ValueError ( "Invalid variable %s" , variable )
Substitute variables with numeric values
6,671
def result ( self ) : return self . eval_ ( ast . parse ( self . expr ) . body [ 0 ] . value )
Evaluate expression and return result
6,672
def email_login ( request , * , email , ** kwargs ) : _u , created = auth . get_user_model ( ) . _default_manager . get_or_create ( email = email ) user = auth . authenticate ( request , email = email ) if user and user . is_active : auth . login ( request , user ) return user , created return None , None
Given a request an email and optionally some additional data ensure that a user with the email address exists and authenticate & login them right away if the user is active .
6,673
def dashboard ( request ) : sources = ( models . Source . objects . all ( ) . prefetch_related ( 'metric_set' ) . order_by ( 'name' ) ) metrics = SortedDict ( [ ( src , src . metric_set . all ( ) ) for src in sources ] ) no_source_metrics = models . Metric . objects . filter ( source__isnull = True ) if no_source_metri...
Shows the latest results for each source
6,674
def _create ( self ) : if not os . path . exists ( settings . SALMON_WHISPER_DB_PATH ) : os . makedirs ( settings . SALMON_WHISPER_DB_PATH ) archives = [ whisper . parseRetentionDef ( retentionDef ) for retentionDef in settings . ARCHIVES . split ( "," ) ] whisper . create ( self . path , archives , xFilesFactor = sett...
Create the Whisper file on disk
6,675
def _update ( self , datapoints ) : if len ( datapoints ) == 1 : timestamp , value = datapoints [ 0 ] whisper . update ( self . path , value , timestamp ) else : whisper . update_many ( self . path , datapoints )
This method store in the datapoints in the current database .
6,676
def fetch ( self , from_time , until_time = None ) : until_time = until_time or datetime . now ( ) time_info , values = whisper . fetch ( self . path , from_time . strftime ( '%s' ) , until_time . strftime ( '%s' ) ) start_time , end_time , step = time_info current = start_time times = [ ] while current <= end_time : t...
This method fetch data from the database according to the period given
6,677
def CMN ( self , params ) : Ra , Rb = self . get_two_parameters ( self . TWO_PARAMETER_COMMA_SEPARATED , params ) self . check_arguments ( low_registers = ( Ra , Rb ) ) def CMN_func ( ) : self . set_NZCV_flags ( self . register [ Ra ] , self . register [ Rb ] , self . register [ Ra ] + self . register [ Rb ] , 'add' ) ...
CMN Ra Rb
6,678
def MULS ( self , params ) : Ra , Rb , Rc = self . get_three_parameters ( self . THREE_PARAMETER_COMMA_SEPARATED , params ) self . check_arguments ( low_registers = ( Ra , Rb , Rc ) ) if Ra != Rc : raise iarm . exceptions . RuleError ( "Third parameter {} is not the same as the first parameter {}" . format ( Rc , Ra ) ...
MULS Ra Rb Ra
6,679
def initialize ( template , service_name , environment = 'dev' ) : template . SERVICE_NAME = os . getenv ( 'SERVICE_NAME' , service_name ) template . SERVICE_ENVIRONMENT = os . getenv ( 'ENV' , environment ) . lower ( ) template . DEFAULT_TAGS = troposphere . Tags ( ** { 'service-name' : template . SERVICE_NAME , 'envi...
Adds SERVICE_NAME SERVICE_ENVIRONMENT and DEFAULT_TAGS to the template
6,680
def get_dist ( dist_name , lookup_dirs = None ) : req = pkg_resources . Requirement . parse ( dist_name ) if lookup_dirs is None : working_set = pkg_resources . WorkingSet ( ) else : working_set = pkg_resources . WorkingSet ( lookup_dirs ) return working_set . find ( req )
Get dist for installed version of dist_name avoiding pkg_resources cache
6,681
def _load_hooks ( path ) : module = imp . load_source ( os . path . splitext ( os . path . basename ( path ) ) [ 0 ] , path ) if not check_hook_mechanism_is_intact ( module ) : log . debug ( 'No valid hook configuration: \'%s\'. Not using hooks!' , path ) else : if check_register_present ( module ) : module . register ...
Load hook module and register signals .
6,682
def main ( doc , tool , dispatch_only = None ) : signal . signal ( signal . SIGTERM , signal_handler ) signal . signal ( signal . SIGINT , signal_handler ) try : arguments = docopt ( doc , sys . argv [ 1 : ] ) command = get_command ( arguments ) verbose = arguments . pop ( '--verbose' , False ) if verbose : logging_con...
gcdt tools parametrized main function to initiate gcdt lifecycle .
6,683
def MOV ( self , params ) : Rx , Ry = self . get_two_parameters ( self . TWO_PARAMETER_COMMA_SEPARATED , params ) self . check_arguments ( any_registers = ( Rx , Ry ) ) def MOV_func ( ) : self . register [ Rx ] = self . register [ Ry ] return MOV_func
MOV Rx Ry MOV PC Ry
6,684
def MRS ( self , params ) : Rj , Rspecial = self . get_two_parameters ( self . TWO_PARAMETER_COMMA_SEPARATED , params ) self . check_arguments ( LR_or_general_purpose_registers = ( Rj , ) , special_registers = ( Rspecial , ) ) def MRS_func ( ) : if Rspecial == 'PSR' : self . register [ Rj ] = self . register [ 'APSR' ]...
MRS Rj Rspecial
6,685
def MSR ( self , params ) : Rspecial , Rj = self . get_two_parameters ( self . TWO_PARAMETER_COMMA_SEPARATED , params ) self . check_arguments ( LR_or_general_purpose_registers = ( Rj , ) , special_registers = ( Rspecial , ) ) def MSR_func ( ) : if Rspecial in ( 'PSR' , 'APSR' ) : self . register [ 'APSR' ] = self . re...
MSR Rspecial Rj
6,686
def MVNS ( self , params ) : Ra , Rb = self . get_two_parameters ( self . TWO_PARAMETER_COMMA_SEPARATED , params ) self . check_arguments ( low_registers = ( Ra , Rb ) ) def MVNS_func ( ) : self . register [ Ra ] = ~ self . register [ Rb ] self . set_NZ_flags ( self . register [ Ra ] ) return MVNS_func
MVNS Ra Rb
6,687
def REV ( self , params ) : Ra , Rb = self . get_two_parameters ( self . TWO_PARAMETER_COMMA_SEPARATED , params ) self . check_arguments ( low_registers = ( Ra , Rb ) ) def REV_func ( ) : self . register [ Ra ] = ( ( self . register [ Rb ] & 0xFF000000 ) >> 24 ) | ( ( self . register [ Rb ] & 0x00FF0000 ) >> 8 ) | ( ( ...
REV Ra Rb
6,688
def REV16 ( self , params ) : Ra , Rb = self . get_two_parameters ( self . TWO_PARAMETER_COMMA_SEPARATED , params ) self . check_arguments ( low_registers = ( Ra , Rb ) ) def REV16_func ( ) : self . register [ Ra ] = ( ( self . register [ Rb ] & 0xFF00FF00 ) >> 8 ) | ( ( self . register [ Rb ] & 0x00FF00FF ) << 8 ) ret...
REV16 Ra Rb
6,689
def SXTB ( self , params ) : Ra , Rb = self . get_two_parameters ( r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*' , params ) self . check_arguments ( low_registers = ( Ra , Rb ) ) def SXTB_func ( ) : if self . register [ Rb ] & ( 1 << 7 ) : self . register [ Ra ] = 0xFFFFFF00 + ( self . register [ Rb ] & 0xFF ) else : s...
STXB Ra Rb
6,690
def SXTH ( self , params ) : Ra , Rb = self . get_two_parameters ( r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*' , params ) self . check_arguments ( low_registers = ( Ra , Rb ) ) def SXTH_func ( ) : if self . register [ Rb ] & ( 1 << 15 ) : self . register [ Ra ] = 0xFFFF0000 + ( self . register [ Rb ] & 0xFFFF ) else ...
STXH Ra Rb
6,691
def UXTB ( self , params ) : Ra , Rb = self . get_two_parameters ( r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*' , params ) self . check_arguments ( low_registers = ( Ra , Rb ) ) def UXTB_func ( ) : self . register [ Ra ] = ( self . register [ Rb ] & 0xFF ) return UXTB_func
UTXB Ra Rb
6,692
def UXTH ( self , params ) : Ra , Rb = self . get_two_parameters ( r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*' , params ) self . check_arguments ( low_registers = ( Ra , Rb ) ) def UXTH_func ( ) : self . register [ Ra ] = ( self . register [ Rb ] & 0xFFFF ) return UXTH_func
UTXH Ra Rb
6,693
def _get_event_source_obj ( awsclient , evt_source ) : event_source_map = { 'dynamodb' : event_source . dynamodb_stream . DynamoDBStreamEventSource , 'kinesis' : event_source . kinesis . KinesisEventSource , 's3' : event_source . s3 . S3EventSource , 'sns' : event_source . sns . SNSEventSource , 'events' : event_source...
Given awsclient event_source dictionary item create an event_source object of the appropriate event type to schedule this event and return the object .
6,694
def unwire ( awsclient , events , lambda_name , alias_name = ALIAS_NAME ) : if not lambda_exists ( awsclient , lambda_name ) : log . error ( colored . red ( 'The function you try to wire up doesn\'t ' + 'exist... Bailing out...' ) ) return 1 client_lambda = awsclient . get_client ( 'lambda' ) lambda_function = client_l...
Unwire a list of event from an AWS Lambda function .
6,695
def wire_deprecated ( awsclient , function_name , s3_event_sources = None , time_event_sources = None , alias_name = ALIAS_NAME ) : if not lambda_exists ( awsclient , function_name ) : log . error ( colored . red ( 'The function you try to wire up doesn\'t ' + 'exist... Bailing out...' ) ) return 1 client_lambda = awsc...
Deprecated! Please use wire!
6,696
def unwire_deprecated ( awsclient , function_name , s3_event_sources = None , time_event_sources = None , alias_name = ALIAS_NAME ) : if not lambda_exists ( awsclient , function_name ) : log . error ( colored . red ( 'The function you try to wire up doesn\'t ' + 'exist... Bailing out...' ) ) return 1 client_lambda = aw...
Deprecated! Please use unwire!
6,697
def _lambda_add_s3_event_source ( awsclient , arn , event , bucket , prefix , suffix ) : json_data = { 'LambdaFunctionConfigurations' : [ { 'LambdaFunctionArn' : arn , 'Id' : str ( uuid . uuid1 ( ) ) , 'Events' : [ event ] } ] } filter_rules = build_filter_rules ( prefix , suffix ) json_data [ 'LambdaFunctionConfigurat...
Use only prefix OR suffix
6,698
def find_eigen ( hint = None ) : r try : import pkgconfig if pkgconfig . installed ( 'eigen3' , '>3.0.0' ) : return pkgconfig . parse ( 'eigen3' ) [ 'include_dirs' ] [ 0 ] except : pass search_dirs = [ ] if hint is None else hint search_dirs += [ "/usr/local/include/eigen3" , "/usr/local/homebrew/include/eigen3" , "/op...
r Try to find the Eigen library . If successful the include directory is returned .
6,699
def check_and_format_logs_params ( start , end , tail ) : def _decode_duration_type ( duration_type ) : durations = { 'm' : 'minutes' , 'h' : 'hours' , 'd' : 'days' , 'w' : 'weeks' } return durations [ duration_type ] if not start : if tail : start_dt = maya . now ( ) . subtract ( seconds = 300 ) . datetime ( naive = T...
Helper to read the params for the logs command