idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
7,300 | def bm3_p ( v , v0 , k0 , k0p , p_ref = 0.0 ) : return cal_p_bm3 ( v , [ v0 , k0 , k0p ] , p_ref = p_ref ) | calculate pressure from 3rd order Birch - Murnathan equation | 58 | 14 |
7,301 | def cal_p_bm3 ( v , k , p_ref = 0.0 ) : vvr = v / k [ 0 ] p = ( p_ref - 0.5 * ( 3. * k [ 1 ] - 5. * p_ref ) * ( 1. - vvr ** ( - 2. / 3. ) ) + 9. / 8. * k [ 1 ] * ( k [ 2 ] - 4. + 35. / 9. * p_ref / k [ 1 ] ) * ( 1. - vvr ** ( - 2. / 3. ) ) ** 2. ) * vvr ** ( - 5. / 3. ) return p | calculate pressure from 3rd order Birch - Murnaghan equation | 145 | 14 |
7,302 | def bm3_v_single ( p , v0 , k0 , k0p , p_ref = 0.0 , min_strain = 0.01 ) : if p <= 1.e-5 : return v0 def f_diff ( v , v0 , k0 , k0p , p , p_ref = 0.0 ) : return bm3_p ( v , v0 , k0 , k0p , p_ref = p_ref ) - p v = brenth ( f_diff , v0 , v0 * min_strain , args = ( v0 , k0 , k0p , p , p_ref ) ) return v | find volume at given pressure using brenth in scipy . optimize this is for single p value not vectorized this cannot handle uncertainties | 151 | 28 |
7,303 | def bm3_k ( p , v0 , k0 , k0p ) : return cal_k_bm3 ( p , [ v0 , k0 , k0p ] ) | calculate bulk modulus wrapper for cal_k_bm3 cannot handle uncertainties | 42 | 17 |
7,304 | def cal_k_bm3 ( p , k ) : v = cal_v_bm3 ( p , k ) return cal_k_bm3_from_v ( v , k ) | calculate bulk modulus | 42 | 6 |
7,305 | def bm3_g ( p , v0 , g0 , g0p , k0 , k0p ) : return cal_g_bm3 ( p , [ g0 , g0p ] , [ v0 , k0 , k0p ] ) | calculate shear modulus at given pressure . not fully tested with mdaap . | 58 | 19 |
7,306 | def cal_g_bm3 ( p , g , k ) : v = cal_v_bm3 ( p , k ) v0 = k [ 0 ] k0 = k [ 1 ] kp = k [ 2 ] g0 = g [ 0 ] gp = g [ 1 ] f = 0.5 * ( ( v / v0 ) ** ( - 2. / 3. ) - 1. ) return ( 1. + 2. * f ) ** ( 5. / 2. ) * ( g0 + ( 3. * k0 * gp - 5. * g0 ) * f + ( 6. * k0 * gp - 24. * k0 - 14. * g0 + 9. / 2. * k0 * kp ) * f ** 2. ) | calculate shear modulus at given pressure | 168 | 10 |
7,307 | def bm3_big_F ( p , v , v0 ) : f = bm3_small_f ( v , v0 ) return cal_big_F ( p , f ) | calculate big F for linearlized form not fully tested | 43 | 13 |
7,308 | def init_poolmanager ( self , connections , maxsize , block = requests . adapters . DEFAULT_POOLBLOCK , * * pool_kwargs ) : context = create_urllib3_context ( ciphers = self . CIPHERS , ssl_version = ssl . PROTOCOL_TLSv1 ) pool_kwargs [ 'ssl_context' ] = context return super ( TLSv1Adapter , self ) . init_poolmanager ( connections , maxsize , block , * * pool_kwargs ) | Initialize poolmanager with cipher and Tlsv1 | 117 | 11 |
7,309 | def proxy_manager_for ( self , proxy , * * proxy_kwargs ) : context = create_urllib3_context ( ciphers = self . CIPHERS , ssl_version = ssl . PROTOCOL_TLSv1 ) proxy_kwargs [ 'ssl_context' ] = context return super ( TLSv1Adapter , self ) . proxy_manager_for ( proxy , * * proxy_kwargs ) | Ensure cipher and Tlsv1 | 97 | 8 |
7,310 | def parse_stdout ( self , filelike ) : from aiida . orm import Dict formulae = { } content = filelike . read ( ) . strip ( ) if not content : return self . exit_codes . ERROR_EMPTY_OUTPUT_FILE try : for line in content . split ( '\n' ) : datablock , formula = re . split ( r'\s+' , line . strip ( ) , 1 ) formulae [ datablock ] = formula except Exception : # pylint: disable=broad-except self . logger . exception ( 'Failed to parse formulae from the stdout file\n%s' , traceback . format_exc ( ) ) return self . exit_codes . ERROR_PARSING_OUTPUT_DATA else : self . out ( 'formulae' , Dict ( dict = formulae ) ) return | Parse the formulae from the content written by the script to standard out . | 199 | 17 |
7,311 | def make_features ( context , frmat = 'table' , str_maximal = False ) : config = Config . create ( context = context , format = frmat , str_maximal = str_maximal ) return FeatureSystem ( config ) | Return a new feature system from context string in the given format . | 53 | 13 |
7,312 | def vinet_p ( v , v0 , k0 , k0p ) : # unumpy.exp works for both numpy and unumpy # so I set uncertainty default. # if unumpy.exp is used for lmfit, it generates an error return cal_p_vinet ( v , [ v0 , k0 , k0p ] , uncertainties = isuncertainties ( [ v , v0 , k0 , k0p ] ) ) | calculate pressure from vinet equation | 100 | 8 |
7,313 | def vinet_v_single ( p , v0 , k0 , k0p , min_strain = 0.01 ) : if p <= 1.e-5 : return v0 def f_diff ( v , v0 , k0 , k0p , p ) : return vinet_p ( v , v0 , k0 , k0p ) - p v = brenth ( f_diff , v0 , v0 * min_strain , args = ( v0 , k0 , k0p , p ) ) return v | find volume at given pressure using brenth in scipy . optimize this is for single p value not vectorized | 121 | 24 |
7,314 | def vinet_v ( p , v0 , k0 , k0p , min_strain = 0.01 ) : if isuncertainties ( [ p , v0 , k0 , k0p ] ) : f_u = np . vectorize ( uct . wrap ( vinet_v_single ) , excluded = [ 1 , 2 , 3 , 4 ] ) return f_u ( p , v0 , k0 , k0p , min_strain = min_strain ) else : f_v = np . vectorize ( vinet_v_single , excluded = [ 1 , 2 , 3 , 4 ] ) return f_v ( p , v0 , k0 , k0p , min_strain = min_strain ) | find volume at given pressure | 167 | 5 |
7,315 | def vinet_k ( p , v0 , k0 , k0p , numerical = False ) : f_u = uct . wrap ( cal_k_vinet ) return f_u ( p , [ v0 , k0 , k0p ] ) | calculate bulk modulus wrapper for cal_k_vinet cannot handle uncertainties | 58 | 17 |
7,316 | def user_portals_picker ( self ) : # print("Getting Portals list. This could take a few seconds...") portals = self . get_portals_list ( ) done = False while not done : opts = [ ( i , p ) for i , p in enumerate ( portals ) ] # print('') for opt , portal in opts : print ( "\t{0} - {1}" . format ( opt , portal [ 1 ] ) ) # print('') valid_choices = [ o [ 0 ] for o in opts ] choice = _input ( "Enter choice ({0}): " . format ( valid_choices ) ) if int ( choice ) in valid_choices : done = True # loop through all portals until we find an 'id':'rid' match self . set_portal_name ( opts [ int ( choice ) ] [ 1 ] [ 1 ] ) self . set_portal_id ( opts [ int ( choice ) ] [ 1 ] [ 0 ] ) # self.set_portal_rid( opts[int(choice)][1][2][1]['info']['key'] ) # self.__portal_sn_rid_dict = opts[int(choice)][1][2][1]['info']['aliases'] else : print ( "'{0}' is not a valid choice. Please choose from {1}" . format ( choice , valid_choices ) ) | This function is broken and needs to either be fixed or discarded . | 322 | 13 |
7,317 | def get_portal_by_name ( self , portal_name ) : portals = self . get_portals_list ( ) for p in portals : # print("Checking {!r}".format(p)) if portal_name == p [ 1 ] : # print("Found Portal!") self . set_portal_name ( p [ 1 ] ) self . set_portal_id ( p [ 0 ] ) self . set_portal_cik ( p [ 2 ] [ 1 ] [ 'info' ] [ 'key' ] ) # print("Active Portal Details:\nName: {0}\nId: {1}\nCIK: {2}".format( # self.portal_name(), # self.portal_id(), # self.portal_cik())) return p return None | Set active portal according to the name passed in portal_name . | 180 | 13 |
7,318 | def delete_device ( self , rid ) : headers = { 'User-Agent' : self . user_agent ( ) , 'Content-Type' : self . content_type ( ) } headers . update ( self . headers ( ) ) r = requests . delete ( self . portals_url ( ) + '/devices/' + rid , headers = headers , auth = self . auth ( ) ) if HTTP_STATUS . NO_CONTENT == r . status_code : print ( "Successfully deleted device with rid: {0}" . format ( rid ) ) return True else : print ( "Something went wrong: <{0}>: {1}" . format ( r . status_code , r . reason ) ) r . raise_for_status ( ) return False | Deletes device object with given rid | 164 | 7 |
7,319 | def list_device_data_sources ( self , device_rid ) : headers = { 'User-Agent' : self . user_agent ( ) , } headers . update ( self . headers ( ) ) r = requests . get ( self . portals_url ( ) + '/devices/' + device_rid + '/data-sources' , headers = headers , auth = self . auth ( ) ) if HTTP_STATUS . OK == r . status_code : return r . json ( ) else : print ( "Something went wrong: <{0}>: {1}" . format ( r . status_code , r . reason ) ) return None | List data sources of a portal device with rid device_rid . | 140 | 13 |
7,320 | def get_data_source_bulk_request ( self , rids , limit = 5 ) : headers = { 'User-Agent' : self . user_agent ( ) , 'Content-Type' : self . content_type ( ) } headers . update ( self . headers ( ) ) r = requests . get ( self . portals_url ( ) + '/data-sources/[' + "," . join ( rids ) + ']/data?limit=' + str ( limit ) , headers = headers , auth = self . auth ( ) ) if HTTP_STATUS . OK == r . status_code : return r . json ( ) else : print ( "Something went wrong: <{0}>: {1}" . format ( r . status_code , r . reason ) ) return { } | This grabs each datasource and its multiple datapoints for a particular device . | 173 | 17 |
7,321 | def get_all_devices_in_portal ( self ) : rids = self . get_portal_by_name ( self . portal_name ( ) ) [ 2 ] [ 1 ] [ 'info' ] [ 'aliases' ] # print("RIDS: {0}".format(rids)) device_rids = [ rid . strip ( ) for rid in rids ] blocks_of_ten = [ device_rids [ x : x + 10 ] for x in range ( 0 , len ( device_rids ) , 10 ) ] devices = [ ] for block_of_ten in blocks_of_ten : retval = self . get_multiple_devices ( block_of_ten ) if retval is not None : devices . extend ( retval ) else : print ( "Not adding to device list: {!r}" . format ( retval ) ) # Parse 'meta' key's raw string values for each device for device in devices : dictify_device_meta ( device ) return devices | This loops through the get_multiple_devices method 10 rids at a time . | 222 | 17 |
7,322 | def map_aliases_to_device_objects ( self ) : all_devices = self . get_all_devices_in_portal ( ) for dev_o in all_devices : dev_o [ 'portals_aliases' ] = self . get_portal_by_name ( self . portal_name ( ) ) [ 2 ] [ 1 ] [ 'info' ] [ 'aliases' ] [ dev_o [ 'rid' ] ] return all_devices | A device object knows its rid but not its alias . A portal object knows its device rids and aliases . | 105 | 22 |
7,323 | def search_for_devices_by_serial_number ( self , sn ) : import re sn_search = re . compile ( sn ) matches = [ ] for dev_o in self . get_all_devices_in_portal ( ) : # print("Checking {0}".format(dev_o['sn'])) try : if sn_search . match ( dev_o [ 'sn' ] ) : matches . append ( dev_o ) except TypeError as err : print ( "Problem checking device {!r}: {!r}" . format ( dev_o [ 'info' ] [ 'description' ] [ 'name' ] , str ( err ) ) ) return matches | Returns a list of device objects that match the serial number in param sn . | 149 | 15 |
7,324 | def print_device_list ( self , device_list = None ) : dev_list = device_list if device_list is not None else self . get_all_devices_in_portal ( ) for dev in dev_list : print ( '{0}\t\t{1}\t\t{2}' . format ( dev [ 'info' ] [ 'description' ] [ 'name' ] , dev [ 'sn' ] , dev [ 'portals_aliases' ] if len ( dev [ 'portals_aliases' ] ) != 1 else dev [ 'portals_aliases' ] [ 0 ] ) ) | Optional parameter is a list of device objects . If omitted will just print all portal devices objects . | 140 | 19 |
7,325 | def print_sorted_device_list ( self , device_list = None , sort_key = 'sn' ) : dev_list = device_list if device_list is not None else self . get_all_devices_in_portal ( ) sorted_dev_list = [ ] if sort_key == 'sn' : sort_keys = [ k [ sort_key ] for k in dev_list if k [ sort_key ] is not None ] sort_keys = sorted ( sort_keys ) for key in sort_keys : sorted_dev_list . extend ( [ d for d in dev_list if d [ 'sn' ] == key ] ) elif sort_key == 'name' : sort_keys = [ k [ 'info' ] [ 'description' ] [ sort_key ] for k in dev_list if k [ 'info' ] [ 'description' ] [ sort_key ] is not None ] sort_keys = sorted ( sort_keys ) for key in sort_keys : sorted_dev_list . extend ( [ d for d in dev_list if d [ 'info' ] [ 'description' ] [ sort_key ] == key ] ) elif sort_key == 'portals_aliases' : sort_keys = [ k [ sort_key ] for k in dev_list if k [ sort_key ] is not None ] sort_keys = sorted ( sort_keys ) for key in sort_keys : sorted_dev_list . extend ( [ d for d in dev_list if d [ sort_key ] == key ] ) else : print ( "Sort key {!r} not recognized." . format ( sort_key ) ) sort_keys = None self . print_device_list ( device_list = sorted_dev_list ) | Takes in a sort key and prints the device list according to that sort . | 388 | 16 |
7,326 | def get_user_id_from_email ( self , email ) : accts = self . get_all_user_accounts ( ) for acct in accts : if acct [ 'email' ] == email : return acct [ 'id' ] return None | Uses the get - all - user - accounts Portals API to retrieve the user - id by supplying an email . | 61 | 24 |
7,327 | def get_user_permission_from_email ( self , email ) : _id = self . get_user_id_from_email ( email ) return self . get_user_permission ( _id ) | Returns a user s permissions object when given the user email . | 47 | 12 |
7,328 | def add_dplist_permission_for_user_on_portal ( self , user_email , portal_id ) : _id = self . get_user_id_from_email ( user_email ) print ( self . get_user_permission_from_email ( user_email ) ) retval = self . add_user_permission ( _id , json . dumps ( [ { 'access' : 'd_p_list' , 'oid' : { 'id' : portal_id , 'type' : 'Portal' } } ] ) ) print ( self . get_user_permission_from_email ( user_email ) ) return retval | Adds the d_p_list permission to a user object when provided a user_email and portal_id . | 151 | 23 |
7,329 | def get_portal_cik ( self , portal_name ) : portal = self . get_portal_by_name ( portal_name ) cik = portal [ 2 ] [ 1 ] [ 'info' ] [ 'key' ] return cik | Retrieves portal object according to portal_name and returns its cik . | 56 | 16 |
7,330 | def init_write_index ( es_write , es_write_index ) : logging . info ( "Initializing index: " + es_write_index ) es_write . indices . delete ( es_write_index , ignore = [ 400 , 404 ] ) es_write . indices . create ( es_write_index , body = MAPPING_GIT ) | Initializes ES write index | 80 | 5 |
7,331 | def enrich ( self , column1 , column2 ) : if column1 not in self . commits . columns or column2 not in self . commits . columns : return self . commits # Select rows where values in column1 are different from # values in column2 pair_df = self . commits [ self . commits [ column1 ] != self . commits [ column2 ] ] new_values = list ( pair_df [ column2 ] ) # Update values from column2 pair_df [ column1 ] = new_values # This adds at the end of the original dataframe those rows duplicating # information and updating the values in column1 return self . commits . append ( pair_df ) | This class splits those commits where column1 and column2 values are different | 143 | 14 |
7,332 | def enrich ( self , column ) : if column not in self . data : return self . data # Insert a new column with default values self . data [ "filetype" ] = 'Other' # Insert 'Code' only in those rows that are # detected as being source code thanks to its extension reg = "\.c$|\.h$|\.cc$|\.cpp$|\.cxx$|\.c\+\+$|\.cp$|\.py$|\.js$|\.java$|\.rs$|\.go$" self . data . loc [ self . data [ column ] . str . contains ( reg ) , 'filetype' ] = 'Code' return self . data | This method adds a new column depending on the extension of the file . | 151 | 14 |
7,333 | def enrich ( self , column , projects ) : if column not in self . data . columns : return self . data self . data = pandas . merge ( self . data , projects , how = 'left' , on = column ) return self . data | This method adds a new column named as project that contains information about the associated project that the event in column belongs to . | 53 | 24 |
7,334 | def __parse_flags ( self , body ) : flags = [ ] values = [ ] lines = body . split ( '\n' ) for l in lines : for name in self . FLAGS_REGEX : m = re . match ( self . FLAGS_REGEX [ name ] , l ) if m : flags . append ( name ) values . append ( m . group ( "value" ) . strip ( ) ) if flags == [ ] : flags = "" values = "" return flags , values | Parse flags from a message | 109 | 6 |
7,335 | def enrich ( self , column ) : if column not in self . data . columns : return self . data self . data [ 'domain' ] = self . data [ column ] . apply ( lambda x : self . __parse_email ( x ) ) return self . data | This enricher returns the same dataframe with a new column named domain . That column is the result of splitting the email address of another column . If there is not a proper email address an unknown domain is returned . | 57 | 44 |
7,336 | def __remove_surrogates ( self , s , method = 'replace' ) : if type ( s ) == list and len ( s ) == 1 : if self . __is_surrogate_escaped ( s [ 0 ] ) : return s [ 0 ] . encode ( 'utf-8' , method ) . decode ( 'utf-8' ) else : return "" if type ( s ) == list : return "" if type ( s ) != str : return "" if self . __is_surrogate_escaped ( s ) : return s . encode ( 'utf-8' , method ) . decode ( 'utf-8' ) return s | Remove surrogates in the specified string | 142 | 7 |
7,337 | def __is_surrogate_escaped ( self , text ) : try : text . encode ( 'utf-8' ) except UnicodeEncodeError as e : if e . reason == 'surrogates not allowed' : return True return False | Checks if surrogate is escaped | 53 | 6 |
7,338 | def enrich ( self , columns ) : for column in columns : if column not in self . data . columns : return self . data for column in columns : a = self . data [ column ] . apply ( self . __remove_surrogates ) self . data [ column ] = a return self . data | This method convert to utf - 8 the provided columns | 64 | 11 |
7,339 | def __parse_addr ( self , addr ) : from email . utils import parseaddr value = parseaddr ( addr ) return value [ 0 ] , value [ 1 ] | Parse email addresses | 36 | 4 |
7,340 | def enrich ( self , columns ) : for column in columns : if column not in self . data . columns : return self . data # Looking for the rows with columns with lists of more # than one element first_column = list ( self . data [ columns [ 0 ] ] ) count = 0 append_df = pandas . DataFrame ( ) for cell in first_column : if len ( cell ) >= 1 : # Interested in those lists with more # than one element df = pandas . DataFrame ( ) # Create a dataframe of N rows from the list for column in columns : df [ column ] = self . data . loc [ count , column ] # Repeat the original rows N times extra_df = pandas . DataFrame ( [ self . data . loc [ count ] ] * len ( df ) ) for column in columns : extra_df [ column ] = list ( df [ column ] ) append_df = append_df . append ( extra_df , ignore_index = True ) extra_df = pandas . DataFrame ( ) count = count + 1 self . data = self . data . append ( append_df , ignore_index = True ) return self . data | This method appends at the end of the dataframe as many rows as items are found in the list of elemnents in the provided columns . | 251 | 30 |
7,341 | def enrich ( self , columns , groupby ) : for column in columns : if column not in self . data . columns : return self . data for column in columns : df_grouped = self . data . groupby ( [ groupby ] ) . agg ( { column : 'max' } ) df_grouped = df_grouped . reset_index ( ) df_grouped . rename ( columns = { column : 'max_' + column } , inplace = True ) self . data = pandas . merge ( self . data , df_grouped , how = 'left' , on = [ groupby ] ) df_grouped = self . data . groupby ( [ groupby ] ) . agg ( { column : 'min' } ) df_grouped = df_grouped . reset_index ( ) df_grouped . rename ( columns = { column : 'min_' + column } , inplace = True ) self . data = pandas . merge ( self . data , df_grouped , how = 'left' , on = [ groupby ] ) return self . data | This method calculates the maximum and minimum value of a given set of columns depending on another column . This is the usual group by clause in SQL . | 237 | 29 |
7,342 | def enrich ( self , column ) : if column not in self . data . columns : return self . data splits = self . data [ column ] . str . split ( " " ) splits = splits . str [ 0 ] self . data [ "gender_analyzed_name" ] = splits . fillna ( "noname" ) self . data [ "gender_probability" ] = 0 self . data [ "gender" ] = "Unknown" self . data [ "gender_count" ] = 0 names = list ( self . data [ "gender_analyzed_name" ] . unique ( ) ) for name in names : if name in self . gender . keys ( ) : gender_result = self . gender [ name ] else : try : # TODO: some errors found due to encode utf-8 issues. # Adding a try-except in the meantime. gender_result = self . connection . get ( [ name ] ) [ 0 ] except Exception : continue # Store info in the list of users self . gender [ name ] = gender_result # Update current dataset if gender_result [ "gender" ] is None : gender_result [ "gender" ] = "NotKnown" self . data . loc [ self . data [ "gender_analyzed_name" ] == name , 'gender' ] = gender_result [ "gender" ] if "probability" in gender_result . keys ( ) : self . data . loc [ self . data [ "gender_analyzed_name" ] == name , 'gender_probability' ] = gender_result [ "probability" ] self . data . loc [ self . data [ "gender_analyzed_name" ] == name , 'gender_count' ] = gender_result [ "count" ] self . data . fillna ( "noname" ) return self . data | This method calculates thanks to the genderize . io API the gender of a given name . | 398 | 18 |
7,343 | def enrich ( self , columns ) : for column in columns : if column not in self . data . columns : return self . data self . data = pandas . merge ( self . data , self . uuids_df , how = 'left' , on = columns ) self . data = self . data . fillna ( "notavailable" ) return self . data | Merges the original dataframe with corresponding entity uuids based on the given columns . Also merges other additional information associated to uuids provided in the uuids dataframe if any . | 78 | 40 |
7,344 | def echo_utc ( string ) : from datetime import datetime click . echo ( '{} | {}' . format ( datetime . utcnow ( ) . isoformat ( ) , string ) ) | Echo the string to standard out prefixed with the current date and time in UTC format . | 45 | 19 |
7,345 | def from_string ( cls , string ) : if string is None : string = '' if not isinstance ( string , six . string_types ) : raise TypeError ( 'string has to be a string type, got: {}' . format ( type ( string ) ) ) dictionary = { } tokens = [ token . strip ( ) for token in shlex . split ( string ) ] def list_tuples ( some_iterable ) : items , nexts = itertools . tee ( some_iterable , 2 ) nexts = itertools . chain ( itertools . islice ( nexts , 1 , None ) , [ None ] ) return list ( zip ( items , nexts ) ) for token_current , token_next in list_tuples ( tokens ) : # If current token starts with a dash, it is a value so we skip it if not token_current . startswith ( '-' ) : continue # If the next token is None or starts with a dash, the current token must be a flag, so the value is True if not token_next or token_next . startswith ( '-' ) : dictionary [ token_current . lstrip ( '-' ) ] = True # Otherwise the current token is an option with the next token being its value else : dictionary [ token_current . lstrip ( '-' ) ] = token_next return cls . from_dictionary ( dictionary ) | Parse a single string representing all command line parameters . | 305 | 11 |
7,346 | def from_dictionary ( cls , dictionary ) : if not isinstance ( dictionary , dict ) : raise TypeError ( 'dictionary has to be a dict type, got: {}' . format ( type ( dictionary ) ) ) return cls ( dictionary ) | Parse a dictionary representing all command line parameters . | 55 | 10 |
7,347 | def get_list ( self ) : result = [ ] for key , value in self . parameters . items ( ) : if value is None : continue if not isinstance ( value , list ) : value = [ value ] if len ( key ) == 1 : string_key = '-{}' . format ( key ) else : string_key = '--{}' . format ( key ) for sub_value in value : if isinstance ( sub_value , bool ) and sub_value is False : continue result . append ( string_key ) if not isinstance ( sub_value , bool ) : if ' ' in sub_value : string_value = "'{}'" . format ( sub_value ) else : string_value = sub_value result . append ( str ( string_value ) ) return result | Return the command line parameters as a list of options their values and arguments . | 174 | 15 |
7,348 | def run ( self , daemon = False ) : from aiida . engine import launch # If daemon is True, submit the process and return if daemon : node = launch . submit ( self . process , * * self . inputs ) echo . echo_info ( 'Submitted {}<{}>' . format ( self . process_name , node . pk ) ) return # Otherwise we run locally and wait for the process to finish echo . echo_info ( 'Running {}' . format ( self . process_name ) ) try : _ , node = launch . run_get_node ( self . process , * * self . inputs ) except Exception as exception : # pylint: disable=broad-except echo . echo_critical ( 'an exception occurred during execution: {}' . format ( str ( exception ) ) ) if node . is_killed : echo . echo_critical ( '{}<{}> was killed' . format ( self . process_name , node . pk ) ) elif not node . is_finished_ok : arguments = [ self . process_name , node . pk , node . exit_status , node . exit_message ] echo . echo_warning ( '{}<{}> failed with exit status {}: {}' . format ( * arguments ) ) else : output = [ ] echo . echo_success ( '{}<{}> finished successfully\n' . format ( self . process_name , node . pk ) ) for triple in sorted ( node . get_outgoing ( ) . all ( ) , key = lambda triple : triple . link_label ) : output . append ( [ triple . link_label , '{}<{}>' . format ( triple . node . __class__ . __name__ , triple . node . pk ) ] ) echo . echo ( tabulate . tabulate ( output , headers = [ 'Output label' , 'Node' ] ) ) | Launch the process with the given inputs by default running in the current interpreter . | 415 | 15 |
7,349 | def _xpathDict ( xml , xpath , cls , parent , * * kwargs ) : children = [ ] for child in xml . xpath ( xpath , namespaces = XPATH_NAMESPACES ) : children . append ( cls . parse ( resource = child , parent = parent , * * kwargs ) ) return children | Returns a default Dict given certain information | 77 | 8 |
7,350 | def _parse_structured_metadata ( obj , xml ) : for metadata in xml . xpath ( "cpt:structured-metadata/*" , namespaces = XPATH_NAMESPACES ) : tag = metadata . tag if "{" in tag : ns , tag = tuple ( tag . split ( "}" ) ) tag = URIRef ( ns [ 1 : ] + tag ) s_m = str ( metadata ) if s_m . startswith ( "urn:" ) or s_m . startswith ( "http:" ) or s_m . startswith ( "https:" ) or s_m . startswith ( "hdl:" ) : obj . metadata . add ( tag , URIRef ( metadata ) ) elif '{http://www.w3.org/XML/1998/namespace}lang' in metadata . attrib : obj . metadata . add ( tag , s_m , lang = metadata . attrib [ '{http://www.w3.org/XML/1998/namespace}lang' ] ) else : if "{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype" in metadata . attrib : datatype = metadata . attrib [ "{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype" ] if not datatype . startswith ( "http" ) and ":" in datatype : datatype = expand_namespace ( metadata . nsmap , datatype ) obj . metadata . add ( tag , Literal ( s_m , datatype = URIRef ( datatype ) ) ) elif isinstance ( metadata , IntElement ) : obj . metadata . add ( tag , Literal ( int ( metadata ) , datatype = XSD . integer ) ) elif isinstance ( metadata , FloatElement ) : obj . metadata . add ( tag , Literal ( float ( metadata ) , datatype = XSD . float ) ) else : obj . metadata . add ( tag , s_m ) | Parse an XML object for structured metadata | 467 | 8 |
7,351 | def ingest ( cls , resource , element = None , xpath = "ti:citation" ) : # Reuse of of find citation results = resource . xpath ( xpath , namespaces = XPATH_NAMESPACES ) if len ( results ) > 0 : citation = cls ( name = results [ 0 ] . get ( "label" ) , xpath = results [ 0 ] . get ( "xpath" ) , scope = results [ 0 ] . get ( "scope" ) ) if isinstance ( element , cls ) : element . child = citation cls . ingest ( resource = results [ 0 ] , element = element . child ) else : element = citation cls . ingest ( resource = results [ 0 ] , element = element ) return citation return None | Ingest xml to create a citation | 166 | 7 |
7,352 | def parse_metadata ( cls , obj , xml ) : for child in xml . xpath ( "ti:description" , namespaces = XPATH_NAMESPACES ) : lg = child . get ( "{http://www.w3.org/XML/1998/namespace}lang" ) if lg is not None : obj . set_cts_property ( "description" , child . text , lg ) for child in xml . xpath ( "ti:label" , namespaces = XPATH_NAMESPACES ) : lg = child . get ( "{http://www.w3.org/XML/1998/namespace}lang" ) if lg is not None : obj . set_cts_property ( "label" , child . text , lg ) obj . citation = cls . CLASS_CITATION . ingest ( xml , obj . citation , "ti:online/ti:citationMapping/ti:citation" ) # Added for commentary for child in xml . xpath ( "ti:about" , namespaces = XPATH_NAMESPACES ) : obj . set_link ( RDF_NAMESPACES . CTS . term ( "about" ) , child . get ( 'urn' ) ) _parse_structured_metadata ( obj , xml ) """ online = xml.xpath("ti:online", namespaces=NS) if len(online) > 0: online = online[0] obj.docname = online.get("docname") for validate in online.xpath("ti:validate", namespaces=NS): obj.validate = validate.get("schema") for namespaceMapping in online.xpath("ti:namespaceMapping", namespaces=NS): obj.metadata["namespaceMapping"][namespaceMapping.get("abbreviation")] = namespaceMapping.get("nsURI") """ | Parse a resource to feed the object | 417 | 8 |
7,353 | def parse ( cls , resource , parent = None ) : xml = xmlparser ( resource ) o = cls ( urn = xml . get ( "urn" ) , parent = parent ) for child in xml . xpath ( "ti:groupname" , namespaces = XPATH_NAMESPACES ) : lg = child . get ( "{http://www.w3.org/XML/1998/namespace}lang" ) if lg is not None : o . set_cts_property ( "groupname" , child . text , lg ) # Parse Works _xpathDict ( xml = xml , xpath = 'ti:work' , cls = cls . CLASS_WORK , parent = o ) _parse_structured_metadata ( o , xml ) return o | Parse a textgroup resource | 175 | 6 |
7,354 | def install ( label , plist ) : fname = launchd . plist . write ( label , plist ) launchd . load ( fname ) | Utility function to store a new . plist file and load it | 33 | 14 |
7,355 | def uninstall ( label ) : if launchd . LaunchdJob ( label ) . exists ( ) : fname = launchd . plist . discover_filename ( label ) launchd . unload ( fname ) os . unlink ( fname ) | Utility function to remove a . plist file and unload it | 53 | 14 |
7,356 | def write_hex ( fout , buf , offset , width = 16 ) : skipped_zeroes = 0 for i , chunk in enumerate ( chunk_iter ( buf , width ) ) : # zero skipping if chunk == ( b"\x00" * width ) : skipped_zeroes += 1 continue elif skipped_zeroes != 0 : fout . write ( " -- skipped zeroes: {}\n" . format ( skipped_zeroes ) ) skipped_zeroes = 0 # starting address of the current line fout . write ( "{:016x} " . format ( i * width + offset ) ) # bytes column column = " " . join ( [ " " . join ( [ "{:02x}" . format ( c ) for c in subchunk ] ) for subchunk in chunk_iter ( chunk , 8 ) ] ) w = width * 2 + ( width - 1 ) + ( ( width // 8 ) - 1 ) if len ( column ) != w : column += " " * ( w - len ( column ) ) fout . write ( column ) # ASCII character column fout . write ( " |" ) for c in chunk : if c in PRINTABLE_CHARS : fout . write ( chr ( c ) ) else : fout . write ( "." ) if len ( chunk ) < width : fout . write ( " " * ( width - len ( chunk ) ) ) fout . write ( "|" ) fout . write ( "\n" ) | Write the content of buf out in a hexdump style | 324 | 11 |
7,357 | def _read_config ( self ) : default_config_filepath = Path2 ( os . path . dirname ( __file__ ) , DEAFULT_CONFIG_FILENAME ) log . debug ( "Read defaults from: '%s'" % default_config_filepath ) if not default_config_filepath . is_file ( ) : raise RuntimeError ( "Internal error: Can't locate the default .ini file here: '%s'" % default_config_filepath ) config = self . _read_and_convert ( default_config_filepath , all_values = True ) log . debug ( "Defaults: %s" , pprint . pformat ( config ) ) self . ini_filepath = get_ini_filepath ( ) if not self . ini_filepath : # No .ini file made by user found # -> Create one into user home self . ini_filepath = get_user_ini_filepath ( ) # We don't use shutil.copyfile here, so the line endings will # be converted e.g. under windows from \n to \n\r with default_config_filepath . open ( "r" ) as infile : with self . ini_filepath . open ( "w" ) as outfile : outfile . write ( infile . read ( ) ) print ( "\n*************************************************************" ) print ( "Default config file was created into your home:" ) print ( "\t%s" % self . ini_filepath ) print ( "Change it for your needs ;)" ) print ( "*************************************************************\n" ) else : print ( "\nread user configuration from:" ) print ( "\t%s\n" % self . ini_filepath ) config . update ( self . _read_and_convert ( self . ini_filepath , all_values = False ) ) log . debug ( "RawConfig changed to: %s" , pprint . pformat ( config ) ) return config | returns the config as a dict . | 442 | 8 |
7,358 | def bind_graph ( graph = None ) : if graph is None : graph = Graph ( ) for prefix , ns in GRAPH_BINDINGS . items ( ) : graph . bind ( prefix , ns , True ) return graph | Bind a graph with generic MyCapytain prefixes | 48 | 11 |
7,359 | def zharkov_pel ( v , temp , v0 , e0 , g , n , z , t_ref = 300. , three_r = 3. * constants . R ) : v_mol = vol_uc2mol ( v , z ) x = v / v0 # a = a0 * np.power(x, m) def f ( t ) : return three_r * n / 2. * e0 * np . power ( x , g ) * np . power ( t , 2. ) * g / v_mol * 1.e-9 return f ( temp ) - f ( t_ref ) | calculate electronic contributions in pressure for the Zharkov equation the equation can be found in Sokolova and Dorogokupets 2013 | 138 | 29 |
7,360 | def tsuchiya_pel ( v , temp , v0 , a , b , c , d , n , z , three_r = 3. * constants . R , t_ref = 300. ) : def f ( temp ) : return a + b * temp + c * np . power ( temp , 2. ) + d * np . power ( temp , 3. ) return f ( temp ) - f ( t_ref ) | calculate electronic contributions in pressure for the Tsuchiya equation | 93 | 13 |
7,361 | def _validate_resources ( self ) : resources = self . options . resources for key in [ 'num_machines' , 'num_mpiprocs_per_machine' , 'tot_num_mpiprocs' ] : if key in resources and resources [ key ] != 1 : raise exceptions . FeatureNotAvailable ( "Cannot set resource '{}' to value '{}' for {}: parallelization is not supported, " "only a value of '1' is accepted." . format ( key , resources [ key ] , self . __class__ . __name__ ) ) | Validate the resources defined in the options . | 131 | 9 |
7,362 | def prepare_for_submission ( self , folder ) : from aiida_codtools . common . cli import CliParameters try : parameters = self . inputs . parameters . get_dict ( ) except AttributeError : parameters = { } self . _validate_resources ( ) cli_parameters = copy . deepcopy ( self . _default_cli_parameters ) cli_parameters . update ( parameters ) codeinfo = datastructures . CodeInfo ( ) codeinfo . code_uuid = self . inputs . code . uuid codeinfo . cmdline_params = CliParameters . from_dictionary ( cli_parameters ) . get_list ( ) codeinfo . stdin_name = self . options . input_filename codeinfo . stdout_name = self . options . output_filename codeinfo . stderr_name = self . options . error_filename calcinfo = datastructures . CalcInfo ( ) calcinfo . uuid = str ( self . uuid ) calcinfo . codes_info = [ codeinfo ] calcinfo . retrieve_list = [ self . options . output_filename , self . options . error_filename ] calcinfo . local_copy_list = [ ( self . inputs . cif . uuid , self . inputs . cif . filename , self . options . input_filename ) ] calcinfo . remote_copy_list = [ ] return calcinfo | This method is called prior to job submission with a set of calculation input nodes . | 310 | 16 |
7,363 | def hugoniot_p ( rho , rho0 , c0 , s ) : eta = 1. - ( rho0 / rho ) Ph = rho0 * c0 * c0 * eta / np . power ( ( 1. - s * eta ) , 2. ) return Ph | calculate pressure along a Hugoniot | 68 | 9 |
7,364 | def _dT_h_delta ( T_in_kK , eta , k , threenk , c_v ) : rho0 = k [ 0 ] # g/m^3 gamma0 = k [ 3 ] # no unit q = k [ 4 ] # no unit theta0_in_kK = k [ 5 ] # K, see Jamieson 1983 for detail rho = rho0 / ( 1. - eta ) c0 = k [ 1 ] # km/s s = k [ 2 ] # no unit dPhdelta_H = rho0 * c0 * c0 * ( 1. + s * eta ) / np . power ( ( 1. - s * eta ) , 3. ) # [g/cm^3][km/s]^2 = 1e9[kg m^2/s^2] = [GPa] Ph = hugoniot_p ( rho , rho0 , c0 , s ) # in [GPa] # calculate Cv gamma = gamma0 * np . power ( ( 1. - eta ) , q ) theta_in_kK = theta0_in_kK * np . exp ( ( gamma0 - gamma ) / q ) x = theta_in_kK / T_in_kK debye3 = debye_E ( x ) if c_v == 0. : c_v = threenk * ( 4. * debye3 - 3. * x / ( np . exp ( x ) - 1. ) ) # [J/g/K] # calculate dYdX dYdX = ( gamma / ( 1. - eta ) * T_in_kK ) + ( dPhdelta_H * eta - Ph ) / ( 2. * c_v * rho0 ) # print('dYdX', dYdX) return dYdX | internal function for calculation of temperature along a Hugoniot | 427 | 11 |
7,365 | def hugoniot_t_single ( rho , rho0 , c0 , s , gamma0 , q , theta0 , n , mass , three_r = 3. * constants . R , t_ref = 300. , c_v = 0. ) : eta = 1. - rho0 / rho if eta == 0.0 : return 300. threenk = three_r / mass * n # [J/mol/K] / [g/mol] = [J/g/K] k = [ rho0 , c0 , s , gamma0 , q , theta0 / 1.e3 ] t_h = odeint ( _dT_h_delta , t_ref / 1.e3 , [ 0. , eta ] , args = ( k , threenk , c_v ) , full_output = 1 ) temp_h = np . squeeze ( t_h [ 0 ] [ 1 ] ) return temp_h * 1.e3 | internal function to calculate pressure along Hugoniot | 223 | 9 |
7,366 | def hugoniot_t ( rho , rho0 , c0 , s , gamma0 , q , theta0 , n , mass , three_r = 3. * constants . R , t_ref = 300. , c_v = 0. ) : if isuncertainties ( [ rho , rho0 , c0 , s , gamma0 , q , theta0 ] ) : f_v = np . vectorize ( uct . wrap ( hugoniot_t_single ) , excluded = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ] ) else : f_v = np . vectorize ( hugoniot_t_single , excluded = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ] ) return f_v ( rho , rho0 , c0 , s , gamma0 , q , theta0 , n , mass , three_r = three_r , t_ref = t_ref , c_v = c_v ) | calculate temperature along a hugoniot | 236 | 9 |
7,367 | def to_str ( self ) : val = c_backend . pystring_get_str ( self . _ptr ) delattr ( self , '_ptr' ) setattr ( self , 'to_str' , _dangling_pointer ) return val . decode ( "utf-8" ) | Consumes the wrapper and returns a Python string . Afterwards is not necessary to destruct it as it has already been consumed . | 65 | 24 |
7,368 | def servers ( self , server = 'api.telldus.com' , port = http . HTTPS_PORT ) : logging . debug ( "Fetching server list from %s:%d" , server , port ) conn = http . HTTPSConnection ( server , port , context = self . ssl_context ( ) ) conn . request ( 'GET' , "/server/assign?protocolVersion=2" ) response = conn . getresponse ( ) if response . status != http . OK : raise RuntimeError ( "Could not connect to {}:{}: {} {}" . format ( server , port , response . status , response . reason ) ) servers = [ ] def extract_servers ( name , attributes ) : if name == "server" : servers . append ( ( attributes [ 'address' ] , int ( attributes [ 'port' ] ) ) ) parser = expat . ParserCreate ( ) parser . StartElementHandler = extract_servers parser . ParseFile ( response ) logging . debug ( "Found %d available servers" , len ( servers ) ) return servers | Fetch list of servers that can be connected to . | 231 | 11 |
7,369 | def execute ( cmd ) : proc = Popen ( cmd , stdout = PIPE ) stdout , _ = proc . communicate ( ) if proc . returncode != 0 : raise CalledProcessError ( proc . returncode , " " . join ( cmd ) ) return stdout . decode ( 'utf8' ) | Run a shell command and return stdout | 67 | 8 |
7,370 | def isuncertainties ( arg_list ) : for arg in arg_list : if isinstance ( arg , ( list , tuple ) ) and isinstance ( arg [ 0 ] , uct . UFloat ) : return True elif isinstance ( arg , np . ndarray ) and isinstance ( np . atleast_1d ( arg ) [ 0 ] , uct . UFloat ) : return True elif isinstance ( arg , ( float , uct . UFloat ) ) and isinstance ( arg , uct . UFloat ) : return True return False | check if the input list contains any elements with uncertainties class | 123 | 11 |
7,371 | def filter_tzfiles ( name_list ) : for src_name in name_list : # pytz-2012j/pytz/zoneinfo/Indian/Christmas parts = src_name . split ( '/' ) if len ( parts ) > 3 and parts [ 2 ] == 'zoneinfo' : dst_name = '/' . join ( parts [ 2 : ] ) yield src_name , dst_name | Returns a list of tuples for names that are tz data files . | 88 | 15 |
7,372 | def setup ( self , app ) : super ( ) . setup ( app ) self . handlers = OrderedDict ( ) # Connect admin templates app . ps . jinja2 . cfg . template_folders . append ( op . join ( PLUGIN_ROOT , 'templates' ) ) @ app . ps . jinja2 . filter def admtest ( value , a , b = None ) : return a if value else b @ app . ps . jinja2 . filter def admeq ( a , b , result = True ) : return result if a == b else not result @ app . ps . jinja2 . register def admurl ( request , prefix ) : qs = { k : v for k , v in request . query . items ( ) if not k . startswith ( prefix ) } if not qs : qs = { 'ap' : 0 } return "%s?%s" % ( request . path , urlparse . urlencode ( qs ) ) if self . cfg . name is None : self . cfg . name = "%s admin" % app . name . title ( ) # Register a base view if not callable ( self . cfg . home ) : def admin_home ( request ) : yield from self . authorize ( request ) return app . ps . jinja2 . render ( self . cfg . template_home , active = None ) self . cfg . home = admin_home app . register ( self . cfg . prefix ) ( self . cfg . home ) if not self . cfg . i18n : app . ps . jinja2 . env . globals . update ( { '_' : lambda s : s , 'gettext' : lambda s : s , 'ngettext' : lambda s , p , n : ( n != 1 and ( p , ) or ( s , ) ) [ 0 ] , } ) return if 'babel' not in app . ps or not isinstance ( app . ps . babel , BPlugin ) : raise PluginException ( 'Plugin `%s` requires for plugin `%s` to be installed to the application.' % ( self . name , BPlugin ) ) # Connect admin locales app . ps . babel . cfg . locales_dirs . append ( op . join ( PLUGIN_ROOT , 'locales' ) ) if not app . ps . babel . locale_selector_func : app . ps . babel . locale_selector_func = app . ps . babel . select_locale_by_request | Initialize the application . | 563 | 5 |
7,373 | def register ( self , * handlers , * * params ) : for handler in handlers : if issubclass ( handler , PWModel ) : handler = type ( handler . _meta . db_table . title ( ) + 'Admin' , ( PWAdminHandler , ) , dict ( model = handler , * * params ) ) self . app . register ( handler ) continue name = handler . name . lower ( ) self . handlers [ name ] = handler | Ensure that handler is not registered . | 94 | 8 |
7,374 | def authorization ( self , func ) : if self . app is None : raise PluginException ( 'The plugin must be installed to application.' ) self . authorize = muffin . to_coroutine ( func ) return func | Define a authorization process . | 45 | 6 |
7,375 | def scandir_limited ( top , limit , deep = 0 ) : deep += 1 try : scandir_it = Path2 ( top ) . scandir ( ) except PermissionError as err : log . error ( "scandir error: %s" % err ) return for entry in scandir_it : if entry . is_dir ( follow_symlinks = False ) : if deep < limit : yield from scandir_limited ( entry . path , limit , deep ) else : yield entry | yields only directories with the given deep limit | 111 | 10 |
7,376 | def iter_filtered_dir_entry ( dir_entries , match_patterns , on_skip ) : def match ( dir_entry_path , match_patterns , on_skip ) : for match_pattern in match_patterns : if dir_entry_path . path_instance . match ( match_pattern ) : on_skip ( dir_entry_path , match_pattern ) return True return False for entry in dir_entries : try : dir_entry_path = DirEntryPath ( entry ) except FileNotFoundError as err : # e.g.: A file was deleted after the first filesystem scan # Will be obsolete if we use shadow-copy / snapshot function from filesystem # see: https://github.com/jedie/PyHardLinkBackup/issues/6 log . error ( "Can't make DirEntryPath() instance: %s" % err ) continue if match ( dir_entry_path , match_patterns , on_skip ) : yield None else : yield dir_entry_path | Filter a list of DirEntryPath instances with the given pattern | 221 | 12 |
7,377 | def parse_pagination ( headers ) : links = { link . rel : parse_qs ( link . href ) . get ( "page" , None ) for link in link_header . parse ( headers . get ( "Link" , "" ) ) . links } return _Navigation ( links . get ( "previous" , [ None ] ) [ 0 ] , links . get ( "next" , [ None ] ) [ 0 ] , links . get ( "last" , [ None ] ) [ 0 ] , links . get ( "current" , [ None ] ) [ 0 ] , links . get ( "first" , [ None ] ) [ 0 ] ) | Parses headers to create a pagination objects | 143 | 10 |
7,378 | def parse_uri ( uri , endpoint_uri ) : temp_parse = urlparse ( uri ) return _Route ( urljoin ( endpoint_uri , temp_parse . path ) , parse_qs ( temp_parse . query ) ) | Parse a URI into a Route namedtuple | 52 | 10 |
7,379 | def _cryptodome_cipher ( key , iv ) : return AES . new ( key , AES . MODE_CFB , iv , segment_size = 128 ) | Build a Pycryptodome AES Cipher object . | 37 | 10 |
7,380 | def _cryptography_cipher ( key , iv ) : return Cipher ( algorithm = algorithms . AES ( key ) , mode = modes . CFB ( iv ) , backend = default_backend ( ) ) | Build a cryptography AES Cipher object . | 44 | 7 |
7,381 | def make_xml_node ( graph , name , close = False , attributes = None , text = "" , complete = False , innerXML = "" ) : name = graph . namespace_manager . qname ( name ) if complete : if attributes is not None : return "<{0} {1}>{2}{3}</{0}>" . format ( name , " " . join ( [ "{}=\"{}\"" . format ( attr_name , attr_value ) for attr_name , attr_value in attributes . items ( ) ] ) , escape ( text ) , innerXML ) return "<{0}>{1}{2}</{0}>" . format ( name , escape ( text ) , innerXML ) elif close is True : return "</{}>" . format ( name ) elif attributes is not None : return "<{} {}>" . format ( name , " " . join ( [ "{}=\"{}\"" . format ( attr_name , attr_value ) for attr_name , attr_value in attributes . items ( ) ] ) ) return "<{}>" . format ( name ) | Create an XML Node | 254 | 4 |
7,382 | def performXpath ( parent , xpath ) : loop = False if xpath . startswith ( ".//" ) : result = parent . xpath ( xpath . replace ( ".//" , "./" , 1 ) , namespaces = XPATH_NAMESPACES ) if len ( result ) == 0 : result = parent . xpath ( "*[{}]" . format ( xpath ) , namespaces = XPATH_NAMESPACES ) loop = True else : result = parent . xpath ( xpath , namespaces = XPATH_NAMESPACES ) return result [ 0 ] , loop | Perform an XPath on an element and indicate if we need to loop over it to find something | 133 | 20 |
7,383 | def copyNode ( node , children = False , parent = False ) : if parent is not False : element = SubElement ( parent , node . tag , attrib = node . attrib , nsmap = { None : "http://www.tei-c.org/ns/1.0" } ) else : element = Element ( node . tag , attrib = node . attrib , nsmap = { None : "http://www.tei-c.org/ns/1.0" } ) if children : if node . text : element . _setText ( node . text ) for child in xmliter ( node ) : element . append ( copy ( child ) ) return element | Copy an XML Node | 150 | 4 |
7,384 | def normalizeXpath ( xpath ) : new_xpath = [ ] for x in range ( 0 , len ( xpath ) ) : if x > 0 and len ( xpath [ x - 1 ] ) == 0 : new_xpath . append ( "/" + xpath [ x ] ) elif len ( xpath [ x ] ) > 0 : new_xpath . append ( xpath [ x ] ) return new_xpath | Normalize XPATH split around slashes | 96 | 8 |
7,385 | def passageLoop ( parent , new_tree , xpath1 , xpath2 = None , preceding_siblings = False , following_siblings = False ) : current_1 , queue_1 = __formatXpath__ ( xpath1 ) if xpath2 is None : # In case we need what is following or preceding our node result_1 , loop = performXpath ( parent , current_1 ) if loop is True : queue_1 = xpath1 central = None has_no_queue = len ( queue_1 ) == 0 # For each sibling, when we need them in the context of a range if preceding_siblings or following_siblings : for sibling in xmliter ( parent ) : if sibling == result_1 : central = True # We copy the node we looked for (Result_1) child = copyNode ( result_1 , children = has_no_queue , parent = new_tree ) # if we don't have children # we loop over the passage child if not has_no_queue : passageLoop ( result_1 , child , queue_1 , None , preceding_siblings = preceding_siblings , following_siblings = following_siblings ) # If we were waiting for preceding_siblings, we break it off # As we don't need to go further if preceding_siblings : break elif not central and preceding_siblings : copyNode ( sibling , parent = new_tree , children = True ) elif central and following_siblings : copyNode ( sibling , parent = new_tree , children = True ) else : result_1 , loop = performXpath ( parent , current_1 ) if loop is True : queue_1 = xpath1 if xpath2 == xpath1 : current_2 , queue_2 = current_1 , queue_1 else : current_2 , queue_2 = __formatXpath__ ( xpath2 ) else : current_2 , queue_2 = __formatXpath__ ( xpath2 ) if xpath1 != xpath2 : result_2 , loop = performXpath ( parent , current_2 ) if loop is True : queue_2 = xpath2 else : result_2 = result_1 if result_1 == result_2 : has_no_queue = len ( queue_1 ) == 0 child = copyNode ( result_1 , children = has_no_queue , parent = new_tree ) if not has_no_queue : passageLoop ( result_1 , child , queue_1 , queue_2 ) else : start = False # For each sibling for sibling in xmliter ( parent ) : # If we have found start # We copy the node because we are between start and end if start : # If we are at the end # We break the copy if sibling == result_2 : break else : copyNode ( sibling , parent = new_tree , children = True ) # If this is start # Then we copy it and initiate star elif sibling == result_1 : start = True has_no_queue_1 = len ( queue_1 ) == 0 node = copyNode ( sibling , children = has_no_queue_1 , parent = new_tree ) if not has_no_queue_1 : passageLoop ( sibling , node , queue_1 , None , following_siblings = True ) continue_loop = len ( queue_2 ) == 0 node = copyNode ( result_2 , children = continue_loop , parent = new_tree ) if not continue_loop : passageLoop ( result_2 , node , queue_2 , None , preceding_siblings = True ) return new_tree | Loop over passages to construct and increment new tree given a parent and XPaths | 780 | 15 |
7,386 | def get_label ( self , lang = None ) : x = None if lang is None : for obj in self . graph . objects ( self . asNode ( ) , RDFS . label ) : return obj for obj in self . graph . objects ( self . asNode ( ) , RDFS . label ) : x = obj if x . language == lang : return x return x | Return label for given lang or any default | 82 | 8 |
7,387 | def parents ( self ) -> List [ "Collection" ] : p = self . parent parents = [ ] while p is not None : parents . append ( p ) p = p . parent return parents | Iterator to find parents of current collection from closest to furthest | 41 | 12 |
7,388 | def _add_member ( self , member ) : if member . id in self . children : return None else : self . children [ member . id ] = member | Does not add member if it already knows it . | 34 | 10 |
7,389 | def export_base_dts ( cls , graph , obj , nsm ) : o = { "@id" : str ( obj . asNode ( ) ) , "@type" : nsm . qname ( obj . type ) , nsm . qname ( RDF_NAMESPACES . HYDRA . title ) : str ( obj . get_label ( ) ) , nsm . qname ( RDF_NAMESPACES . HYDRA . totalItems ) : obj . size } for desc in graph . objects ( obj . asNode ( ) , RDF_NAMESPACES . HYDRA . description ) : o [ nsm . qname ( RDF_NAMESPACES . HYDRA . description ) ] = str ( desc ) return o | Export the base DTS information in a simple reusable way | 168 | 11 |
7,390 | def get_subject ( self , lang = None ) : return self . metadata . get_single ( key = DC . subject , lang = lang ) | Get the subject of the object | 31 | 6 |
7,391 | def get_context ( self ) : if not self . is_valid ( ) : raise ValueError ( "Cannot generate Context when form is invalid." ) return dict ( request = self . request , * * self . cleaned_data ) | Context sent to templates for rendering include the form s cleaned data and also the current Request object . | 50 | 19 |
7,392 | def zharkov_panh ( v , temp , v0 , a0 , m , n , z , t_ref = 300. , three_r = 3. * constants . R ) : v_mol = vol_uc2mol ( v , z ) x = v / v0 a = a0 * np . power ( x , m ) def f ( t ) : return three_r * n / 2. * a * m / v_mol * np . power ( t , 2. ) * 1.e-9 return f ( temp ) - f ( t_ref ) | calculate pressure from anharmonicity for Zharkov equation the equation is from Dorogokupets 2015 | 128 | 24 |
7,393 | def split_words ( line ) : # Normalize any camel cased words first line = _NORM_REGEX . sub ( r'\1 \2' , line ) return [ normalize ( w ) for w in _WORD_REGEX . split ( line ) ] | Return the list of words contained in a line . | 60 | 10 |
7,394 | def add ( self , files ) : if files . __class__ . __name__ == 'str' : self . _files . append ( files ) else : self . _files . extend ( files ) | Adds files to check . | 43 | 5 |
7,395 | def check ( self ) : errors = [ ] results = [ ] for fn in self . _files : if not os . path . isdir ( fn ) : try : with open ( fn , 'r' ) as f : line_ct = 1 for line in f : for word in split_words ( line ) : if ( word in self . _misspelling_dict or word . lower ( ) in self . _misspelling_dict ) : results . append ( [ fn , line_ct , word ] ) line_ct += 1 except UnicodeDecodeError : pass except IOError : errors . append ( '%s' % sys . exc_info ( ) [ 1 ] ) return errors , results | Checks the files for misspellings . | 149 | 9 |
7,396 | def suggestions ( self , word ) : suggestions = set ( self . _misspelling_dict . get ( word , [ ] ) ) . union ( set ( self . _misspelling_dict . get ( word . lower ( ) , [ ] ) ) ) return sorted ( [ same_case ( source = word , destination = w ) for w in suggestions ] ) | Returns a list of suggestions for a misspelled word . | 76 | 11 |
7,397 | def dump_misspelling_list ( self ) : results = [ ] for bad_word in sorted ( self . _misspelling_dict . keys ( ) ) : for correction in self . _misspelling_dict [ bad_word ] : results . append ( [ bad_word , correction ] ) return results | Returns a list of misspelled words and corrections . | 65 | 10 |
7,398 | def status ( self ) : orig_dict = self . _get ( self . _service_url ( 'status' ) ) orig_dict [ 'implementation_version' ] = orig_dict . pop ( 'Implementation-Version' ) orig_dict [ 'built_from_git_sha1' ] = orig_dict . pop ( 'Built-From-Git-SHA1' ) return Status ( orig_dict ) | Get the status of Alerting Service | 93 | 7 |
7,399 | def cli ( ctx , report , semantic , rcfile ) : ctx . obj = { 'report' : report , 'semantic' : semantic , 'rcfile' : rcfile , } | Query or manipulate smother reports | 43 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.