idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
49,900
def get_file ( self , file_name , local_destination = None , ** kwargs ) : if not local_destination : local_destination = file_name return SubprocessTask ( self . _rsync_cmd ( ) + [ '-ut' , '%s:%s' % ( self . hostname , file_name ) , local_destination ] , ** kwargs )
Get a file from a remote host with rsync .
49,901
def make_config ( self , data : dict ) : self . validate_config ( data ) config_data = self . prepare_config ( data ) return config_data
Make a MIP config .
49,902
def validate_config ( data : dict ) -> dict : errors = ConfigSchema ( ) . validate ( data ) if errors : for field , messages in errors . items ( ) : if isinstance ( messages , dict ) : for level , sample_errors in messages . items ( ) : sample_id = data [ 'samples' ] [ level ] [ 'sample_id' ] for sub_field , sub_messag...
Convert to MIP config format .
49,903
def prepare_config ( data : dict ) -> dict : data_copy = deepcopy ( data ) if len ( data_copy [ 'samples' ] ) == 1 : if data_copy [ 'samples' ] [ 0 ] [ 'phenotype' ] == 'unknown' : LOG . info ( "setting 'unknown' phenotype to 'unaffected'" ) data_copy [ 'samples' ] [ 0 ] [ 'phenotype' ] = 'unaffected' for sample_data i...
Prepare the config data .
49,904
def save_config ( self , data : dict ) -> Path : out_dir = Path ( self . families_dir ) / data [ 'family' ] out_dir . mkdir ( parents = True , exist_ok = True ) out_path = out_dir / 'pedigree.yaml' dump = ruamel . yaml . round_trip_dump ( data , indent = 4 , block_seq_indent = 2 ) out_path . write_text ( dump ) return ...
Save a config to the expected location .
49,905
def create_broadcast ( src_atr_name , dest_processors , dest_atr_name = None , transform_function = lambda x : x ) : from functools import partial if dest_atr_name == None : dest_atr_name = src_atr_name if not hasattr ( dest_processors , "__iter__" ) : dest_processors = [ dest_processors ] return partial ( _broadcast ,...
This method creates a function intended to be called as a Processor posthook that copies some of the processor s attributes to other processors
49,906
def get_parameters ( self ) : parameter_names = self . PARAMETERS . keys ( ) parameter_values = [ getattr ( processor , n ) for n in parameter_names ] return dict ( zip ( parameter_names , parameter_values ) )
returns a dictionary with the processor s stored parameters
49,907
def set_parameters ( self , ** args ) : for k , v in self . PARAMETERS . items ( ) : new_value = args . get ( k ) if new_value != None : if not _same_type ( new_value , v ) : raise Exception ( "On processor {0}, argument {1} takes something like {2}, but {3} was given" . format ( self , k , v , new_value ) ) setattr ( ...
sets the processor stored parameters
49,908
def get_parameters ( self ) : d = { } for p in self . processors : parameter_names = list ( p . PARAMETERS . keys ( ) ) parameter_values = [ getattr ( p , n ) for n in parameter_names ] d . update ( dict ( zip ( parameter_names , parameter_values ) ) ) return d
gets from all wrapped processors
49,909
def set_parameters ( self , ** args ) : not_used = set ( ) not_given = set ( ) for p in self . processors : nu , ng = p . set_parameters ( ** args ) not_used = not_used . union ( nu ) not_given = not_given . union ( ng ) return not_used , not_given
sets to all wrapped processors
49,910
def render ( self , filename ) : self . elapsed_time = - time ( ) dpi = 100 fig = figure ( figsize = ( 16 , 9 ) , dpi = dpi ) with self . writer . saving ( fig , filename , dpi ) : for frame_id in xrange ( self . frames + 1 ) : self . renderFrame ( frame_id ) self . writer . grab_frame ( ) self . elapsed_time += time (...
Perform initialization of render set quality and size video attributes and then call template method that is defined in child class .
49,911
def report ( self ) : message = 'Elapsed in {0} seconds with {1} frames and {2} step.' print ( message . format ( self . elapsed_time , self . frames , self . step ) )
Prints in standard output report about animation rendering . Namely it prints seconds spent number of frames and step size that is used in functional animation .
49,912
def update ( self , addresses ) : if isinstance ( addresses , six . string_types ) : addresses = [ addresses , ] s0_ , s1_ = set ( self . addresses ) , set ( addresses ) sr_ , sa_ = s0_ . difference ( s1_ ) , s1_ . difference ( s0_ ) for a__ in sr_ : self . remove ( a__ ) for a__ in sa_ : self . add ( a__ ) return bool...
Updating with a set of addresses .
49,913
def _add_hook ( self , socket , callback ) : self . _hooks . append ( socket ) self . _hooks_cb [ socket ] = callback if self . poller : self . poller . register ( socket , POLLIN )
Generic hook . The passed socket has to be receive only .
49,914
def _magickfy_topics ( topics ) : if topics is None : return None if isinstance ( topics , six . string_types ) : topics = [ topics , ] ts_ = [ ] for t__ in topics : if not t__ . startswith ( _MAGICK ) : if t__ and t__ [ 0 ] == '/' : t__ = _MAGICK + t__ else : t__ = _MAGICK + '/' + t__ ts_ . append ( t__ ) return ts_
Add the magick to the topics if missing .
49,915
def start ( self ) : def _get_addr_loop ( service , timeout ) : then = datetime . now ( ) + timedelta ( seconds = timeout ) while datetime . now ( ) < then : addrs = get_pub_address ( service , nameserver = self . _nameserver ) if addrs : return [ addr [ "URI" ] for addr in addrs ] time . sleep ( 1 ) return [ ] LOGGER ...
Start the subscriber .
49,916
def _get_transient_metadata_from_database_list ( self ) : self . log . debug ( 'starting the ``_get_transient_metadata_from_database_list`` method' ) sqlQuery = self . settings [ "database settings" ] [ "transients" ] [ "transient query" ] + " limit " + str ( self . largeBatchSize ) thisInt = randint ( 0 , 100 ) if "wh...
use the transient query in the settings file to generate a list of transients to corssmatch and classify
49,917
def _remove_previous_ned_queries ( self , coordinateList ) : self . log . debug ( 'starting the ``_remove_previous_ned_queries`` method' ) radius = 60. * 60. updatedCoordinateList = [ ] keepers = [ ] now = datetime . now ( ) td = timedelta ( days = self . settings [ "ned stream refresh rate in days" ] ) refreshLimit = ...
iterate through the transient locations to see if we have recent local NED coverage of that area already
49,918
def _crossmatch_transients_against_catalogues ( self , transientsMetadataListIndex , colMaps ) : global theseBatches self . log . debug ( 'starting the ``_crossmatch_transients_against_catalogues`` method' ) transientsMetadataList = theseBatches [ transientsMetadataListIndex ] dbConn = database ( log = self . log , dbS...
run the transients through the crossmatch algorithm in the settings file
49,919
def name_file ( lane : int , flowcell : str , sample : str , read : int , undetermined : bool = False , date : dt . datetime = None , index : str = None ) -> str : flowcell = f"{flowcell}-undetermined" if undetermined else flowcell date_str = date . strftime ( '%y%m%d' ) if date else '171015' index = index if index els...
Name a FASTQ file following MIP conventions .
49,920
def link ( self , family : str , sample : str , analysis_type : str , files : List [ str ] ) : root_dir = Path ( self . families_dir ) / family / analysis_type / sample / 'fastq' root_dir . mkdir ( parents = True , exist_ok = True ) for fastq_data in files : fastq_path = Path ( fastq_data [ 'path' ] ) fastq_name = self...
Link FASTQ files for a sample .
49,921
def mcast_sender ( mcgroup = MC_GROUP ) : sock = socket ( AF_INET , SOCK_DGRAM ) sock . setsockopt ( SOL_SOCKET , SO_REUSEADDR , 1 ) if _is_broadcast_group ( mcgroup ) : group = '<broadcast>' sock . setsockopt ( SOL_SOCKET , SO_BROADCAST , 1 ) elif ( ( int ( mcgroup . split ( "." ) [ 0 ] ) > 239 ) or ( int ( mcgroup . ...
Non - object interface for sending multicast messages .
49,922
def mcast_receiver ( port , mcgroup = MC_GROUP ) : if _is_broadcast_group ( mcgroup ) : group = None else : group = mcgroup sock = socket ( AF_INET , SOCK_DGRAM ) sock . setsockopt ( SOL_SOCKET , SO_REUSEADDR , 1 ) if group : sock . setsockopt ( SOL_IP , IP_MULTICAST_TTL , TTL_LOCALNET ) sock . setsockopt ( SOL_IP , IP...
Open a UDP socket bind it to a port and select a multicast group .
49,923
def close ( self ) : self . socket . setsockopt ( SOL_SOCKET , SO_LINGER , struct . pack ( 'ii' , 1 , 1 ) ) self . socket . close ( )
Close the receiver .
49,924
def _delete_temp_logs ( self , family_name : str ) : for temp_log in self . store . analyses ( family = family_name , temp = True ) : log . debug ( f"delete temporary log: {temp_log.id} - {temp_log.status}" ) temp_log . delete ( )
Delete temporary logs for the current family .
49,925
def parse ( cls , config_data : dict , sampleinfo_data : dict , sacct_jobs : List [ dict ] , jobs : int ) -> dict : analysis_types = [ sample [ 'type' ] for sample in config_data [ 'samples' ] ] run_data = { 'user' : config_data [ 'email' ] , 'family' : config_data [ 'family' ] , 'priority' : config_data [ 'priority' ]...
Parse information about a run .
49,926
def _parse_sacct ( sacct_jobs : List [ dict ] , jobs_count : int = None ) : failed_jobs = sacct_api . filter_jobs ( sacct_jobs , failed = True ) completed_jobs = [ job for job in sacct_jobs if job [ 'is_completed' ] ] last_job_end = completed_jobs [ - 1 ] [ 'end' ] if len ( completed_jobs ) > 0 else None data = { 'jobs...
Parse out info from Sacct log .
49,927
def _get_analysis_type ( analysis_types : List [ str ] ) -> str : types_set = set ( analysis_types ) return types_set . pop ( ) if len ( types_set ) == 1 else 'wgs'
Determine the overall analysis type .
49,928
def build ( self , run_data : dict ) -> models . Analysis : existing_run = self . store . find_analysis ( family = run_data [ 'family' ] , started_at = run_data [ 'started_at' ] , status = run_data [ 'status' ] ) if existing_run : return None run_data [ 'user' ] = self . store . user ( run_data [ 'user' ] ) new_failed_...
Build a new Analysis object .
49,929
def get_default_value ( self ) : default = self . default_value if isinstance ( default , collections . Callable ) : default = default ( ) return default
return default value
49,930
def _init_compiled ( cls , dialect , connection , dbapi_connection , compiled , parameters ) : self = cls . __new__ ( cls ) self . root_connection = connection self . _dbapi_connection = dbapi_connection self . dialect = connection . dialect self . compiled = compiled assert compiled . can_execute self . execution_opti...
Initialize execution context for a Compiled construct .
49,931
def takes_instance_or_queryset ( func ) : @ wraps ( func ) def decorated_function ( self , request , queryset ) : if not isinstance ( queryset , QuerySet ) : try : queryset = self . get_queryset ( request ) . filter ( pk = queryset . pk ) except AttributeError : try : model = queryset . _meta . model except AttributeEr...
Decorator that makes standard Django admin actions compatible .
49,932
def get_urls ( self ) : urls = super ( BaseDjangoObjectActions , self ) . get_urls ( ) return self . _get_action_urls ( ) + urls
Prepend get_urls with our own patterns .
49,933
def _get_action_urls ( self ) : actions = { } model_name = self . model . _meta . model_name base_url_name = '%s_%s' % ( self . model . _meta . app_label , model_name ) model_actions_url_name = '%s_actions' % base_url_name self . tools_view_name = 'admin:' + model_actions_url_name for action in chain ( self . change_ac...
Get the url patterns that route each action to a view .
49,934
def _get_tool_dict ( self , tool_name ) : tool = getattr ( self , tool_name ) standard_attrs , custom_attrs = self . _get_button_attrs ( tool ) return dict ( name = tool_name , label = getattr ( tool , 'label' , tool_name ) , standard_attrs = standard_attrs , custom_attrs = custom_attrs , )
Represents the tool as a dict with extra meta .
49,935
def _get_button_attrs ( self , tool ) : attrs = getattr ( tool , 'attrs' , { } ) if 'href' in attrs : attrs . pop ( 'href' ) if 'title' in attrs : attrs . pop ( 'title' ) default_attrs = { 'class' : attrs . get ( 'class' , '' ) , 'title' : getattr ( tool , 'short_description' , '' ) , } standard_attrs = { } custom_attr...
Get the HTML attributes associated with a tool .
49,936
def question_mark ( self , request , obj ) : obj . question = obj . question + '?' obj . save ( )
Add a question mark .
49,937
def build_link ( href , text , cls = None , icon_class = None , ** attrs ) : return build_html_element ( tag = 'a' , text = text , href = href , cls = cls , icon_class = icon_class , ** attrs )
Builds an html link .
49,938
def build_html_element ( tag , text = None , icon_class = None , cls = None , ** kwargs ) : if cls is not None : kwargs [ 'class' ] = cls tag_attrs = ' ' . join ( [ '{0}="{1}"' . format ( k , v ) for k , v in kwargs . items ( ) ] ) tag_content = '{tag} {tag_attrs}' . format ( tag = tag , tag_attrs = tag_attrs ) if tag ...
Builds an html element .
49,939
def dump_migration_session_state ( raw ) : class BlockStyle ( str ) : pass class SessionDumper ( yaml . SafeDumper ) : pass def str_block_formatter ( dumper , data ) : return dumper . represent_scalar ( u'tag:yaml.org,2002:str' , data , style = '|' ) SessionDumper . add_representer ( BlockStyle , str_block_formatter ) ...
Serialize a migration session state to yaml using nicer formatting
49,940
def add_migrations ( self , migrations ) : if self . __closed : raise MigrationSessionError ( "Can't change applied session" ) self . _to_apply . extend ( migrations )
Add migrations to be applied .
49,941
def _get_current_migration_state ( self , loader , apps ) : apps = set ( apps ) relevant_applied = [ migration for migration in loader . applied_migrations if migration [ 0 ] in apps ] most_recents = dict ( sorted ( relevant_applied , key = lambda m : m [ 1 ] ) ) most_recents = [ [ app , 'zero' if app not in most_recen...
Extract the most recent migrations from the relevant apps . If no migrations have been performed return zero as the most recent migration for the app .
49,942
def list_migrations ( self ) : connection = connections [ self . _database_name ] loader = MigrationLoader ( connection , ignore_no_migrations = True ) unapplied = self . _get_unapplied_migrations ( loader ) currents = self . _get_current_migration_state ( loader , [ u [ 0 ] for u in unapplied ] ) return unapplied , cu...
Returns a tuple of unapplied current
49,943
def __apply ( self , migration = None , run_all = False ) : out = StringIO ( ) trace = None migrate_kwargs = { 'interactive' : False , 'stdout' : out , 'database' : self . _database_name , } if migration is not None : migrate_kwargs . update ( { 'app_label' : migration [ 0 ] , 'migration_name' : migration [ 1 ] , } ) e...
If a migration is supplied runs that migration and appends to state . If run_all == True runs all migrations . Raises a ValueError if neither migration nor run_all are provided .
49,944
def apply ( self ) : if self . __closed : raise MigrationSessionError ( "Can't apply applied session" ) try : while self . _to_apply : self . __apply ( migration = self . _to_apply . pop ( 0 ) ) except : raise finally : self . __closed = True
Applies all migrations that have been added . Note that some migrations depend on others so you might end up running more than one .
49,945
def apply_all ( self ) : if self . __closed : raise MigrationSessionError ( "Can't apply applied session" ) if self . _to_apply : raise MigrationSessionError ( "Can't apply_all with migrations added to session" ) try : self . __apply ( run_all = True ) except : raise finally : self . __closed = True
Applies all Django model migrations at once recording the result .
49,946
def send_email_from_template ( to_email , from_email , subject , markdown_template = None , text_template = None , html_template = None , fail_silently = False , context = None , ** kwargs ) : return send_emails_from_template ( to_emails = [ to_email ] , from_email = from_email , subject = subject , markdown_template =...
Send an email from a template .
49,947
def send_emails_from_template ( to_emails , from_email , subject , markdown_template = None , text_template = None , html_template = None , fail_silently = False , context = None , attachments = None , ** kwargs ) : if not to_emails : return if context is None : context = { } if markdown_template : try : from markdown ...
Send many emails from single template . Each email address listed in the to_emails will receive an separate email .
49,948
def all_models ( self , alphabet : _Alphabet ) -> Set [ PLInterpretation ] : all_possible_interpretations = alphabet . powerset ( ) . symbols all_models = set ( ) for i in all_possible_interpretations : current_interpretation = PLInterpretation ( i ) if self . truth ( current_interpretation ) : all_models . add ( curre...
Find all the possible interpretations given a set of symbols
49,949
def save ( self , * args , ** kwargs ) : self . save_prep ( instance_or_instances = self ) return super ( AbstractTokenModel , self ) . save ( * args , ** kwargs )
Make sure token is added .
49,950
def save_prep ( cls , instance_or_instances ) : instances = make_obj_list ( instance_or_instances ) tokens = set ( cls . objects . get_available_tokens ( count = len ( instances ) , token_length = cls . token_length ) ) for instance in instances : if not instance . token : instance . token = tokens . pop ( ) super ( Ab...
Preprocess the object before the object is saved . This automatically gets called when the save method gets called .
49,951
def _popup ( self ) : res = ( ) for child in self . formulas : if type ( child ) == type ( self ) : superchilds = child . formulas res += superchilds else : res += ( child , ) return tuple ( res )
recursively find commutative binary operator among child formulas and pop up them at the same level
49,952
def get_content_object_url ( self ) : if ( self . content_object and hasattr ( self . content_object , 'get_absolute_url' ) ) : return self . content_object . get_absolute_url ( ) return None
Gets the absolute url for the content object .
49,953
def get_widget_css_class ( self , attrs ) : size_class = 'size-{0}' . format ( self . num_inputs ) if 'class' in attrs : attrs [ 'class' ] += ' {0}' . format ( size_class ) else : attrs [ 'class' ] = size_class
Gets the class for the widget .
49,954
def get_or_none ( self , prefetch_related = None , select_related = False , ** kwargs ) : try : if prefetch_related : query_set = self . prefetch_related ( * prefetch_related ) elif select_related == True : query_set = self . select_related ( ) elif isinstance ( select_related , ( list , tuple ) ) : query_set = self . ...
Gets a single object based on kwargs or None if one is not found .
49,955
def get_by_id_or_404 ( self , id , ** kwargs ) : obj = self . get_by_id ( id = id , ** kwargs ) if obj : return obj raise Http404
Gets by a instance instance r raises a 404 is one isn t found .
49,956
def bulk_create ( self , objs , * args , ** kwargs ) : if hasattr ( self . model , 'save_prep' ) : self . model . save_prep ( instance_or_instances = objs ) return super ( CommonManager , self ) . bulk_create ( objs = objs , * args , ** kwargs )
Insert many object at once .
49,957
def delete_by_ids ( self , ids ) : try : self . filter ( id__in = ids ) . delete ( ) return True except self . model . DoesNotExist : return False
Delete objects by ids .
49,958
def is_slug_available ( self , slug , ** kwargs ) : try : self . get ( slug = slug , ** kwargs ) return False except self . model . DoesNotExist : return True
Checks to see if a slug is available . If the slug is already being used this method returns False . Otherwise return True .
49,959
def get_next_slug ( self , slug , ** kwargs ) : original_slug = slug = slugify ( slug ) count = 0 while not self . is_slug_available ( slug = slug , ** kwargs ) : count += 1 slug = '{0}-{1}' . format ( original_slug , count ) return slug
Gets the next available slug .
49,960
def get_next_token ( self , length = 15 , ** kwargs ) : return self . get_available_tokens ( count = 1 , token_length = length , ** kwargs ) [ 0 ]
Gets the next available token .
49,961
def get_available_tokens ( self , count = 10 , token_length = 15 , ** kwargs ) : token_buffer = int ( math . ceil ( count * .05 ) ) if token_buffer < 5 : token_buffer = 5 available = set ( [ ] ) while True : tokens = [ random_alphanum ( length = token_length ) for t in range ( count + token_buffer ) ] db_tokens = self ...
Gets a list of available tokens .
49,962
def create_generic ( self , content_object = None , ** kwargs ) : if content_object : kwargs [ 'content_type' ] = ContentType . objects . get_for_model ( content_object ) kwargs [ 'object_id' ] = content_object . id return self . create ( ** kwargs )
Create a generic object .
49,963
def filter_generic ( self , content_object = None , ** kwargs ) : if content_object : kwargs [ 'content_type' ] = ContentType . objects . get_for_model ( content_object ) kwargs [ 'object_id' ] = content_object . id return self . filter ( ** kwargs )
Filter by a generic object .
49,964
def get_by_model ( self , model ) : content_type = ContentType . objects . get_for_model ( model ) return self . filter ( content_type = content_type )
Gets all object by a specific model .
49,965
def attr ( obj , attr ) : if not obj or not hasattr ( obj , attr ) : return '' return getattr ( obj , attr , '' )
Does the same thing as getattr .
49,966
def make_iterable ( obj ) : if not obj : return tuple ( ) if isinstance ( obj , ( list , tuple , set ) ) : return obj return ( obj , )
Make an object iterable .
49,967
def get_form_kwargs ( self ) : kwargs = super ( ApiFormView , self ) . get_form_kwargs ( ) kwargs [ 'data' ] = kwargs . get ( 'initial' ) return kwargs
Add the data to the form args so you can validate the form data on a get request .
49,968
def form_invalid ( self , form , context = None , ** kwargs ) : if not context : context = { } context [ 'errors' ] = form . errors return super ( ApiFormView , self ) . render_to_response ( context = context , status = 400 )
This will return the request with form errors as well as any additional context .
49,969
def is_valid_hex ( value ) : if not value : return False regex = re . compile ( HEX_COLOR_REGEX ) return bool ( regex . match ( value ) )
Boolean indicating of the value is a valid hex value .
49,970
def is_valid_rgb_color ( value ) : if not value : return False regex = re . compile ( RGB_COLOR_REGEX ) return bool ( regex . match ( value ) )
Checks whether the value is a valid rgb or rgba color string .
49,971
def validate_password_strength ( value ) : min_length = 7 if len ( value ) < min_length : raise ValidationError ( _ ( 'Password must be at least {0} characters ' 'long.' ) . format ( min_length ) ) if not any ( char . isdigit ( ) for char in value ) : raise ValidationError ( _ ( 'Password must contain at least 1 digit....
Validates that a password is as least 7 characters long and has at least 1 digit and 1 letter .
49,972
def random_alphanum ( length = 10 , lower_only = False ) : character_set = ALPHANUM_LOWER if lower_only else ALPHANUM sample_size = 5 chars = random . sample ( character_set , sample_size ) while len ( chars ) < length : chars += random . sample ( character_set , sample_size ) random . shuffle ( chars ) return '' . joi...
Gets a random alphanumeric value using both letters and numbers .
49,973
def generate_key ( low = 7 , high = 10 , lower_only = False ) : return random_alphanum ( length = randint ( 7 , 10 ) , lower_only = lower_only )
Gets a random alphanumeric key between low and high characters in length .
49,974
def get_absolute_url_link ( self , text = None , cls = None , icon_class = None , ** attrs ) : if text is None : text = self . get_link_text ( ) return build_link ( href = self . get_absolute_url ( ) , text = text , cls = cls , icon_class = icon_class , ** attrs )
Gets the html link for the object .
49,975
def get_edit_url_link ( self , text = None , cls = None , icon_class = None , ** attrs ) : if text is None : text = 'Edit' return build_link ( href = self . get_edit_url ( ) , text = text , cls = cls , icon_class = icon_class , ** attrs )
Gets the html edit link for the object .
49,976
def get_delete_url_link ( self , text = None , cls = None , icon_class = None , ** attrs ) : if text is None : text = 'Delete' return build_link ( href = self . get_delete_url ( ) , text = text , cls = cls , icon_class = icon_class , ** attrs )
Gets the html delete link for the object .
49,977
def expire_by_email ( self , email_address , ** kwargs ) : if not email_address : return None if isinstance ( email_address , ( set , list , tuple ) ) : email_address = [ e . strip ( ) for e in set ( email_address ) if e and e . strip ( ) ] if len ( email_address ) <= 0 : return None kwargs [ 'email_address__in' ] = em...
Expires tokens for an email address or email addresses .
49,978
def map_query_string ( self ) : if ( not self . query_key_mapper or self . request . method == 'POST' ) : return { } keys = list ( self . query_key_mapper . keys ( ) ) return { self . query_key_mapper . get ( k ) if k in keys else k : v . strip ( ) for k , v in self . request . GET . items ( ) }
Maps the GET query string params the the query_key_mapper dict and updates the request s GET QueryDict with the mapped keys .
49,979
async def call ( self , method , ** params ) : url = self . SLACK_RPC_PREFIX + method data = FormData ( ) data . add_fields ( MultiDict ( token = self . bot_token , charset = 'utf-8' , ** params ) ) response_body = await self . request ( method = 'POST' , url = url , data = data ) if 'warning' in response_body : logger...
Call an Slack Web API method
49,980
def rtm_handler ( self , ws_message ) : message = json . loads ( ws_message . data ) if 'reply_to' in message : reply_to = message [ 'reply_to' ] future = self . response_futures . pop ( reply_to , None ) if future is None : logger . error ( f'This should not happen, received reply to unknown message! {message}' ) retu...
Handle a message processing it internally if required . If it s a message that should go outside the bot this function will return True
49,981
def get_default_prefix ( self , instance = None ) : if instance is None and hasattr ( self , 'instance' ) : instance = self . instance if instance and instance . id is not None : instance_prefix = self . default_instance_prefix if instance_prefix is None : instance_prefix = self . __class__ . __name__ . lower ( ) + 'i-...
Gets the prefix for this form .
49,982
def formfield ( self , form_class = None , choices_form_class = None , ** kwargs ) : defaults = { 'form_class' : form_class or self . get_form_class ( ) } defaults . update ( kwargs ) return super ( ListField , self ) . formfield ( ** defaults )
Make the default formfield a CommaSeparatedListField .
49,983
def validate ( self , value , model_instance , ** kwargs ) : self . get_choices_form_class ( ) . validate ( value , model_instance , ** kwargs )
This follows the validate rules for choices_form_class field used .
49,984
def get_authorization ( self , ** kwargs ) : if self . authorization is not None : return self . authorization auth_class = self . get_authorization_class ( ) auth_user = self . get_authorization_user ( ) auth_kwargs = { 'token' : self . get_authorization_token ( ** kwargs ) } if auth_user and auth_user . is_authentica...
Gets the authorization object for the view .
49,985
def get_authorization_user ( self , ** kwargs ) : if self . authorization_user is not None : return self . authorization_user self . authorization_user = self . request . user return self . request . user
Gets the user the authorization object is for .
49,986
def safe_redirect ( next_url , default = None ) : if is_legit_next_url ( next_url ) : return redirect ( next_url ) if default : return redirect ( default ) return redirect ( '/' )
Makes sure it s a legit site to redirect to .
49,987
def replace_url_query_values ( url , replace_vals ) : if '?' not in url : return url parsed_url = urlparse ( url ) query = dict ( parse_qsl ( parsed_url . query ) ) query . update ( replace_vals ) return '{0}?{1}' . format ( url . split ( '?' ) [ 0 ] , urlencode ( query ) )
Replace querystring values in a url string .
49,988
def get_query_values_from_url ( url , keys = None ) : if not url or '?' not in url : return None parsed_url = urlparse ( url ) query = dict ( parse_qsl ( parsed_url . query ) ) if keys is None : return query if isinstance ( keys , string_types ) : return query . get ( keys ) return { k : query . get ( k ) for k in keys...
Gets query string values from a url .
49,989
def get_json_response ( self , content , ** kwargs ) : if isinstance ( content , dict ) : response_content = { k : deepcopy ( v ) for k , v in content . items ( ) if k not in ( 'form' , 'view' ) or k in ( 'form' , 'view' ) and not isinstance ( v , ( Form , View ) ) } else : response_content = content return HttpRespons...
Returns a json response object .
49,990
def find_atomics ( formula : Formula ) -> Set [ PLAtomic ] : f = formula res = set ( ) if isinstance ( formula , PLFormula ) : res = formula . find_atomics ( ) else : res . add ( f ) return res
Finds all the atomic formulas
49,991
def _transform_delta ( f : Formula , formula2AtomicFormula ) : t = type ( f ) if t == PLNot : return PLNot ( _transform_delta ( f , formula2AtomicFormula ) ) elif t == PLAnd or t == PLOr or t == PLImplies or t == PLEquivalence : return t ( [ _transform_delta ( subf , formula2AtomicFormula ) for subf in f . formulas ] )...
From a Propositional Formula to a Propositional Formula with non - propositional subformulas replaced with a freezed atomic formula .
49,992
def get_setting ( key , ** kwargs ) : has_default = 'default' in kwargs default_val = kwargs . get ( 'default' ) try : if has_default : return getattr ( settings , key , default_val ) else : return getattr ( settings , key ) except Exception as e : raise ImproperlyConfigured ( _ ( '"{0}" setting has not been properly s...
Gets a settings key or raises an improperly configured error .
49,993
def get_class_from_settings ( settings_key ) : cls_path = getattr ( settings , settings_key , None ) if not cls_path : raise NotImplementedError ( ) try : return get_model_from_settings ( settings_key = settings_key ) except : try : return get_class_from_settings_from_apps ( settings_key = settings_key ) except : retur...
Gets a class from a setting key . This will first check loaded models then look in installed apps then fallback to import from lib .
49,994
def get_model_from_settings ( settings_key ) : cls_path = getattr ( settings , settings_key , None ) if not cls_path : raise NotImplementedError ( ) try : app_label , model_name = cls_path . split ( '.' ) except ValueError : raise ImproperlyConfigured ( "{0} must be of the form " "'app_label.model_name'" . format ( set...
Return the django model from a settings key .
49,995
def get_class_from_settings_from_apps ( settings_key ) : cls_path = getattr ( settings , settings_key , None ) if not cls_path : raise NotImplementedError ( ) try : app_label = cls_path . split ( '.' ) [ - 2 ] model_name = cls_path . split ( '.' ) [ - 1 ] except ValueError : raise ImproperlyConfigured ( "{0} must be of...
Try and get a class from a settings path by lookin in installed apps .
49,996
def get_class_from_settings_full_path ( settings_key ) : cls_path = getattr ( settings , settings_key , None ) if not cls_path : raise NotImplementedError ( ) try : module_name , class_name = cls_path . rsplit ( '.' , 1 ) except ValueError : raise ImproperlyConfigured ( "{0} must be of the form " "'some.path.module.MyC...
Get a class from it s full path .
49,997
def get_function_from_settings ( settings_key ) : renderer_func_str = getattr ( settings , settings_key , None ) if not renderer_func_str : return None module_str , renderer_func_name = renderer_func_str . rsplit ( '.' , 1 ) try : mod = importlib . import_module ( module_str ) return getattr ( mod , renderer_func_name ...
Gets a function from the string path defined in a settings file .
49,998
def caller_locals ( ) : try : raise ValueError except ValueError : _ , _ , tb = sys . exc_info ( ) assert tb , "Can't get traceback, this shouldn't happen" caller_frame = tb . tb_frame . f_back . f_back return caller_frame . f_locals
Return the frame object for the caller s stack frame .
49,999
def make_repr ( inst , attrs ) : arg_str = ", " . join ( "%s=%r" % ( a , getattr ( inst , a ) ) for a in attrs if hasattr ( inst , a ) ) repr_str = "%s(%s)" % ( inst . __class__ . __name__ , arg_str ) return repr_str
Create a repr from an instance of a class