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_messages in sample_errors . items ( ) : LOG . error ( f"{sample_id} -> {sub_field}: {', '.join(sub_messages)}" ) else : LOG . error ( f"{field}: {', '.join(messages)}" ) raise ConfigError ( 'invalid config input' , errors = errors )
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 in data_copy [ 'samples' ] : sample_data [ 'mother' ] = sample_data . get ( 'mother' ) or '0' sample_data [ 'father' ] = sample_data . get ( 'father' ) or '0' if sample_data [ 'analysis_type' ] == 'wgs' and sample_data . get ( 'capture_kit' ) is None : sample_data [ 'capture_kit' ] = DEFAULT_CAPTURE_KIT return data_copy
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 out_path
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 , src_atr_name = src_atr_name , dest_processors = dest_processors , dest_atr_name = dest_atr_name , transform_function = transform_function )
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 ( self , k , new_value ) not_used = set ( args . keys ( ) ) . difference ( set ( self . PARAMETERS . keys ( ) ) ) not_given = set ( self . PARAMETERS . keys ( ) ) . difference ( set ( args . keys ( ) ) ) return not_used , not_given
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 ( sr_ or sa_ )
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 . debug ( "Subscribing to topics %s" , str ( self . _topics ) ) self . _subscriber = Subscriber ( self . _addresses , self . _topics , translate = self . _translate ) if self . _addr_listener : self . _addr_listener = _AddressListener ( self . _subscriber , self . _services , nameserver = self . _nameserver ) for service in self . _services : addresses = _get_addr_loop ( service , self . _timeout ) if not addresses : LOGGER . warning ( "Can't get any address for %s" , service ) continue else : LOGGER . debug ( "Got address for %s: %s" , str ( service ) , str ( addresses ) ) for addr in addresses : self . _subscriber . add ( addr ) return self . _subscriber
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 "where" in sqlQuery : sqlQuery = sqlQuery . replace ( "where" , "where %(thisInt)s=%(thisInt)s and " % locals ( ) ) transientsMetadataList = readquery ( log = self . log , sqlQuery = sqlQuery , dbConn = self . transientsDbConn , quiet = False ) self . log . debug ( 'completed the ``_get_transient_metadata_from_database_list`` method' ) return transientsMetadataList
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 = now - td refreshLimit = refreshLimit . strftime ( "%Y-%m-%d %H:%M:%S" ) raList = [ ] raList [ : ] = [ c [ 0 ] for c in coordinateList ] decList = [ ] decList [ : ] = [ c [ 1 ] for c in coordinateList ] cs = conesearch ( log = self . log , dbConn = self . cataloguesDbConn , tableName = "tcs_helper_ned_query_history" , columns = "*" , ra = raList , dec = decList , radiusArcsec = radius , separations = True , distinct = True , sqlWhere = "dateQueried > '%(refreshLimit)s'" % locals ( ) , closest = False ) matchIndies , matches = cs . search ( ) curatedMatchIndices = [ ] curatedMatches = [ ] for i , m in zip ( matchIndies , matches . list ) : match = False row = m row [ "separationArcsec" ] = row [ "cmSepArcsec" ] raStream = row [ "raDeg" ] decStream = row [ "decDeg" ] radiusStream = row [ "arcsecRadius" ] dateStream = row [ "dateQueried" ] angularSeparation = row [ "separationArcsec" ] if angularSeparation + self . settings [ "first pass ned search radius arcec" ] < radiusStream : curatedMatchIndices . append ( i ) curatedMatches . append ( m ) for i , v in enumerate ( coordinateList ) : if i not in curatedMatchIndices : updatedCoordinateList . append ( v ) self . log . debug ( 'completed the ``_remove_previous_ned_queries`` method' ) return updatedCoordinateList
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 , dbSettings = self . settings [ "database settings" ] [ "static catalogues" ] ) . connect ( ) self . allClassifications = [ ] cm = transient_catalogue_crossmatch ( log = self . log , dbConn = dbConn , transients = transientsMetadataList , settings = self . settings , colMaps = colMaps ) crossmatches = cm . match ( ) self . log . debug ( 'completed the ``_crossmatch_transients_against_catalogues`` method' ) return crossmatches
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 else 'XXXXXX' return f"{lane}_{date_str}_{flowcell}_{sample}_{index}_{read}.fastq.gz"
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 . name_file ( lane = fastq_data [ 'lane' ] , flowcell = fastq_data [ 'flowcell' ] , sample = sample , read = fastq_data [ 'read' ] , undetermined = fastq_data [ 'undetermined' ] , ) dest_path = root_dir / fastq_name if not dest_path . exists ( ) : log . info ( f"linking: {fastq_path} -> {dest_path}" ) dest_path . symlink_to ( fastq_path ) else : log . debug ( f"destination path already exists: {dest_path}" )
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 . split ( "." ) [ 0 ] ) < 224 ) ) : raise IOError ( "Invalid multicast address." ) else : group = mcgroup ttl = struct . pack ( 'b' , TTL_LOCALNET ) sock . setsockopt ( IPPROTO_IP , IP_MULTICAST_TTL , ttl ) return sock , group
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_MULTICAST_LOOP , 1 ) sock . bind ( ( '' , port ) ) if group : group = gethostbyname ( group ) bytes_ = [ int ( b ) for b in group . split ( "." ) ] grpaddr = 0 for byte in bytes_ : grpaddr = ( grpaddr << 8 ) | byte ifaddr = INADDR_ANY mreq = struct . pack ( '!LL' , grpaddr , ifaddr ) sock . setsockopt ( IPPROTO_IP , IP_ADD_MEMBERSHIP , mreq ) return sock , group or '<broadcast>'
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' ] , 'started_at' : sampleinfo_data [ 'date' ] , 'version' : sampleinfo_data [ 'version' ] , 'out_dir' : config_data [ 'out_dir' ] , 'config_path' : config_data [ 'config_path' ] , 'type' : cls . _get_analysis_type ( analysis_types ) , } sacct_data , last_job_end = cls . _parse_sacct ( sacct_jobs , jobs_count = jobs ) run_data . update ( sacct_data ) run_data [ 'status' ] = cls . get_status ( sampleinfo_data [ 'is_finished' ] , len ( run_data [ 'failed_jobs' ] ) ) if run_data [ 'status' ] == 'completed' : run_data [ 'completed_at' ] = last_job_end return run_data
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' : jobs_count , 'completed_jobs' : len ( completed_jobs ) , 'progress' : ( len ( completed_jobs ) / jobs_count ) if jobs_count else None , 'failed_jobs' : [ { 'slurm_id' : job [ 'id' ] , 'started_at' : job [ 'start' ] , 'elapsed' : job [ 'elapsed' ] , 'status' : job [ 'state' ] . lower ( ) , 'name' : job [ 'step' ] , 'context' : job [ 'context' ] , } for job in failed_jobs ] } return data , last_job_end
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_jobs = [ self . store . Job ( ** job ) for job in run_data [ 'failed_jobs' ] ] del run_data [ 'failed_jobs' ] new_run = self . store . Analysis ( ** run_data ) new_run . failed_jobs = new_failed_jobs return new_run
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_options = compiled . execution_options . union ( connection . _execution_options ) self . result_column_struct = ( compiled . _result_columns , compiled . _ordered_columns , compiled . _textual_ordered_columns ) self . unicode_statement = util . text_type ( compiled ) if not dialect . supports_unicode_statements : self . statement = self . unicode_statement . encode ( self . dialect . encoding ) else : self . statement = self . unicode_statement self . isinsert = compiled . isinsert self . isupdate = compiled . isupdate self . isdelete = compiled . isdelete self . is_text = compiled . isplaintext if not parameters : self . compiled_parameters = [ compiled . construct_params ( ) ] else : self . compiled_parameters = [ compiled . construct_params ( m , _group_number = grp ) for grp , m in enumerate ( parameters ) ] self . executemany = len ( parameters ) > 1 self . cursor = self . create_cursor ( ) if self . isinsert or self . isupdate or self . isdelete : self . is_crud = True self . _is_explicit_returning = bool ( compiled . statement . _returning ) self . _is_implicit_returning = bool ( compiled . returning and not compiled . statement . _returning ) if self . compiled . insert_prefetch or self . compiled . update_prefetch : if self . executemany : self . _process_executemany_defaults ( ) else : self . _process_executesingle_defaults ( ) processors = compiled . _bind_processors parameters = [ ] if dialect . positional : for compiled_params in self . compiled_parameters : param = [ ] for key in self . compiled . positiontup : if key in processors : param . append ( processors [ key ] ( compiled_params [ key ] ) ) else : param . append ( compiled_params [ key ] ) parameters . append ( dialect . execute_sequence_format ( param ) ) else : encode = not dialect . supports_unicode_statements for compiled_params in self . compiled_parameters : if encode : param = dict ( ( dialect . _encoder ( key ) [ 0 ] , processors [ key ] ( compiled_params [ key ] ) if key in processors else compiled_params [ key ] ) for key in compiled_params ) else : param = dict ( ( key , processors [ key ] ( compiled_params [ key ] ) if key in processors else compiled_params [ key ] ) for key in compiled_params ) parameters . append ( param ) self . parameters = dialect . execute_sequence_format ( parameters ) self . statement = compiled return self
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 AttributeError : model = queryset . _meta . concrete_model queryset = model . objects . filter ( pk = queryset . pk ) return func ( self , request , queryset ) return decorated_function
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_actions , self . changelist_actions ) : actions [ action ] = getattr ( self , action ) return [ url ( r'^(?P<pk>.+)/actions/(?P<tool>\w+)/$' , self . admin_site . admin_view ( ChangeActionView . as_view ( model = self . model , actions = actions , back = 'admin:%s_change' % base_url_name , current_app = self . admin_site . name , ) ) , name = model_actions_url_name ) , url ( r'^actions/(?P<tool>\w+)/$' , self . admin_site . admin_view ( ChangeListActionView . as_view ( model = self . model , actions = actions , back = 'admin:%s_changelist' % base_url_name , current_app = self . admin_site . name , ) ) , name = model_actions_url_name ) , ]
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_attrs = { } for k , v in dict ( default_attrs , ** attrs ) . items ( ) : if k in default_attrs : standard_attrs [ k ] = v else : custom_attrs [ k ] = v return standard_attrs , custom_attrs
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 in ( 'img' , 'input' , 'hr' , 'br' ) : return mark_safe ( '<{tag_content} />' . format ( tag_content = tag_content ) ) icon = '<i class="{0}"></i> ' . format ( icon_class ) if icon_class else '' if not text : text = '' elif not isinstance ( text , SafeText ) : text = escape ( text ) return mark_safe ( '<{tag_content}>{icon}{text}</{tag}>' . format ( tag_content = tag_content , icon = icon , tag = tag , text = text ) )
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 ) raw = deepcopy ( raw ) for step in raw : step [ 'output' ] = BlockStyle ( step [ 'output' ] ) step [ 'traceback' ] = BlockStyle ( step [ 'traceback' ] ) return yaml . dump ( raw , Dumper = SessionDumper )
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_recents else str ( most_recents [ app ] ) ] for app in apps ] return most_recents
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 , currents
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 ] , } ) elif not run_all : raise ValueError ( 'Either a migration must be provided or "run_all" must be True' ) start = self . _timer ( ) try : call_command ( "migrate" , ** migrate_kwargs ) except Exception : trace = '' . join ( traceback . format_exception ( * sys . exc_info ( ) ) ) finally : end = self . _timer ( ) successes , failure = self . _parse_migrate_output ( out . getvalue ( ) ) self . _migration_state . append ( { 'database' : self . _database_name , 'migration' : 'all' if run_all else ( migration [ 0 ] , migration [ 1 ] ) , 'duration' : end - start , 'output' : _remove_escape_characters ( out . getvalue ( ) ) , 'succeeded_migrations' : successes , 'failed_migration' : failure , 'traceback' : trace , 'succeeded' : failure is None and trace is None , } ) if failure is not None : raise CommandError ( "Migration failed for app '{}' - migration '{}'.\n" . format ( * failure ) ) elif trace is not None : raise CommandError ( "Migrations failed unexpectedly. See self.state['traceback'] for details." )
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 = markdown_template , text_template = text_template , html_template = html_template , fail_silently = fail_silently , context = context , ** kwargs )
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 import markdown except ImportError : raise ImportError ( 'The application is attempting to send an email by using the ' '"markdown" library, but markdown is not installed. Please ' 'install it. See: ' 'http://pythonhosted.org/Markdown/install.html' ) base_html_template = getattr ( settings , 'CORE_BASE_HTML_EMAIL_TEMPLATE' , 'django_core/mail/base_email.html' ) text_content = render_to_string ( markdown_template , context ) context [ 'email_content' ] = markdown ( text_content ) html_content = render_to_string ( base_html_template , context ) else : text_content = render_to_string ( text_template , context ) html_content = render_to_string ( html_template , context ) emails = [ ] for email_address in to_emails : email = EmailMultiAlternatives ( subject = subject , body = text_content , from_email = from_email , to = [ email_address ] , alternatives = [ ( html_content , 'text/html' ) ] ) if attachments : email . mixed_subtype = 'related' for attachment in attachments : email . attach ( attachment ) emails . append ( email ) connection = mail . get_connection ( ) connection . open ( ) connection . send_messages ( emails ) connection . close ( )
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 ( current_interpretation ) self . _all_models = all_models return all_models
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 ( AbstractTokenModel , cls ) . save_prep ( instance_or_instances = instances )
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 . select_related ( * select_related ) else : query_set = self return query_set . get ( ** kwargs ) except self . model . DoesNotExist : return None
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 . filter ( token__in = tokens ) . values_list ( 'token' , flat = True ) available . update ( set ( tokens ) . difference ( db_tokens ) ) if len ( available ) >= count : return list ( available ) [ : count ]
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.' ) ) if not any ( char . isalpha ( ) for char in value ) : raise ValidationError ( _ ( 'Password must contain at least 1 letter.' ) )
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 '' . join ( chars [ : length ] )
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' ] = email_address else : kwargs [ 'email_address' ] = email_address if 'reason' not in kwargs and self . model . reason_default : kwargs [ 'reason' ] = self . model . reason_default if 'reason' in kwargs and kwargs . get ( 'reason' ) is None : del kwargs [ 'reason' ] self . filter ( ** kwargs ) . update ( expires = datetime ( 1970 , 1 , 1 ) )
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 . warning ( f'Warnings received from API call {method}: {response_body["warning"]}' ) if 'ok' not in response_body : logger . error ( f'No ok marker in slack API call {method} {params} => {response_body}' ) raise SlackCallException ( 'There is no ok marker, ... strange' , method = method ) if not response_body [ 'ok' ] : logger . error ( f'Slack API call failed {method} {params} => {response_body}' ) raise SlackCallException ( f'No OK response returned' , method = method ) return response_body
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}' ) return None future . set_result ( message ) return None if 'type' not in message : logger . error ( f'No idea what this could be {message}' ) return message_type = message [ 'type' ] if hasattr ( self , f'handle_{message_type}' ) : function = getattr ( self , f'handle_{message_type}' ) return function ( message ) if message_type in self . SLACK_RTM_EVENTS : logger . debug ( f'Unhandled {message_type}. {message}' ) else : logger . warning ( f'Unknown {message_type}. {message}' ) return message
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-' return '{0}{1}' . format ( instance_prefix , instance . id ) if self . default_new_prefix is not None : return self . default_new_prefix return self . __class__ . __name__ . lower ( ) + 'new-'
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_authenticated ( ) : auth_kwargs [ 'created_user' ] = self . get_authorization_user ( ) self . authorization = auth_class . objects . get_by_token_or_404 ( ** auth_kwargs ) return self . authorization
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 HttpResponse ( content = json . dumps ( response_content ) , content_type = 'application/json; charset=utf-8' , ** kwargs )
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 ] ) elif t == PLTrue or t == PLFalse : return f else : return formula2AtomicFormula [ f ]
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 set. {1}' ) . format ( key , e ) )
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 : return get_class_from_settings_full_path ( settings_key )
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 ( settings_key ) ) model = apps . get_model ( app_label , model_name ) if model is None : raise ImproperlyConfigured ( "{0} refers to model '%s' that has not " "been installed" . format ( settings_key ) ) return model
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 the form " "'app_label.model_name'" . format ( settings_key ) ) app = apps . get_app_config ( app_label ) . models_module if not app : raise ImproperlyConfigured ( "{0} setting refers to an app that has not " "been installed" . format ( settings_key ) ) return getattr ( app , model_name )
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.MyClass'" . format ( settings_key ) ) manager_module = importlib . import_module ( module_name ) if not manager_module : raise ImproperlyConfigured ( "{0} refers to a module that has not been " "installed" . format ( settings_key ) ) return getattr ( manager_module , class_name )
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 ) except Exception : return None
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