idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
4,100
def select_data ( db_file , slab = None , facet = None ) : con = sql . connect ( db_file ) cur = con . cursor ( ) if slab and facet : select_command = 'select chemical_composition, facet, reactants, products, reaction_energy ' 'from reaction where facet=' + str ( facet ) + ' and chemical_composition LIKE "%' + slab + '...
Gathers relevant data from SQL database generated by CATHUB .
184
14
4,101
def file_to_df ( file_name ) : filename , file_extension = os . path . splitext ( file_name ) if file_extension == '.csv' : df = pd . read_csv ( file_name , sep = ',' , header = 0 ) . iloc [ : , 1 : ] elif file_extension == '.tsv' : df = pd . read_csv ( file_name , sep = '\t' , header = 0 ) . iloc [ : , 1 : ] else : pr...
Read in file and return pandas data_frame .
141
11
4,102
def db_to_df ( db_file , slabs = None , facet = None ) : systems = [ ] data = [ ] if slabs : for slab in slabs : data_tmp = select_data ( db_file , slab = slab , facet = facet ) data . append ( data_tmp ) subsystem = [ tup [ 0 ] for i , tup in enumerate ( data_tmp ) ] systems . append ( list ( set ( subsystem ) ) [ 0 ]...
Transforms database to data frame .
397
7
4,103
def unique_reactions ( df ) : reaction_list = [ ] for idx , entry in enumerate ( df [ 'reactants' ] ) : reaction = [ ] for x in entry : reaction . append ( x ) reaction . append ( '-->' ) for y in df [ 'products' ] [ idx ] : reaction . append ( y ) reaction_list . append ( reaction ) string_list = [ str ( reaction ) fo...
Identifies unique elementary reactions in data frame .
142
9
4,104
def get_helmholtz_energy ( self , temperature , electronic_energy = 0 , verbose = False ) : thermo_object = HarmonicThermo ( vib_energies = self . vib_energies , potentialenergy = electronic_energy ) self . helmholtz_energy = thermo_object . get_helmholtz_energy ( temperature = temperature , verbose = verbose ) return ...
Returns the Helmholtz energy of an adsorbed molecule .
97
13
4,105
def get_vib_energies ( self ) : vibs = self . molecule_dict [ self . name ] [ 'vibrations' ] vibs = np . array ( vibs ) * cm2ev return ( vibs )
Returns a list of vibration in energy units eV .
52
11
4,106
def set_intermediates ( self , intermediates , betas = None , transition_states = None ) : self . intermediates = intermediates self . betas = betas self . transition_states = transition_states if self . corrections is None : self . net_corrections = [ 0.0 for _ in intermediates ] if not self . betas : self . betas = [...
Sets up intermediates and specifies whether it s an electrochemical step . Either provide individual contributions or net contributions . If both are given only the net contributions are used .
217
34
4,107
def debugger ( ) : sdb = _current [ 0 ] if sdb is None or not sdb . active : sdb = _current [ 0 ] = Sdb ( ) return sdb
Return the current debugger instance or create if none .
41
10
4,108
def global_matches ( self , text ) : matches = [ ] n = len ( text ) for word in self . namespace : if word [ : n ] == text and word != "__builtins__" : matches . append ( word ) return matches
Compute matches when text is a simple name . Return a list of all keywords built - in functions and names currently defined in self . namespace that match .
54
31
4,109
def dec2str ( n ) : s = hex ( int ( n ) ) [ 2 : ] . rstrip ( 'L' ) if len ( s ) % 2 != 0 : s = '0' + s return hex2str ( s )
decimal number to string .
53
6
4,110
def bin2str ( b ) : ret = [ ] for pos in range ( 0 , len ( b ) , 8 ) : ret . append ( chr ( int ( b [ pos : pos + 8 ] , 2 ) ) ) return '' . join ( ret )
Binary to string .
56
5
4,111
def n2s ( n ) : s = hex ( n ) [ 2 : ] . rstrip ( "L" ) if len ( s ) % 2 != 0 : s = "0" + s return s . decode ( "hex" )
Number to string .
52
4
4,112
def s2b ( s ) : ret = [ ] for c in s : ret . append ( bin ( ord ( c ) ) [ 2 : ] . zfill ( 8 ) ) return "" . join ( ret )
String to binary .
46
4
4,113
def long_to_bytes ( n , blocksize = 0 ) : # after much testing, this algorithm was deemed to be the fastest s = b'' n = int ( n ) pack = struct . pack while n > 0 : s = pack ( '>I' , n & 0xffffffff ) + s n = n >> 32 # strip off leading zeros for i in range ( len ( s ) ) : if s [ i ] != b'\000' [ 0 ] : break else : # on...
Convert an integer to a byte string .
199
9
4,114
def make_request ( endpoint , * * kwargs ) : data = kwargs . get ( 'json' , [ ] ) package = kwargs . get ( 'package' , None ) method = kwargs . get ( 'method' , 'GET' ) function = getattr ( requests , method . lower ( ) ) try : if package : response = function ( endpoint , data = data , files = { 'file' : package } ) e...
Send a request to server .
144
6
4,115
def get_napps ( self ) : endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'napps' , '' ) res = self . make_request ( endpoint ) if res . status_code != 200 : msg = 'Error getting NApps from server (%s) - %s' LOG . error ( msg , res . status_code , res . reason ) sys . exit ( 1 ) return json . lo...
Get all NApps from the server .
122
8
4,116
def get_napp ( self , username , name ) : endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'napps' , username , name , '' ) res = self . make_request ( endpoint ) if res . status_code == 404 : # We need to know if NApp is not found return None if res . status_code != 200 : msg = 'Error getting %...
Return napp metadata or None if not found .
143
10
4,117
def reload_napps ( self , napps = None ) : if napps is None : napps = [ ] api = self . _config . get ( 'kytos' , 'api' ) endpoint = os . path . join ( api , 'api' , 'kytos' , 'core' , 'reload' , 'all' ) response = self . make_request ( endpoint ) for napp in napps : api = self . _config . get ( 'kytos' , 'api' ) endpoi...
Reload a specific NApp or all Napps .
203
11
4,118
def upload_napp ( self , metadata , package ) : endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'napps' , '' ) metadata [ 'token' ] = self . _config . get ( 'auth' , 'token' ) request = self . make_request ( endpoint , json = metadata , package = package , method = "POST" ) if request . status_...
Upload the napp from the current directory to the napps server .
210
14
4,119
def register ( self , user_dict ) : endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'users' , '' ) res = self . make_request ( endpoint , method = 'POST' , json = user_dict ) return res . content . decode ( 'utf-8' )
Send an user_dict to NApps server using POST request .
76
13
4,120
def on_message ( self , message ) : if message . address != self . _address : return if isinstance ( message , velbus . ChannelNamePart1Message ) or isinstance ( message , velbus . ChannelNamePart1Message2 ) : self . _process_channel_name_message ( 1 , message ) elif isinstance ( message , velbus . ChannelNamePart2Mess...
Process received message
203
3
4,121
def load ( self , callback ) : if callback is None : def callb ( ) : """No-op""" pass callback = callb if len ( self . _loaded_callbacks ) == 0 : self . _request_module_status ( ) self . _request_channel_name ( ) else : print ( "++++++++++++++++++++++++++++++++++" ) self . _loaded_callbacks . append ( callback ) self ....
Retrieve names of channels
91
5
4,122
def _name_messages_complete ( self ) : for channel in range ( 1 , self . number_of_channels ( ) + 1 ) : try : for name_index in range ( 1 , 4 ) : if not isinstance ( self . _name_data [ channel ] [ name_index ] , str ) : return False except Exception : return False return True
Check if all name messages have been received
79
8
4,123
def as_json ( self ) : # type: () -> dict self . _config [ 'applyCss' ] = self . applyCss self . _json [ 'config' ] = self . _config return self . _json
Represent effect as JSON dict .
50
6
4,124
def _delete_stale ( self ) : for name , hash_ in self . _stale_files . items ( ) : path = self . download_root . joinpath ( name ) if not path . exists ( ) : continue current_hash = self . _path_hash ( path ) if current_hash == hash_ : progress_logger . info ( 'deleting: %s which is stale...' , name ) path . unlink ( )...
Delete files left in self . _stale_files . Also delete their directories if empty .
242
19
4,125
def _file_path ( self , src_path , dest , regex ) : m = re . search ( regex , src_path ) if dest . endswith ( '/' ) or dest == '' : dest += '{filename}' names = m . groupdict ( ) if not names and m . groups ( ) : names = { 'filename' : m . groups ( ) [ - 1 ] } for name , value in names . items ( ) : dest = dest . repla...
check src_path complies with regex and generate new filename
200
12
4,126
def _lock ( self , url : str , name : str , hash_ : str ) : self . _new_lock . append ( { 'url' : url , 'name' : name , 'hash' : hash_ , } ) self . _stale_files . pop ( name , None )
Add details of the files downloaded to _new_lock so they can be saved to the lock file . Also remove path from _stale_files whatever remains at the end therefore is stale and can be deleted .
65
43
4,127
def setup_smtp ( self , host , port , user , passwd , recipients , * * kwargs ) : self . _smtp = kwargs self . _smtp . update ( { 'host' : host , 'port' : port , 'user' : user , 'passwd' : passwd , 'recipients' : recipients } ) try : self . _smtp [ 'timeout' ] = int ( kwargs . get ( 'timeout' , SMTP_DEFAULT_TIMEOUT ) )...
Set up the crash reporter to send reports via email using SMTP
160
13
4,128
def enable ( self ) : if not CrashReporter . active : CrashReporter . active = True # Store this function so we can set it back if the CrashReporter is deactivated self . _excepthook = sys . excepthook sys . excepthook = self . exception_handler self . logger . info ( 'CrashReporter: Enabled' ) if self . report_dir : i...
Enable the crash reporter . CrashReporter is defaulted to be enabled on creation .
190
17
4,129
def disable ( self ) : if CrashReporter . active : CrashReporter . active = False # Restore the original excepthook sys . excepthook = self . _excepthook self . stop_watcher ( ) self . logger . info ( 'CrashReporter: Disabled' )
Disable the crash reporter . No reports will be sent or saved .
65
13
4,130
def start_watcher ( self ) : if self . _watcher and self . _watcher . is_alive : self . _watcher_running = True else : self . logger . info ( 'CrashReporter: Starting watcher.' ) self . _watcher = Thread ( target = self . _watcher_thread , name = 'offline_reporter' ) self . _watcher . setDaemon ( True ) self . _watcher...
Start the watcher that periodically checks for offline reports and attempts to upload them .
112
16
4,131
def stop_watcher ( self ) : if self . _watcher : self . _watcher_running = False self . logger . info ( 'CrashReporter: Stopping watcher.' )
Stop the watcher thread that tries to send offline reports .
42
12
4,132
def subject ( self ) : if self . application_name and self . application_version : return 'Crash Report - {name} (v{version})' . format ( name = self . application_name , version = self . application_version ) else : return 'Crash Report'
Return a string to be used as the email subject line .
59
12
4,133
def store_report ( self , payload ) : offline_reports = self . get_offline_reports ( ) if offline_reports : # Increment the name of all existing reports 1 --> 2, 2 --> 3 etc. for ii , report in enumerate ( reversed ( offline_reports ) ) : rpath , ext = os . path . splitext ( report ) n = int ( re . findall ( '(\d+)' , ...
Save the crash report to a file . Keeping the last offline_report_limit files in a cyclical FIFO buffer . The newest crash report always named is 01
290
34
4,134
def _watcher_thread ( self ) : while 1 : time . sleep ( self . check_interval ) if not self . _watcher_running : break self . logger . info ( 'CrashReporter: Attempting to send offline reports.' ) self . submit_offline_reports ( ) remaining_reports = len ( self . get_offline_reports ( ) ) if remaining_reports == 0 : br...
Periodically attempt to upload the crash reports . If any upload method is successful delete the saved reports .
112
21
4,135
def colorize ( style , msg , resp ) : code = resp . status . split ( maxsplit = 1 ) [ 0 ] if code [ 0 ] == '2' : # Put 2XX first, since it should be the common case msg = style . HTTP_SUCCESS ( msg ) elif code [ 0 ] == '1' : msg = style . HTTP_INFO ( msg ) elif code == '304' : msg = style . HTTP_NOT_MODIFIED ( msg ) el...
Taken and modified from django . utils . log . ServerFormatter . format to mimic runserver s styling .
199
25
4,136
def access ( self , resp , req , environ , request_time ) : if not ( self . cfg . accesslog or self . cfg . logconfig or self . cfg . syslog ) : return msg = self . make_access_message ( resp , req , environ , request_time ) try : self . access_log . info ( msg ) except : self . error ( traceback . format_exc ( ) )
Override to apply styling on access logs .
94
8
4,137
def update ( cls , args ) : kytos_api = KytosConfig ( ) . config . get ( 'kytos' , 'api' ) url = f"{kytos_api}api/kytos/core/web/update" version = args [ "<version>" ] if version : url += f"/{version}" try : result = requests . post ( url ) except ( HTTPError , URLError , requests . exceptions . ConnectionError ) : LOG...
Call the method to update the Web UI .
169
9
4,138
def disable ( cls , args ) : mgr = NAppsManager ( ) if args [ 'all' ] : napps = mgr . get_enabled ( ) else : napps = args [ '<napp>' ] for napp in napps : mgr . set_napp ( * napp ) LOG . info ( 'NApp %s:' , mgr . napp_id ) cls . disable_napp ( mgr )
Disable subcommand .
99
4
4,139
def disable_napp ( mgr ) : if mgr . is_enabled ( ) : LOG . info ( ' Disabling...' ) mgr . disable ( ) LOG . info ( ' Disabled.' ) else : LOG . error ( " NApp isn't enabled." )
Disable a NApp .
58
5
4,140
def enable ( cls , args ) : mgr = NAppsManager ( ) if args [ 'all' ] : napps = mgr . get_disabled ( ) else : napps = args [ '<napp>' ] cls . enable_napps ( napps )
Enable subcommand .
61
4
4,141
def enable_napp ( cls , mgr ) : try : if not mgr . is_enabled ( ) : LOG . info ( ' Enabling...' ) mgr . enable ( ) LOG . info ( ' Enabled.' ) except ( FileNotFoundError , PermissionError ) as exception : LOG . error ( ' %s' , exception )
Install one NApp using NAppManager object .
75
10
4,142
def enable_napps ( cls , napps ) : mgr = NAppsManager ( ) for napp in napps : mgr . set_napp ( * napp ) LOG . info ( 'NApp %s:' , mgr . napp_id ) cls . enable_napp ( mgr )
Enable a list of NApps .
70
7
4,143
def uninstall ( cls , args ) : mgr = NAppsManager ( ) for napp in args [ '<napp>' ] : mgr . set_napp ( * napp ) LOG . info ( 'NApp %s:' , mgr . napp_id ) if mgr . is_installed ( ) : if mgr . is_enabled ( ) : cls . disable_napp ( mgr ) LOG . info ( ' Uninstalling...' ) mgr . uninstall ( ) LOG . info ( ' Uninstalled.' ) ...
Uninstall and delete NApps .
133
7
4,144
def install_napps ( cls , napps ) : mgr = NAppsManager ( ) for napp in napps : mgr . set_napp ( * napp ) LOG . info ( ' NApp %s:' , mgr . napp_id ) if not mgr . is_installed ( ) : try : cls . install_napp ( mgr ) if not mgr . is_enabled ( ) : cls . enable_napp ( mgr ) napp_dependencies = mgr . dependencies ( ) if napp_...
Install local or remote NApps .
182
7
4,145
def install_napp ( cls , mgr ) : try : LOG . info ( ' Searching local NApp...' ) mgr . install_local ( ) LOG . info ( ' Found and installed.' ) except FileNotFoundError : LOG . info ( ' Not found. Downloading from NApps Server...' ) try : mgr . install_remote ( ) LOG . info ( ' Downloaded and installed.' ) return excep...
Install a NApp .
175
5
4,146
def search ( cls , args ) : safe_shell_pat = re . escape ( args [ '<pattern>' ] ) . replace ( r'\*' , '.*' ) pat_str = '.*{}.*' . format ( safe_shell_pat ) pattern = re . compile ( pat_str , re . IGNORECASE ) remote_json = NAppsManager . search ( pattern ) remote = set ( ) for napp in remote_json : # WARNING: This will...
Search for NApps in NApps server matching a pattern .
184
12
4,147
def _print_napps ( cls , napp_list ) : mgr = NAppsManager ( ) enabled = mgr . get_enabled ( ) installed = mgr . get_installed ( ) napps = [ ] for napp , desc in sorted ( napp_list ) : status = 'i' if napp in installed else '-' status += 'e' if napp in enabled else '-' status = '[{}]' . format ( status ) name = '{}/{}' ...
Format the NApp list to be printed .
140
9
4,148
def list ( cls , args ) : # pylint: disable=unused-argument mgr = NAppsManager ( ) # Add status napps = [ napp + ( '[ie]' , ) for napp in mgr . get_enabled ( ) ] napps += [ napp + ( '[i-]' , ) for napp in mgr . get_disabled ( ) ] # Sort, add description and reorder columns napps . sort ( ) napps_ordered = [ ] for user ...
List all installed NApps and inform whether they are enabled .
202
12
4,149
def print_napps ( napps ) : if not napps : print ( 'No NApps found.' ) return stat_w = 6 # We already know the size of Status col name_w = max ( len ( n [ 1 ] ) for n in napps ) desc_w = max ( len ( n [ 2 ] ) for n in napps ) term_w = os . popen ( 'stty size' , 'r' ) . read ( ) . split ( ) [ 1 ] remaining = max ( 0 , i...
Print status name and description .
325
6
4,150
def delete ( args ) : mgr = NAppsManager ( ) for napp in args [ '<napp>' ] : mgr . set_napp ( * napp ) LOG . info ( 'Deleting NApp %s from server...' , mgr . napp_id ) try : mgr . delete ( ) LOG . info ( ' Deleted.' ) except requests . HTTPError as exception : if exception . response . status_code == 405 : LOG . error ...
Delete NApps from server .
149
6
4,151
def reload ( cls , args ) : LOG . info ( 'Reloading NApps...' ) mgr = NAppsManager ( ) try : if args [ 'all' ] : mgr . reload ( None ) else : napps = args [ '<napp>' ] mgr . reload ( napps ) LOG . info ( '\tReloaded.' ) except requests . HTTPError as exception : if exception . response . status_code != 200 : msg = json...
Reload NApps code .
132
6
4,152
def choices ( self ) : # from the reference property (instance) we need to get the value of the reference property in the model # in the reference property of the model the value is set to the ID of the model from which we can choose parts model_parent_part = self . part . model ( ) # makes single part call property_mo...
Retrieve the parts that you can reference for this ReferenceProperty .
144
13
4,153
def _generate_notebook_by_tag_body ( notebook_object , dict_by_tag ) : tag_keys = list ( dict_by_tag . keys ( ) ) tag_keys . sort ( ) for tag in tag_keys : if tag . lower ( ) not in SIGNAL_TYPE_LIST : markdown_cell = group_tag_code . TAG_TABLE_HEADER markdown_cell = markdown_cell . replace ( "Tag i" , tag ) for noteboo...
Internal function that is used for generation of the page where notebooks are organized by tag values .
459
18
4,154
def add_markdown_cell ( self , content , tags = None ) : self . notebook [ "cells" ] . append ( nb . v4 . new_markdown_cell ( content , * * { "metadata" : { "tags" : tags } } ) )
Class method responsible for adding a markdown cell with content content to the Notebook object .
60
18
4,155
def add_code_cell ( self , content , tags = None ) : self . notebook [ "cells" ] . append ( nb . v4 . new_code_cell ( content , * * { "metadata" : { "tags" : tags } } ) )
Class method responsible for adding a code cell with content content to the Notebook object .
58
17
4,156
def is_tracking_shield_displayed ( self ) : with self . selenium . context ( self . selenium . CONTEXT_CHROME ) : if self . window . firefox_version >= 63 : # Bug 1471713, 1476218 el = self . root . find_element ( * self . _tracking_protection_shield_locator ) return el . get_attribute ( "active" ) is not None el = sel...
Tracking Protection shield .
129
5
4,157
def validate_registration ( self ) : url = '/api/%s' % self . username response = self . make_request ( 'GET' , url ) if 'error' in response : return False return True
Checks if the device + username have already been registered with the bridge .
46
15
4,158
def connect ( self ) : # Don't try to register if we already have if self . validate_registration ( ) : return True body = { 'devicetype' : self . device_type , 'username' : self . username , } response = self . make_request ( 'POST' , '/api' , body ) if 'error' in response : if response [ 'error' ] [ 'type' ] == 101 :...
Registers a new device + username with the bridge
125
10
4,159
def get_lights ( self ) : url = '/api/%s/lights' % self . username response = self . make_request ( 'GET' , url ) lights = [ ] # Did we get a success response back? # error responses look like: # [{'error': {'address': '/lights', # 'description': 'unauthorized user', # 'type': 1}}] if 'error' in response : raise Except...
Lists all available lights on the bridge .
199
9
4,160
def set_color ( self , light_id , hex_value , brightness = None ) : light = self . get_light ( light_id ) xy = get_xy_from_hex ( hex_value ) data = { 'xy' : [ xy . x , xy . y ] , } if brightness is not None : data [ 'bri' ] = brightness return self . set_state ( light . light_id , * * data )
This will set the light color based on a hex value
99
11
4,161
def plotfft ( s , fmax , doplot = False ) : fs = abs ( np . fft . fft ( s ) ) f = linspace ( 0 , fmax / 2 , len ( s ) / 2 ) if doplot : #pl.plot(f[1:int(len(s) / 2)], fs[1:int(len(s) / 2)]) pass return ( f [ 1 : int ( len ( s ) / 2 ) ] . copy ( ) , fs [ 1 : int ( len ( s ) / 2 ) ] . copy ( ) )
This functions computes the fft of a signal returning the frequency and their magnitude values .
131
18
4,162
def discover ( service , timeout = 5 , retries = 5 ) : group = ( '239.255.255.250' , 1900 ) message = '\r\n' . join ( [ 'M-SEARCH * HTTP/1.1' , 'HOST: {0}:{1}' , 'MAN: "ssdp:discover"' , 'ST: {st}' , 'MX: 3' , '' , '' ] ) socket . setdefaulttimeout ( timeout ) responses = { } for _ in range ( retries ) : sock = socket ...
Discovers services on a network using the SSDP Protocol .
277
13
4,163
def _isinstance ( self , model , raise_error = True ) : rv = isinstance ( model , self . __model__ ) if not rv and raise_error : raise ValueError ( '%s is not of type %s' % ( model , self . __model__ ) ) return rv
Checks if the specified model instance matches the class model . By default this method will raise a ValueError if the model is not of expected type .
67
30
4,164
def _preprocess_params ( cls , kwargs ) : # kwargs.pop('csrf_token', None) for attr , val in kwargs . items ( ) : if cls . is_the_primary_key ( attr ) and cls . _prevent_primary_key_initialization_ : del kwargs [ attr ] continue if val == "" : # Making an assumption that there is no good usecase # for setting an empty ...
Returns a preprocessed dictionary of parameters . Use this to filter the kwargs passed to new create build methods .
498
24
4,165
def update ( self , * * kwargs ) : kwargs = self . _preprocess_params ( kwargs ) kwargs = self . preprocess_kwargs_before_update ( kwargs ) for key , value in kwargs . iteritems ( ) : cls = type ( self ) if not hasattr ( cls , key ) or isinstance ( getattr ( cls , key ) , property ) : continue if key not in self . _no_...
Updates an instance .
242
5
4,166
def filter_by ( cls , * * kwargs ) : limit = kwargs . pop ( 'limit' , None ) reverse = kwargs . pop ( 'reverse' , False ) q = cls . query . filter_by ( * * kwargs ) if reverse : q = q . order_by ( cls . id . desc ( ) ) if limit : q = q . limit ( limit ) return q
Same as SQLAlchemy s filter_by . Additionally this accepts two special keyword arguments limit and reverse for limiting the results and reversing the order respectively .
93
30
4,167
def count ( cls , * criterion , * * kwargs ) : if criterion or kwargs : return cls . filter ( * criterion , * * kwargs ) . count ( ) else : return cls . query . count ( )
Returns a count of the instances meeting the specified filter criterion and kwargs .
53
16
4,168
def new ( cls , * * kwargs ) : kwargs = cls . preprocess_kwargs_before_new ( kwargs ) if cls . __mapper__ . polymorphic_on is not None : discriminator_key = cls . __mapper__ . polymorphic_on . name discriminator_val = kwargs . get ( discriminator_key ) if discriminator_val is not None and discriminator_val in cls . __m...
Returns a new unsaved instance of the model class .
217
11
4,169
def add ( cls , model , commit = True ) : if not isinstance ( model , cls ) : raise ValueError ( '%s is not of type %s' % ( model , cls ) ) cls . session . add ( model ) try : if commit : cls . session . commit ( ) return model except : cls . session . rollback ( ) raise
Adds a model instance to session and commits the transaction .
82
11
4,170
def add_all ( cls , models , commit = True , check_type = False ) : if check_type : for model in models : if not isinstance ( model , cls ) : raise ValueError ( '%s is not of type %s' ( model , cls ) ) if None in models : cls . session . add_all ( [ m for m in models if m is not None ] ) else : cls . session . add_all ...
Batch method for adding a list of model instances to the db in one get_or_404 .
130
21
4,171
def get ( cls , keyval , key = 'id' , user_id = None ) : if keyval is None : return None if ( key in cls . __table__ . columns and cls . __table__ . columns [ key ] . primary_key ) : # if user_id and hasattr(cls, 'user_id'): # return cls.query.filter_by(id=keyval, user_id=user_id).first() return cls . query . get ( key...
Fetches a single instance which has value keyval for the attribute key .
180
16
4,172
def get_all ( cls , keyvals , key = 'id' , user_id = None ) : if len ( keyvals ) == 0 : return [ ] original_keyvals = keyvals keyvals_set = list ( set ( keyvals ) ) resultset = cls . query . filter ( getattr ( cls , key ) . in_ ( keyvals_set ) ) # This is ridiculous. user_id check cannot be here. A hangover # from the ...
Works like a map function from keyvals to instances .
221
11
4,173
def create ( cls , * * kwargs ) : try : return cls . add ( cls . new ( * * kwargs ) ) except : cls . session . rollback ( ) raise
Initializes a new instance adds it to the db and commits the transaction .
45
15
4,174
def find_or_create ( cls , * * kwargs ) : keys = kwargs . pop ( 'keys' ) if 'keys' in kwargs else [ ] return cls . first ( * * subdict ( kwargs , keys ) ) or cls . create ( * * kwargs )
Checks if an instance already exists by filtering with the kwargs . If yes returns that instance . If not creates a new instance with kwargs and returns it
70
34
4,175
def update_or_create ( cls , * * kwargs ) : keys = kwargs . pop ( 'keys' ) if 'keys' in kwargs else [ ] filter_kwargs = subdict ( kwargs , keys ) if filter_kwargs == { } : obj = None else : obj = cls . first ( * * filter_kwargs ) if obj is not None : for key , value in kwargs . iteritems ( ) : if ( key not in keys and ...
Checks if an instance already exists by filtering with the kwargs . If yes updates the instance with new kwargs and returns that instance . If not creates a new instance with kwargs and returns it .
171
44
4,176
def create_all ( cls , list_of_kwargs ) : try : return cls . add_all ( [ cls . new ( * * kwargs ) if kwargs is not None else None for kwargs in list_of_kwargs ] ) except : cls . session . rollback ( ) raise
Batch method for creating a list of instances
72
9
4,177
def find_or_create_all ( cls , list_of_kwargs , keys = [ ] ) : list_of_kwargs_wo_dupes , markers = remove_and_mark_duplicate_dicts ( list_of_kwargs , keys ) added_objs = cls . add_all ( [ cls . first ( * * subdict ( kwargs , keys ) ) or cls . new ( * * kwargs ) for kwargs in list_of_kwargs_wo_dupes ] ) result_objs = [ ...
Batch method for querying for a list of instances and creating them if required
212
16
4,178
def update_or_create_all ( cls , list_of_kwargs , keys = [ ] ) : objs = [ ] for kwargs in list_of_kwargs : filter_kwargs = subdict ( kwargs , keys ) if filter_kwargs == { } : obj = None else : obj = cls . first ( * * filter_kwargs ) if obj is not None : for key , value in kwargs . iteritems ( ) : if ( key not in keys a...
Batch method for updating a list of instances and creating them if required
181
14
4,179
def build ( cls , * * kwargs ) : return cls . add ( cls . new ( * * kwargs ) , commit = False )
Similar to create . But the transaction is not committed
35
10
4,180
def find_or_build ( cls , * * kwargs ) : keys = kwargs . pop ( 'keys' ) if 'keys' in kwargs else [ ] return cls . first ( * * subdict ( kwargs , keys ) ) or cls . build ( * * kwargs )
Checks if an instance already exists in db with these kwargs else returns a new saved instance of the service s model class .
70
27
4,181
def build_all ( cls , list_of_kwargs ) : return cls . add_all ( [ cls . new ( * * kwargs ) for kwargs in list_of_kwargs ] , commit = False )
Similar to create_all . But transaction is not committed .
53
12
4,182
def find_or_build_all ( cls , list_of_kwargs ) : return cls . add_all ( [ cls . first ( * * kwargs ) or cls . new ( * * kwargs ) for kwargs in list_of_kwargs ] , commit = False )
Similar to find_or_create_all . But transaction is not committed .
69
16
4,183
def update_all ( cls , * criterion , * * kwargs ) : try : r = cls . query . filter ( * criterion ) . update ( kwargs , 'fetch' ) cls . session . commit ( ) return r except : cls . session . rollback ( ) raise
Batch method for updating all instances obeying the criterion
66
11
4,184
def peakdelta ( v , delta , x = None ) : maxtab = [ ] mintab = [ ] if x is None : x = arange ( len ( v ) ) v = asarray ( v ) if len ( v ) != len ( x ) : sys . exit ( 'Input vectors v and x must have same length' ) if not isscalar ( delta ) : sys . exit ( 'Input argument delta must be a scalar' ) if delta <= 0 : sys . e...
Returns two arrays
297
3
4,185
def on_status_update ( self , channel , callback ) : if channel not in self . _callbacks : self . _callbacks [ channel ] = [ ] self . _callbacks [ channel ] . append ( callback )
Callback to execute on status of update of channel
48
9
4,186
def temp_chdir ( cwd = None ) : if six . PY3 : from tempfile import TemporaryDirectory with TemporaryDirectory ( ) as tempwd : origin = cwd or os . getcwd ( ) os . chdir ( tempwd ) try : yield tempwd if os . path . exists ( tempwd ) else '' finally : os . chdir ( origin ) else : from tempfile import mkdtemp tempwd = mk...
Create and return a temporary directory which you can use as a context manager .
143
15
4,187
def parse_datetime ( value ) : if value is None : # do not process the value return None def _get_fixed_timezone ( offset ) : """Return a tzinfo instance with a fixed offset from UTC.""" if isinstance ( offset , timedelta ) : offset = offset . seconds // 60 sign = '-' if offset < 0 else '+' hhmm = '%02d%02d' % divmod (...
Convert datetime string to datetime object .
509
10
4,188
def _save_customization ( self , widgets ) : if len ( widgets ) > 0 : # Get the current customization and only replace the 'ext' part of it customization = self . activity . _json_data . get ( 'customization' , dict ( ) ) if customization : customization [ 'ext' ] = dict ( widgets = widgets ) else : customization = dic...
Save the complete customization to the activity .
249
8
4,189
def _add_widget ( self , widget ) : widgets = self . widgets ( ) widgets += [ widget ] self . _save_customization ( widgets )
Add a widget to the customization .
33
7
4,190
def widgets ( self ) : customization = self . activity . _json_data . get ( 'customization' ) if customization and "ext" in customization . keys ( ) : return customization [ 'ext' ] [ 'widgets' ] else : return [ ]
Get the Ext JS specific customization from the activity .
55
10
4,191
def delete_widget ( self , index ) : widgets = self . widgets ( ) if len ( widgets ) == 0 : raise ValueError ( "This customization has no widgets" ) widgets . pop ( index ) self . _save_customization ( widgets )
Delete widgets by index .
53
5
4,192
def add_json_widget ( self , config ) : validate ( config , component_jsonwidget_schema ) self . _add_widget ( dict ( config = config , name = WidgetNames . JSONWIDGET ) )
Add an Ext Json Widget to the customization .
49
11
4,193
def add_property_grid_widget ( self , part_instance , max_height = None , custom_title = False , show_headers = True , show_columns = None ) : height = max_height # Check whether the parent_part_instance is uuid type or class `Part` if isinstance ( part_instance , Part ) : part_instance_id = part_instance . id elif isi...
Add a KE - chain Property Grid widget to the customization .
632
12
4,194
def add_text_widget ( self , text = None , custom_title = None , collapsible = True , collapsed = False ) : # Declare text widget config config = { "xtype" : ComponentXType . HTMLPANEL , "filter" : { "activity_id" : str ( self . activity . id ) , } } # Add text and custom title if text : config [ 'html' ] = text if cus...
Add a KE - chain Text widget to the customization .
282
11
4,195
def enable_mp_crash_reporting ( ) : global mp_crash_reporting_enabled multiprocessing . Process = multiprocessing . process . Process = CrashReportingProcess mp_crash_reporting_enabled = True
Monkey - patch the multiprocessing . Process class with our own CrashReportingProcess . Any subsequent imports of multiprocessing . Process will reference CrashReportingProcess instead .
50
36
4,196
def feed ( self , data ) : self . buffer += data while len ( self . buffer ) >= 6 : self . next_packet ( )
Add new incoming data to buffer and try to process
31
10
4,197
def valid_header_waiting ( self ) : if len ( self . buffer ) < 4 : self . logger . debug ( "Buffer does not yet contain full header" ) result = False else : result = True result = result and self . buffer [ 0 ] == velbus . START_BYTE if not result : self . logger . warning ( "Start byte not recognized" ) result = resul...
Check if a valid header is waiting in buffer
181
9
4,198
def valid_body_waiting ( self ) : # 0f f8 be 04 00 08 00 00 2f 04 packet_size = velbus . MINIMUM_MESSAGE_SIZE + ( self . buffer [ 3 ] & 0x0F ) if len ( self . buffer ) < packet_size : self . logger . debug ( "Buffer does not yet contain full message" ) result = False else : result = True result = result and self . buff...
Check if a valid body is waiting in buffer
214
9
4,199
def next_packet ( self ) : try : start_byte_index = self . buffer . index ( velbus . START_BYTE ) except ValueError : self . buffer = bytes ( [ ] ) return if start_byte_index >= 0 : self . buffer = self . buffer [ start_byte_index : ] if self . valid_header_waiting ( ) and self . valid_body_waiting ( ) : next_packet = ...
Process next packet if present
155
5