idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
14,600
def task ( func , * args , * * kwargs ) : # Note we must import here to avoid recursion issue with kombu entry points registration from celery import shared_task if 'serializer' not in kwargs : kwargs [ 'serializer' ] = DJANGO_CEREAL_PICKLE return shared_task ( func , * args , * * kwargs )
A task decorator that uses the django - cereal pickler as the default serializer .
88
19
14,601
def find_files ( directory , pattern , recursively = True ) : for root , dirs , files in os . walk ( directory ) : for basename in files : if fnmatch . fnmatch ( basename , pattern ) : yield root , basename if not recursively : break
Yield a list of files with their base directories recursively or not .
62
16
14,602
def validate ( self ) : if self . error : return False for v in self . validators : self . error = v ( self . value ) if self . error : return False return True
Run the form value through the validators and update the error field if needed
40
15
14,603
def form_group_classes ( self ) : classes = [ 'form-group' ] if self . style == styles . BOOTSTRAP_4 and self . form_type == formtype . HORIZONTAL : classes . append ( 'row' ) if self . error and self . style == styles . BOOTSTRAP_3 : classes . append ( 'has-error' ) if self . form_group_css_class : classes . append ( self . form_group_css_class ) return ' ' . join ( classes )
Full list of classes for the class attribute of the form group . Returned as a string with spaces separating each class ready for insertion into the class attribute .
116
31
14,604
def input_classes ( self ) : classes = [ self . base_input_css_class ] if self . css_class : classes . append ( self . css_class ) if self . style == styles . BOOTSTRAP_4 and self . error : classes . append ( 'is-invalid' ) return ' ' . join ( classes )
Full list of classes for the class attribute of the input returned as a string with spaces separating each class .
77
21
14,605
def render ( self ) : return Markup ( env . get_template ( 'form.html' ) . render ( form = self , render_open_tag = True , render_close_tag = True , render_before = True , render_sections = True , render_after = True , generate_csrf_token = None if self . disable_csrf else _csrf_generation_function ) )
Render the form and all sections to HTML
88
8
14,606
def render_before_sections ( self ) : return Markup ( env . get_template ( 'form.html' ) . render ( form = self , render_open_tag = True , render_close_tag = False , render_before = True , render_sections = False , render_after = False , generate_csrf_token = None if self . action else _csrf_generation_function ) )
Render the form up to the first section . This will open the form tag but not close it .
89
20
14,607
def read_form_data ( self ) : if self . processed_data : raise exceptions . AlreadyProcessed ( 'The data has already been processed for this form' ) if self . readonly : return if request . method == self . method : if self . method == 'POST' : data = request . form else : data = request . args if self . submitted_hidden_input_name in data : # The form has been submitted self . processed_data = True for field in self . all_fields : # We need to skip readonly fields if field . readonly : pass else : field . extract_value ( data ) # Validate the field if not field . validate ( ) : log . debug ( 'Validation error in field \'%s\': %s' % ( field . name , field . error ) ) self . has_errors = True
Attempt to read the form data from the request
182
9
14,608
def get_if_present ( self , name , default = None ) : if not self . processed_data : raise exceptions . FormNotProcessed ( 'The form data has not been processed yet' ) if name in self . field_dict : return self [ name ] return default
Returns the value for a field but if the field doesn t exist will return default instead
59
17
14,609
def disable_validation ( self , field_name ) : field = self . field_dict . get ( field_name ) if not field : raise exceptions . FieldNotFound ( 'Field not found: \'%s\' when trying to disable validation' % field_name ) field . validators = [ ]
Disable the validation rules for a field
65
7
14,610
def create_single_button_clone ( self , submit_text = 'Submit' , submit_css_class = 'btn-primary' , read_form_data = True , form_type = None ) : from . basicfields import BooleanCheckbox , HiddenField , SubmitButton fields = [ ] for field in self . all_fields : # If it's valid for the field to be missing, and the value of the field is empty, # then don't add it, otherwise create a hidden input if field . allow_missing : if field . value is None or field . value == '' : continue elif isinstance ( field , BooleanCheckbox ) and not field . value : continue # TODO: is this right? elif isinstance ( field , SubmitButton ) : continue # If we get here, we need to add this field to the list fields . append ( HiddenField ( field . name , field . value ) ) form = Form ( fields , action = self . action , method = self . method , submit_css_class = submit_css_class , submit_text = submit_text , read_form_data = read_form_data , disable_csrf = self . disable_csrf , readonly = False , form_type = form_type if form_type else self . form_type ) return form
This will create a copy of this form with all of inputs replaced with hidden inputs and with a single submit button . This allows you to easily create a button that will submit a post request which is identical to the current state of the form . You could then if required change some of the values in the hidden inputs .
283
63
14,611
def polish ( commit_indexes = None , urls = None ) : def decorator ( f ) : if commit_indexes : f . polish_commit_indexes = commit_indexes if urls : f . polish_urls = urls @ wraps ( f ) def wrappee ( * args , * * kwargs ) : return f ( * args , * * kwargs ) return wrappee return decorator
Apply certain behaviors to commits or URLs that need polishing before they are ready for screenshots
94
17
14,612
def timestamp_to_datetime ( cls , time_stamp , localized = True ) : ret = datetime . datetime . utcfromtimestamp ( time_stamp ) if localized : ret = localize ( ret , pytz . utc ) return ret
Converts a UTC timestamp to a datetime . datetime .
58
13
14,613
def _imm_default_init ( self , * args , * * kwargs ) : for ( k , v ) in six . iteritems ( { k : v for dct in ( args + ( kwargs , ) ) for ( k , v ) in dct } ) : setattr ( self , k , v )
An immutable s defalt initialization function is to accept any number of dictionaries followed by any number of keyword args and to turn them all into the parameters of the immutable that is being created .
71
38
14,614
def _imm_init_getattribute ( self , name ) : values = _imm_value_data ( self ) params = _imm_param_data ( self ) if name in values : _imm_init_to_trans ( self ) return getattr ( self , name ) elif name in params : dd = object . __getattribute__ ( self , '__dict__' ) if name in dd : return dd [ name ] else : raise RuntimeError ( 'Required immutable parameter %s requested before set' % name ) else : # if they request a required param before it's set, raise an exception; that's fine return object . __getattribute__ ( self , name )
During the initial transient state getattribute works on params ; as soon as a non - param is requested all checks are forced and the getattr switches to standard transient form .
145
34
14,615
def _imm_getattribute ( self , name ) : if _imm_is_init ( self ) : return _imm_init_getattribute ( self , name ) else : dd = object . __getattribute__ ( self , '__dict__' ) if name == '__dict__' : return dd curval = dd . get ( name , dd ) if curval is not dd : return dd [ name ] values = _imm_value_data ( self ) if name not in values : return object . __getattribute__ ( self , name ) ( args , memfn , _ ) = values [ name ] value = memfn ( * [ getattr ( self , arg ) for arg in args ] ) dd [ name ] = value # if this is a const, it may have checks to run if name in _imm_const_data ( self ) : # #TODO # Note that there's a race condition that eventually needs to be handled here: # If dd[name] is set then a check fails, there may have been something that read the # improper value in the meantime try : _imm_check ( self , [ name ] ) except : del dd [ name ] raise # if those pass, then we're fine return value
An immutable s getattribute calculates lazy values when not yet cached in the object then adds them as attributes .
263
21
14,616
def _imm_init_setattr ( self , name , value ) : params = _imm_param_data ( self ) if name in params : tx_fn = params [ name ] [ 1 ] value = value if tx_fn is None else tx_fn ( value ) # Set the value object . __getattribute__ ( self , '__dict__' ) [ name ] = value # No checks are run, as we're in initialization mode... else : raise TypeError ( 'Attempt to change non-parameter \'%s\' of initializing immutable' % name )
An immutable s initial setattr allows only param s to be set and does not run checks on the new parameters until a full parameter - set has been specified at which point it runs all checks and switches over to a normal setattr and getattr method .
122
51
14,617
def _imm_trans_setattr ( self , name , value ) : params = _imm_param_data ( self ) dd = object . __getattribute__ ( self , '__dict__' ) if name in params : ( _ , tx_fn , arg_lists , check_fns , deps ) = params [ name ] value = value if tx_fn is None else tx_fn ( value ) old_deps = { } orig_value = dd [ name ] # clear the dependencies before we run the checks; save them in case the checks fail and we # go back to how things were... for dep in deps : if dep in dd : old_deps [ dep ] = dd [ dep ] del dd [ dep ] try : dd [ name ] = value for ( args , check_fn ) in zip ( arg_lists , check_fns ) : if not check_fn ( * [ getattr ( self , arg ) for arg in args ] ) : raise RuntimeError ( ( 'Changing value of immutable attribute \'%s\'' + ' caused validation failure: %s' ) % ( name , ( args , check_fn ) ) ) # if all the checks ran, we don't return the old deps; they are now invalid old_deps = None finally : if old_deps : # in this case, something didn't check-out, so we return the old deps and let the # exception ride; we also return the original value of the edited param for ( dep , val ) in six . iteritems ( old_deps ) : dd [ dep ] = val dd [ name ] = orig_value else : raise TypeError ( 'Attempt to change non-parameter member \'%s\' of transient immutable' % name )
An immutable s transient setattr allows params to be set and runs checks as they are .
377
18
14,618
def _imm_setattr ( self , name , value ) : if _imm_is_persist ( self ) : raise TypeError ( 'Attempt to change parameter \'%s\' of non-transient immutable' % name ) elif _imm_is_trans ( self ) : return _imm_trans_setattr ( self , name , value ) else : return _imm_init_setattr ( self , name , value )
A persistent immutable s setattr simply does not allow attributes to be set .
93
15
14,619
def _imm_trans_delattr ( self , name ) : ( params , values ) = ( _imm_param_data ( self ) , _imm_value_data ( self ) ) if name in params : dflt = params [ name ] [ 0 ] if dflt is None : raise TypeError ( 'Attempt to reset required parameter \'%s\' of immutable' % name ) setattr ( self , name , dflt [ 0 ] ) elif name in values : dd = object . __getattribute__ ( self , '__dict__' ) if name in dd : del dd [ name ] if name in _imm_const_data ( self ) : _imm_check ( imm , [ name ] ) else : raise TypeError ( 'Cannot delete non-value non-param attribute \'%s\' from immutable' % name )
A transient immutable s delattr allows the object s value - caches to be invalidated ; a var that is deleted returns to its default - value in a transient immutable otherwise raises an exception .
179
38
14,620
def _imm_delattr ( self , name ) : if _imm_is_persist ( self ) : values = _imm_value_data ( self ) if name in values : dd = object . __getattribute__ ( self , '__dict__' ) if name in dd : del dd [ name ] if name in _imm_const_data ( self ) : _imm_check ( imm , [ name ] ) else : raise TypeError ( 'Attempt to reset parameter \'%s\' of non-transient immutable' % name ) else : return _imm_trans_delattr ( self , name )
A persistent immutable s delattr allows the object s value - caches to be invalidated otherwise raises an exception .
131
22
14,621
def _imm_dir ( self ) : dir0 = set ( dir ( self . __class__ ) ) dir0 . update ( self . __dict__ . keys ( ) ) dir0 . update ( six . iterkeys ( _imm_value_data ( self ) ) ) return sorted ( list ( dir0 ) )
An immutable object s dir function should list not only its attributes but also its un - cached lazy values .
68
21
14,622
def _imm_repr ( self ) : return ( type ( self ) . __name__ + ( '(' if _imm_is_persist ( self ) else '*(' ) + ', ' . join ( [ k + '=' + str ( v ) for ( k , v ) in six . iteritems ( imm_params ( self ) ) ] ) + ')' )
The default representation function for an immutable object .
81
9
14,623
def _imm_new ( cls ) : imm = object . __new__ ( cls ) # Note that right now imm has a normal setattr method; # Give any parameter that has one a default value params = cls . _pimms_immutable_data_ [ 'params' ] for ( p , dat ) in six . iteritems ( params ) : dat = dat [ 0 ] if dat : object . __setattr__ ( imm , p , dat [ 0 ] ) # Clear any values; they are not allowed yet _imm_clear ( imm ) # Note that we are initializing... dd = object . __getattribute__ ( imm , '__dict__' ) dd [ '_pimms_immutable_is_init' ] = True # That should do it! return imm
All immutable new classes use a hack to make sure the post - init cleanup occurs .
172
17
14,624
def _scan_file ( filename , sentinel , source_type = 'import' ) : filename = os . path . abspath ( filename ) real_filename = os . path . realpath ( filename ) if os . path . getsize ( filename ) <= max_file_size : if real_filename not in sentinel and os . path . isfile ( filename ) : sentinel . add ( real_filename ) basename = os . path . basename ( filename ) scope , imports = ast_scan_file ( filename ) if scope is not None and imports is not None : for imp in imports : yield ( source_type , imp . module , None ) if 'INSTALLED_APPS' in scope and basename == 'settings.py' : log . info ( 'Found Django settings: %s' , filename ) for item in django . handle_django_settings ( filename ) : yield item else : log . warn ( 'Could not scan imports from: %s' , filename ) else : log . warn ( 'File size too large: %s' , filename )
Generator that performs the actual scanning of files .
232
10
14,625
def _scan_directory ( directory , sentinel , depth = 0 ) : directory = os . path . abspath ( directory ) real_directory = os . path . realpath ( directory ) if depth < max_directory_depth and real_directory not in sentinel and os . path . isdir ( directory ) : sentinel . add ( real_directory ) for item in os . listdir ( directory ) : if item in ( '.' , '..' ) : # I'm not sure if this is even needed any more. continue p = os . path . abspath ( os . path . join ( directory , item ) ) if ( os . path . isdir ( p ) and _dir_ignore . search ( p ) ) or ( os . path . isfile ( p ) and _ext_ignore . search ( p ) ) : continue yield p
Basically os . listdir with some filtering .
181
9
14,626
def _get_project_conf ( ) : config_settings = { } project_root = find_vcs_root ( "." ) if project_root is None : return config_settings for conf_dir in PROJECT_CONF_DIRS : conf_dir = conf_dir . lstrip ( "./" ) joined_dir = os . path . join ( project_root , conf_dir ) if conf_dir else project_root joined_glob = os . path . join ( joined_dir , PROJECT_CONF ) conf_files = glob . glob ( joined_glob ) # config files found, not trying other directories if conf_files : break else : conf_files = [ ] for conf_file in conf_files : try : with io . open ( conf_file , encoding = "utf-8" ) as input_file : loaded_settings = yaml . safe_load ( input_file ) except EnvironmentError : logger . warning ( "Failed to load config from %s" , conf_file ) else : logger . info ( "Config loaded from %s" , conf_file ) config_settings . update ( loaded_settings ) return config_settings
Loads configuration from project config file .
256
8
14,627
def get_config ( config_file = None , config_values = None , load_project_conf = True ) : config_values = config_values or { } config_settings = { } default_conf = _get_default_conf ( ) user_conf = _get_user_conf ( config_file ) if config_file else { } # load project configuration only when user configuration was not specified project_conf = { } if user_conf or not load_project_conf else _get_project_conf ( ) if not ( user_conf or project_conf or config_values ) : if load_project_conf : raise Dump2PolarionException ( "Failed to find configuration file for the project " "and no configuration file or values passed." ) raise Dump2PolarionException ( "No configuration file or values passed." ) # merge configuration config_settings . update ( default_conf ) config_settings . update ( user_conf ) config_settings . update ( project_conf ) config_settings . update ( config_values ) _populate_urls ( config_settings ) _set_legacy_project_id ( config_settings ) _set_legacy_custom_fields ( config_settings ) _check_config ( config_settings ) return config_settings
Loads config file and returns its content .
279
9
14,628
def verify_predictions ( predictions ) : # Check that it contains only zeros and ones predictions = np . array ( predictions , copy = False ) if not np . array_equal ( predictions , predictions . astype ( bool ) ) : raise ValueError ( "predictions contains invalid values. " + "The only permitted values are 0 or 1." ) if predictions . ndim == 1 : predictions = predictions [ : , np . newaxis ] return predictions
Ensures that predictions is stored as a numpy array and checks that all values are either 0 or 1 .
95
23
14,629
def verify_scores ( scores ) : scores = np . array ( scores , copy = False ) if np . any ( ~ np . isfinite ( scores ) ) : raise ValueError ( "scores contains invalid values. " + "Please check that all values are finite." ) if scores . ndim == 1 : scores = scores [ : , np . newaxis ] return scores
Ensures that scores is stored as a numpy array and checks that all values are finite .
81
20
14,630
def verify_consistency ( predictions , scores , proba , opt_class ) : if predictions . shape != scores . shape : raise ValueError ( "predictions and scores arrays have inconsistent " + "dimensions." ) n_class = scores . shape [ 1 ] if scores . ndim > 1 else 1 # If proba not given, default to False for all classifiers if proba is None : proba = np . repeat ( False , n_class ) # If opt_class is not given, default to True for all classifiers if opt_class is None : opt_class = np . repeat ( True , n_class ) # Convert to numpy arrays if necessary proba = np . array ( proba , dtype = bool , ndmin = 1 ) opt_class = np . array ( opt_class , dtype = bool , ndmin = 1 ) if np . sum ( opt_class ) < 1 : raise ValueError ( "opt_class should contain at least one True value." ) if predictions . shape [ 1 ] != len ( proba ) : raise ValueError ( "mismatch in shape of proba and predictions." ) if predictions . shape [ 1 ] != len ( opt_class ) : raise ValueError ( "mismatch in shape of opt_class and predictions." ) for m in range ( n_class ) : if ( np . any ( np . logical_or ( scores [ : , m ] < 0 , scores [ : , m ] > 1 ) ) and proba [ m ] ) : warnings . warn ( "scores fall outside the [0,1] interval for " + "classifier {}. Setting proba[m]=False." . format ( m ) ) proba [ m ] = False return proba , opt_class
Verifies that all arrays have consistent dimensions . Also verifies that the scores are consistent with proba .
382
21
14,631
def verify_identifiers ( identifiers , n_items ) : if identifiers is None : return identifiers identifiers = np . array ( identifiers , copy = False ) # Check length for consistency if len ( identifiers ) != n_items : raise ValueError ( "identifiers has inconsistent dimension." ) # Check that identifiers are unique if len ( np . unique ( identifiers ) ) != n_items : raise ValueError ( "identifiers contains duplicate values." ) return identifiers
Ensure that identifiers has a compatible length and that its elements are unique
94
14
14,632
def scores_to_probs ( scores , proba , eps = 0.01 ) : if np . any ( ~ proba ) : # Need to convert some of the scores into probabilities probs = copy . deepcopy ( scores ) n_class = len ( proba ) for m in range ( n_class ) : if not proba [ m ] : #TODO: incorporate threshold (currently assuming zero) # find most extreme absolute score max_extreme_score = max ( np . abs ( np . min ( scores [ : , m ] ) ) , np . abs ( np . max ( scores [ : , m ] ) ) ) k = np . log ( ( 1 - eps ) / eps ) / max_extreme_score # scale factor self . _probs [ : , m ] = expit ( k * self . scores [ : , m ] ) return probs else : return scores
Transforms scores to probabilities by applying the logistic function
195
11
14,633
def fire_metric ( metric_name , metric_value ) : metric_value = float ( metric_value ) metric = { metric_name : metric_value } metric_client . fire_metrics ( * * metric ) return "Fired metric <{}> with value <{}>" . format ( metric_name , metric_value )
Fires a metric using the MetricsApiClient
75
11
14,634
def fire_failed_msisdn_lookup ( self , to_identity ) : payload = { "to_identity" : to_identity } hooks = Hook . objects . filter ( event = "identity.no_address" ) for hook in hooks : hook . deliver_hook ( None , payload_override = { "hook" : hook . dict ( ) , "data" : payload } )
Fires a webhook in the event of a None to_addr .
90
15
14,635
def dump_data ( self , filename , queryset ) : with gzip . open ( filename , "wb" ) as f : for outbound in queryset . iterator ( ) : data = OutboundArchiveSerializer ( outbound ) . data data = JSONRenderer ( ) . render ( data ) f . write ( data ) f . write ( "\n" . encode ( "utf-8" ) )
Serializes the queryset into a newline separated JSON format and places it into a gzipped file
91
22
14,636
def create_archived_outbound ( self , date , filename ) : with open ( filename , "rb" ) as f : f = File ( f ) ArchivedOutbounds . objects . create ( date = date , archive = f )
Creates the required ArchivedOutbound entry with the file specified at filename
52
15
14,637
def manages ( self , account ) : account_slug = str ( account ) for organization in self . request . session . get ( 'roles' , { } ) . get ( 'manager' , [ ] ) : if account_slug == organization [ 'slug' ] : return True return False
Returns True if the request . user is a manager for account . account will be converted to a string and compared to an organization slug .
65
27
14,638
def get_queryset ( self ) : kwargs = { } if self . ends_at : kwargs . update ( { '%s__lt' % self . date_field : self . ends_at } ) return super ( BeforeMixin , self ) . get_queryset ( ) . filter ( * * kwargs )
Implements before date filtering on date_field
76
10
14,639
def get_queryset ( self ) : kwargs = { } if self . start_at : kwargs . update ( { '%s__gte' % self . date_field : self . start_at } ) return super ( DateRangeMixin , self ) . get_queryset ( ) . filter ( * * kwargs )
Implements date range filtering on created_at
78
10
14,640
def create ( self , fname , lname , group , type , group_api ) : self . __username ( fname , lname ) self . client . add ( self . __distinguished_name ( type , fname = fname , lname = lname ) , API . __object_class ( ) , self . __ldap_attr ( fname , lname , type , group , group_api ) )
Create an LDAP User .
92
6
14,641
def show ( self , username ) : filter = [ '(objectclass=posixAccount)' , "(uid={})" . format ( username ) ] return self . client . search ( filter )
Return a specific user s info in LDIF format .
40
11
14,642
def find ( self , username ) : filter = [ '(uid={})' . format ( username ) ] results = self . client . search ( filter ) if len ( results ) < 1 : raise ldap_tools . exceptions . NoUserFound ( 'User ({}) not found' . format ( username ) ) return # pragma: no cover elif len ( results ) > 1 : raise ldap_tools . exceptions . TooManyResults ( 'Multiple users found. Please narrow your search.' ) return # pragma: no cover else : return results
Find user with given username .
117
6
14,643
def __username ( self , fname , lname ) : # pragma: no cover self . username = '.' . join ( [ i . lower ( ) for i in [ fname , lname ] ] )
Convert first name + last name into first . last style username .
46
14
14,644
def __distinguished_name ( self , type , fname = None , lname = None , username = None ) : # pragma: no cover if username is None : uid = "uid={}" . format ( self . username ) else : uid = "uid={}" . format ( username ) dn_list = [ uid , "ou={}" . format ( self . __organizational_unit ( type ) ) , self . client . basedn , ] return ',' . join ( dn_list )
Assemble the DN of the user .
112
8
14,645
def __ldap_attr ( self , fname , lname , type , group , group_api ) : # pragma: no cover return { 'uid' : str ( self . username ) . encode ( ) , 'cn' : ' ' . join ( [ fname , lname ] ) . encode ( ) , 'sn' : str ( lname ) . encode ( ) , 'givenname' : str ( fname ) . encode ( ) , 'homedirectory' : os . path . join ( os . path . sep , 'home' , self . username ) . encode ( ) , 'loginshell' : os . path . join ( os . path . sep , 'bin' , 'bash' ) . encode ( ) , 'mail' : '@' . join ( [ self . username , self . client . mail_domain ] ) . encode ( ) , 'uidnumber' : self . __uidnumber ( type ) , 'gidnumber' : API . __gidnumber ( group , group_api ) , 'userpassword' : str ( '{SSHA}' + API . __create_password ( ) . decode ( ) ) . encode ( ) , }
User LDAP attributes .
257
5
14,646
def __create_password ( ) : # pragma: no cover salt = b64encode ( API . __generate_string ( 32 ) ) password = b64encode ( API . __generate_string ( 64 ) ) return b64encode ( sha1 ( password + salt ) . digest ( ) )
Create a password for the user .
69
7
14,647
def __generate_string ( length ) : # pragma: no cover return '' . join ( SystemRandom ( ) . choice ( string . ascii_letters + string . digits ) for x in range ( length ) ) . encode ( )
Generate a string for password creation .
52
8
14,648
def create ( config , name , group , type ) : if type not in ( 'user' , 'service' ) : raise click . BadOptionUsage ( "--type must be 'user' or 'service'" ) client = Client ( ) client . prepare_connection ( ) user_api = API ( client ) group_api = GroupApi ( client ) user_api . create ( name [ 0 ] , name [ 1 ] , group , type , group_api )
Create an LDAP user .
100
6
14,649
def index ( config ) : client = Client ( ) client . prepare_connection ( ) user_api = API ( client ) CLI . show_user ( user_api . index ( ) )
Display user info in LDIF format .
40
8
14,650
def show ( config , username ) : client = Client ( ) client . prepare_connection ( ) user_api = API ( client ) CLI . show_user ( user_api . show ( username ) )
Display a specific user .
43
5
14,651
async def set_discovery_enabled ( self ) : endpoint = '/setup/bluetooth/discovery' data = { "enable_discovery" : True } url = API . format ( ip = self . _ipaddress , endpoint = endpoint ) try : async with async_timeout . timeout ( 5 , loop = self . _loop ) : response = await self . _session . post ( url , headers = HEADERS , data = json . dumps ( data ) ) _LOGGER . debug ( response . status ) except ( asyncio . TimeoutError , aiohttp . ClientError , socket . gaierror ) as error : _LOGGER . error ( 'Error connecting to %s - %s' , self . _ipaddress , error )
Enable bluetooth discoverablility .
161
7
14,652
async def scan_for_devices_multi_run ( self , runs = 2 ) : run = 1 master = { } while run < runs + 1 : await self . scan_for_devices ( ) await self . get_scan_result ( ) if master is None : for device in self . _devices : mac = device [ 'mac_address' ] master [ mac ] = { } master [ mac ] [ 'rssi' ] = device [ 'rssi' ] master [ mac ] [ 'device_class' ] = device [ 'device_class' ] master [ mac ] [ 'name' ] = device [ 'name' ] master [ mac ] [ 'device_type' ] = device [ 'device_type' ] master [ mac ] [ 'count' ] = 1 else : for device in self . _devices : mac = device [ 'mac_address' ] if master . get ( mac , False ) : master [ mac ] [ 'rssi' ] = device [ 'rssi' ] master [ mac ] [ 'count' ] = str ( 1 + 1 ) else : master [ mac ] = { } master [ mac ] [ 'rssi' ] = device [ 'rssi' ] master [ mac ] [ 'device_class' ] = device [ 'device_class' ] master [ mac ] [ 'name' ] = device [ 'name' ] master [ mac ] [ 'device_type' ] = device [ 'device_type' ] master [ mac ] [ 'count' ] = 1 run = run + 1 result = [ ] for device in master : if int ( master [ device ] [ 'count' ] ) > 1 : result . append ( master [ device ] ) self . _devices = result
Scan for devices multiple times .
372
6
14,653
def contract_from_file ( fname ) : f = open ( fname ) j = f . read ( ) f . close ( ) return Contract ( json . loads ( j ) )
Loads a Barrister IDL JSON from the given file and returns a Contract class
40
17
14,654
def get_prop ( self , key , default_val = None ) : if self . props . has_key ( key ) : return self . props [ key ] else : return default_val
Returns a property set on the context .
41
8
14,655
def set_error ( self , code , msg , data = None ) : self . error = err_response ( self . request [ "id" ] , code , msg , data )
Set an error on this request which will prevent request execution . Should only be called from pre hook methods . If called from a post hook this operation will be ignored .
39
33
14,656
def add_handler ( self , iface_name , handler ) : if self . contract . has_interface ( iface_name ) : self . handlers [ iface_name ] = handler else : raise RpcException ( ERR_INVALID_REQ , "Unknown interface: '%s'" , iface_name )
Associates the given handler with the interface name . If the interface does not exist in the Contract an RpcException is raised .
72
27
14,657
def set_filters ( self , filters ) : if filters == None or isinstance ( filters , ( tuple , list ) ) : self . filters = filters else : self . filters = [ filters ]
Sets the filters for the server .
42
8
14,658
def call ( self , req , props = None ) : resp = None if self . log . isEnabledFor ( logging . DEBUG ) : self . log . debug ( "Request: %s" % str ( req ) ) if isinstance ( req , list ) : if len ( req ) < 1 : resp = err_response ( None , ERR_INVALID_REQ , "Invalid Request. Empty batch." ) else : resp = [ ] for r in req : resp . append ( self . _call_and_format ( r , props ) ) else : resp = self . _call_and_format ( req , props ) if self . log . isEnabledFor ( logging . DEBUG ) : self . log . debug ( "Response: %s" % str ( resp ) ) return resp
Executes a Barrister request and returns a response . If the request is a list then the response will also be a list . If the request is an empty list a RpcException is raised .
168
40
14,659
def _call ( self , context ) : req = context . request if not req . has_key ( "method" ) : raise RpcException ( ERR_INVALID_REQ , "Invalid Request. No 'method'." ) method = req [ "method" ] if method == "barrister-idl" : return self . contract . idl_parsed iface_name , func_name = unpack_method ( method ) if self . handlers . has_key ( iface_name ) : iface_impl = self . handlers [ iface_name ] func = getattr ( iface_impl , func_name ) if func : if req . has_key ( "params" ) : params = req [ "params" ] else : params = [ ] if self . validate_req : self . contract . validate_request ( iface_name , func_name , params ) if hasattr ( iface_impl , "barrister_pre" ) : pre_hook = getattr ( iface_impl , "barrister_pre" ) pre_hook ( context , params ) if params : result = func ( * params ) else : result = func ( ) if self . validate_resp : self . contract . validate_response ( iface_name , func_name , result ) return result else : msg = "Method '%s' not found" % ( method ) raise RpcException ( ERR_METHOD_NOT_FOUND , msg ) else : msg = "No implementation of '%s' found" % ( iface_name ) raise RpcException ( ERR_METHOD_NOT_FOUND , msg )
Executes a single request against a handler . If the req . method == barrister - idl the Contract IDL JSON structure is returned . Otherwise the method is resolved to a handler based on the interface name and the appropriate function is called on the handler .
359
52
14,660
def request ( self , req ) : data = json . dumps ( req ) req = urllib2 . Request ( self . url , data , self . headers ) f = self . opener . open ( req ) resp = f . read ( ) f . close ( ) return json . loads ( resp )
Makes a request against the server and returns the deserialized result .
64
15
14,661
def call ( self , iface_name , func_name , params ) : req = self . to_request ( iface_name , func_name , params ) if self . log . isEnabledFor ( logging . DEBUG ) : self . log . debug ( "Request: %s" % str ( req ) ) resp = self . transport . request ( req ) if self . log . isEnabledFor ( logging . DEBUG ) : self . log . debug ( "Response: %s" % str ( resp ) ) return self . to_result ( iface_name , func_name , resp )
Makes a single RPC request and returns the result .
126
11
14,662
def to_request ( self , iface_name , func_name , params ) : if self . validate_req : self . contract . validate_request ( iface_name , func_name , params ) method = "%s.%s" % ( iface_name , func_name ) reqid = self . id_gen ( ) return { "jsonrpc" : "2.0" , "id" : reqid , "method" : method , "params" : params }
Converts the arguments to a JSON - RPC request dict . The id field is populated using the id_gen function passed to the Client constructor .
107
29
14,663
def to_result ( self , iface_name , func_name , resp ) : if resp . has_key ( "error" ) : e = resp [ "error" ] data = None if e . has_key ( "data" ) : data = e [ "data" ] raise RpcException ( e [ "code" ] , e [ "message" ] , data ) result = resp [ "result" ] if self . validate_resp : self . contract . validate_response ( iface_name , func_name , result ) return result
Takes a JSON - RPC response and checks for an error slot . If it exists a RpcException is raised . If no error slot exists the result slot is returned .
119
35
14,664
def validate_request ( self , iface_name , func_name , params ) : self . interface ( iface_name ) . function ( func_name ) . validate_params ( params )
Validates that the given params match the expected length and types for this interface and function .
42
18
14,665
def validate_response ( self , iface_name , func_name , resp ) : self . interface ( iface_name ) . function ( func_name ) . validate_response ( resp )
Validates that the response matches the return type for the function
42
12
14,666
def get ( self , name ) : if self . structs . has_key ( name ) : return self . structs [ name ] elif self . enums . has_key ( name ) : return self . enums [ name ] elif self . interfaces . has_key ( name ) : return self . interfaces [ name ] else : raise RpcException ( ERR_INVALID_PARAMS , "Unknown entity: '%s'" % name )
Returns the struct enum or interface with the given name or raises RpcException if no elements match that name .
99
22
14,667
def struct ( self , struct_name ) : if self . structs . has_key ( struct_name ) : return self . structs [ struct_name ] else : raise RpcException ( ERR_INVALID_PARAMS , "Unknown struct: '%s'" , struct_name )
Returns the struct with the given name or raises RpcException if no struct matches
65
16
14,668
def interface ( self , iface_name ) : if self . has_interface ( iface_name ) : return self . interfaces [ iface_name ] else : raise RpcException ( ERR_INVALID_PARAMS , "Unknown interface: '%s'" , iface_name )
Returns the interface with the given name or raises RpcException if no interface matches
65
16
14,669
def validate ( self , expected_type , is_array , val ) : if val == None : if expected_type . optional : return True , None else : return False , "Value cannot be null" elif is_array : if not isinstance ( val , list ) : return self . _type_err ( val , "list" ) else : for v in val : ok , msg = self . validate ( expected_type , False , v ) if not ok : return ok , msg elif expected_type . type == "int" : if not isinstance ( val , ( long , int ) ) : return self . _type_err ( val , "int" ) elif expected_type . type == "float" : if not isinstance ( val , ( float , int , long ) ) : return self . _type_err ( val , "float" ) elif expected_type . type == "bool" : if not isinstance ( val , bool ) : return self . _type_err ( val , "bool" ) elif expected_type . type == "string" : if not isinstance ( val , ( str , unicode ) ) : return self . _type_err ( val , "string" ) else : return self . get ( expected_type . type ) . validate ( val ) return True , None
Validates that the expected type matches the value
285
9
14,670
def function ( self , func_name ) : if self . functions . has_key ( func_name ) : return self . functions [ func_name ] else : raise RpcException ( ERR_METHOD_NOT_FOUND , "%s: Unknown function: '%s'" , self . name , func_name )
Returns the Function instance associated with the given func_name or raises a RpcException if no function matches .
69
22
14,671
def validate ( self , val ) : if val in self . values : return True , None else : return False , "'%s' is not in enum: %s" % ( val , str ( self . values ) )
Validates that the val is in the list of values for this Enum .
47
16
14,672
def field ( self , name ) : if self . fields . has_key ( name ) : return self . fields [ name ] elif self . extends : if not self . parent : self . parent = self . contract . struct ( self . extends ) return self . parent . field ( name ) else : return None
Returns the field on this struct with the given name . Will try to find this name on all ancestors if this struct extends another .
66
26
14,673
def validate ( self , val ) : if type ( val ) is not dict : return False , "%s is not a dict" % ( str ( val ) ) for k , v in val . items ( ) : field = self . field ( k ) if field : ok , msg = self . contract . validate ( field , field . is_array , v ) if not ok : return False , "field '%s': %s" % ( field . name , msg ) else : return False , "field '%s' not found in struct %s" % ( k , self . name ) all_fields = self . get_all_fields ( [ ] ) for field in all_fields : if not val . has_key ( field . name ) and not field . optional : return False , "field '%s' missing from: %s" % ( field . name , str ( val ) ) return True , None
Validates that the val matches the expected fields for this struct . val must be a dict and must contain only fields represented by this struct and its ancestors .
196
31
14,674
def get_all_fields ( self , arr ) : for k , v in self . fields . items ( ) : arr . append ( v ) if self . extends : parent = self . contract . get ( self . extends ) if parent : return parent . get_all_fields ( arr ) return arr
Returns a list containing this struct s fields and all the fields of its ancestors . Used during validation .
64
20
14,675
def validate_params ( self , params ) : plen = 0 if params != None : plen = len ( params ) if len ( self . params ) != plen : vals = ( self . full_name , len ( self . params ) , plen ) msg = "Function '%s' expects %d param(s). %d given." % vals raise RpcException ( ERR_INVALID_PARAMS , msg ) if params != None : i = 0 for p in self . params : self . _validate_param ( p , params [ i ] ) i += 1
Validates params against expected types for this function . Raises RpcException if the params are invalid .
129
21
14,676
def validate_response ( self , resp ) : ok , msg = self . contract . validate ( self . returns , self . returns . is_array , resp ) if not ok : vals = ( self . full_name , str ( resp ) , msg ) msg = "Function '%s' invalid response: '%s'. %s" % vals raise RpcException ( ERR_INVALID_RESP , msg )
Validates resp against expected return type for this function . Raises RpcException if the response is invalid .
93
22
14,677
def submit ( xml_root , submit_config , session , dry_run = None , * * kwargs ) : properties . xunit_fill_testrun_id ( xml_root , kwargs . get ( "testrun_id" ) ) if dry_run is not None : properties . set_dry_run ( xml_root , dry_run ) xml_input = utils . etree_to_string ( xml_root ) logger . info ( "Submitting data to %s" , submit_config . submit_target ) files = { "file" : ( "results.xml" , xml_input ) } try : response = session . post ( submit_config . submit_target , files = files ) # pylint: disable=broad-except except Exception as err : logger . error ( err ) response = None return SubmitResponse ( response )
Submits data to the Polarion Importer .
188
10
14,678
def submit_and_verify ( xml_str = None , xml_file = None , xml_root = None , config = None , session = None , dry_run = None , * * kwargs ) : try : config = config or configuration . get_config ( ) xml_root = _get_xml_root ( xml_root , xml_str , xml_file ) submit_config = SubmitConfig ( xml_root , config , * * kwargs ) session = session or utils . get_session ( submit_config . credentials , config ) submit_response = submit ( xml_root , submit_config , session , dry_run = dry_run , * * kwargs ) except Dump2PolarionException as err : logger . error ( err ) return None valid_response = submit_response . validate_response ( ) if not valid_response or kwargs . get ( "no_verify" ) : return submit_response . response response = verify_submit ( session , submit_config . queue_url , submit_config . log_url , submit_response . job_ids , timeout = kwargs . get ( "verify_timeout" ) , log_file = kwargs . get ( "log_file" ) , ) return response
Submits data to the Polarion Importer and checks that it was imported .
277
16
14,679
def get_job_ids ( self ) : if not self . parsed_response : return None try : job_ids = self . parsed_response [ "files" ] [ "results.xml" ] [ "job-ids" ] except KeyError : return None if not job_ids or job_ids == [ 0 ] : return None return job_ids
Returns job IDs of the import .
76
7
14,680
def validate_response ( self ) : if self . response is None : logger . error ( "Failed to submit" ) return False if not self . response : logger . error ( "HTTP status %d: failed to submit to %s" , self . response . status_code , self . response . url , ) return False if not self . parsed_response : logger . error ( "Submit to %s failed, invalid response received" , self . response . url ) return False error_message = self . get_error_message ( ) if error_message : logger . error ( "Submit to %s failed with error" , self . response . url ) logger . debug ( "Error message: %s" , error_message ) return False if not self . job_ids : logger . error ( "Submit to %s failed to get job id" , self . response . url ) return False logger . info ( "Results received by the Importer (HTTP status %d)" , self . response . status_code ) logger . info ( "Job IDs: %s" , self . job_ids ) return True
Checks that the response is valid and import succeeded .
235
11
14,681
def get_targets ( self ) : if self . xml_root . tag == "testcases" : self . submit_target = self . config . get ( "testcase_taget" ) self . queue_url = self . config . get ( "testcase_queue" ) self . log_url = self . config . get ( "testcase_log" ) elif self . xml_root . tag == "testsuites" : self . submit_target = self . config . get ( "xunit_target" ) self . queue_url = self . config . get ( "xunit_queue" ) self . log_url = self . config . get ( "xunit_log" ) elif self . xml_root . tag == "requirements" : self . submit_target = self . config . get ( "requirement_target" ) self . queue_url = self . config . get ( "requirement_queue" ) self . log_url = self . config . get ( "requirement_log" ) else : raise Dump2PolarionException ( "Failed to submit to Polarion - submit target not found" )
Sets targets .
253
4
14,682
def get_credentials ( self , * * kwargs ) : login = ( kwargs . get ( "user" ) or os . environ . get ( "POLARION_USERNAME" ) or self . config . get ( "username" ) ) pwd = ( kwargs . get ( "password" ) or os . environ . get ( "POLARION_PASSWORD" ) or self . config . get ( "password" ) ) if not all ( [ login , pwd ] ) : raise Dump2PolarionException ( "Failed to submit to Polarion - missing credentials" ) self . credentials = ( login , pwd )
Sets credentails .
146
6
14,683
def e_164 ( msisdn : str ) -> str : # Phonenumbers library requires the + to identify the country, so we add it if it # does not already exist number = phonenumbers . parse ( "+{}" . format ( msisdn . lstrip ( "+" ) ) , None ) return phonenumbers . format_number ( number , phonenumbers . PhoneNumberFormat . E164 )
Returns the msisdn in E . 164 international format .
88
12
14,684
def loadFile ( self , filePath ) : self . _filePath = filePath if self . _proc . state ( ) != QProcess . Running : self . _kill ( ) self . _run ( self . _filePath ) else : self . _execute ( "pausing_keep_force pt_step 1" ) self . _execute ( "get_property pause" ) self . _execute ( "loadfile \"%s\"" % self . _filePath ) self . _data . reset ( ) self . videoDataChanged . emit ( False ) self . _changePlayingState ( True )
Loads a file
129
4
14,685
def play ( self ) : if self . _proc . state ( ) == QProcess . Running : if self . isPlaying is False : self . _execute ( "pause" ) self . _changePlayingState ( True ) elif self . _filePath is not None : self . _kill ( ) self . _run ( self . _filePath ) self . _changePlayingState ( True )
Starts a playback
84
4
14,686
def fourier ( x , N ) : term = 0. for n in range ( 1 , N , 2 ) : term += ( 1. / n ) * math . sin ( n * math . pi * x / L ) return ( 4. / ( math . pi ) ) * term
Fourier approximation with N terms
61
7
14,687
def parse_enum ( enum ) : docs = enum [ 'comment' ] code = '<span class="k">enum</span> <span class="gs">%s</span> {\n' % enum [ 'name' ] for v in enum [ "values" ] : if v [ 'comment' ] : for line in v [ 'comment' ] . split ( "\n" ) : code += ' <span class="c1">// %s</span>\n' % line code += ' <span class="nv">%s</span>\n' % v [ 'value' ] code += "}" return to_section ( docs , code )
Returns a docco section for the given enum .
143
10
14,688
def parse_struct ( s ) : docs = s [ 'comment' ] code = '<span class="k">struct</span> <span class="gs">%s</span>' % s [ 'name' ] if s [ 'extends' ] : code += ' extends <span class="gs">%s</span>' % s [ 'extends' ] code += ' {\n' namelen = 0 typelen = 0 for v in s [ "fields" ] : tlen = len ( format_type ( v , includeOptional = False ) ) if len ( v [ 'name' ] ) > namelen : namelen = len ( v [ 'name' ] ) if tlen > typelen : typelen = tlen namelen += 1 typelen += 1 formatstr = ' <span class="nv">%s</span><span class="kt">%s %s</span>\n' i = 0 for v in s [ "fields" ] : if v . has_key ( 'comment' ) and v [ 'comment' ] : if i > 0 : code += "\n" for line in v [ 'comment' ] . split ( "\n" ) : code += ' <span class="c1">// %s</span>\n' % line opt = "" if v . has_key ( 'optional' ) and v [ 'optional' ] == True : opt = " [optional]" code += formatstr % ( string . ljust ( v [ 'name' ] , namelen ) , string . ljust ( format_type ( v , includeOptional = False ) , typelen ) , opt ) i += 1 code += "}" return to_section ( docs , code )
Returns a docco section for the given struct .
379
10
14,689
def parse_interface ( iface ) : sections = [ ] docs = iface [ 'comment' ] code = '<span class="k">interface</span> <span class="gs">%s</span> {\n' % iface [ 'name' ] for v in iface [ "functions" ] : func_code = ' <span class="nf">%s</span>(' % v [ 'name' ] i = 0 for p in v [ "params" ] : if i == 0 : i = 1 else : func_code += ", " func_code += '<span class="na">%s</span> <span class="kt">%s</span>' % ( p [ 'name' ] , format_type ( p ) ) func_code += ') <span class="kt">%s</span>\n' % format_type ( v [ 'returns' ] ) if v . has_key ( 'comment' ) and v [ 'comment' ] : if code : sections . append ( to_section ( docs , code ) ) docs = v [ 'comment' ] code = func_code else : code += func_code code += "}" sections . append ( to_section ( docs , code ) ) return sections
Returns a docco section for the given interface .
274
10
14,690
def to_sections ( idl_parsed ) : sections = [ ] for entity in idl_parsed : if entity [ "type" ] == "comment" : sections . append ( to_section ( entity [ "value" ] , "" ) ) elif entity [ "type" ] == "enum" : sections . append ( parse_enum ( entity ) ) elif entity [ "type" ] == "struct" : sections . append ( parse_struct ( entity ) ) elif entity [ "type" ] == "interface" : sections . extend ( parse_interface ( entity ) ) return sections
Iterates through elements in idl_parsed list and returns a list of section dicts . Currently elements of type comment enum struct and interface are processed .
131
33
14,691
def sub_location ( self , nbr ) : assert nbr > - 1 , "Sub location number must be greater or equal to 0!" assert nbr < self . nbr_of_sub_locations ( ) - 1 , "Sub location number must be lower than %d!" % self . nbr_of_sub_locations ( ) - 1 return self . _locations_list [ nbr ]
Return a given sub location 0 - based .
89
9
14,692
def get_locations_list ( self , lower_bound = 0 , upper_bound = None ) : real_upper_bound = upper_bound if upper_bound is None : real_upper_bound = self . nbr_of_sub_locations ( ) try : return self . _locations_list [ lower_bound : real_upper_bound ] except : return list ( )
Return the internal location list .
85
6
14,693
def get_args ( args , kwargs , arg_names ) : n_args = len ( arg_names ) if len ( args ) + len ( kwargs ) > n_args : raise MoultScannerError ( 'Too many arguments supplied. Expected: {}' . format ( n_args ) ) out_args = { } for i , a in enumerate ( args ) : out_args [ arg_names [ i ] ] = a for a in arg_names : if a not in out_args : out_args [ a ] = None out_args . update ( kwargs ) return out_args
Get arguments as a dict .
136
6
14,694
def ast_scan_file ( filename , re_fallback = True ) : try : with io . open ( filename , 'rb' ) as fp : try : root = ast . parse ( fp . read ( ) , filename = filename ) except ( SyntaxError , IndentationError ) : if re_fallback : log . debug ( 'Falling back to regex scanner' ) return _ast_scan_file_re ( filename ) else : log . error ( 'Could not parse file: %s' , filename ) log . info ( 'Exception:' , exc_info = True ) return None , None log . debug ( 'Starting AST Scan: %s' , filename ) ast_visitor . reset ( filename ) ast_visitor . visit ( root ) log . debug ( 'Project path: %s' , ast_visitor . import_root ) return ast_visitor . scope , ast_visitor . imports except IOError : log . warn ( 'Could not open file: %s' , filename ) return None , None
Scans a file for imports using AST .
224
9
14,695
def dump ( d , fmt = 'json' , stream = None ) : if fmt == 'json' : return _dump_json ( d , stream = stream ) elif fmt == 'yaml' : return yaml . dump ( d , stream ) elif fmt == 'lha' : s = _dump_lha ( d ) if stream is None : return s else : return stream . write ( s )
Serialize structured data into a stream in JSON YAML or LHA format . If stream is None return the produced string instead .
89
27
14,696
def inline_for_model ( model , variants = [ ] , inline_args = { } ) : if not isinstance ( model , ModelBase ) : raise ValueError ( "inline_for_model requires it's argument to be a Django Model" ) d = dict ( model = model ) if variants : d [ 'variants' ] = variants if inline_args : d [ 'args' ] = inline_args class_name = "%sInline" % model . _meta . module_name . capitalize ( ) return type ( class_name , ( ModelInline , ) , d )
A shortcut function to produce ModelInlines for django models
127
12
14,697
def initialize_mpi ( mpi = False ) : if mpi : import mpi4py . MPI comm = mpi4py . MPI . COMM_WORLD rank = comm . Get_rank ( ) size = comm . Get_size ( ) else : comm = None rank = 0 size = 1 return { "comm" : comm , "rank" : rank , "size" : size , "mode" : mpi }
initialize mpi settings
94
5
14,698
def create_ports ( port , mpi , rank ) : if port == "random" or port is None : # ports will be filled in using random binding ports = { } else : port = int ( port ) ports = { "REQ" : port + 0 , "PUSH" : port + 1 , "SUB" : port + 2 } # if we want to communicate with separate domains # we have to setup a socket for each of them if mpi == 'all' : # use a socket for each rank rank for port in ports : ports [ port ] += ( rank * 3 ) return ports
create a list of ports for the current rank
128
9
14,699
def import_from_string ( full_class_name ) : s = full_class_name . split ( '.' ) class_name = s [ - 1 ] module_name = full_class_name [ : - len ( class_name ) - 1 ] module = importlib . import_module ( module_name ) # the class, it's common to spell with k as class is reserved klass = getattr ( module , class_name ) return klass
return a class based on it s full class name
100
10