idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
8,300
def _read_file ( filename ) : # read data with open ( filename , 'r' ) as fid2 : abem_data_orig = fid2 . read ( ) fid = StringIO ( ) fid . write ( abem_data_orig ) fid . seek ( 0 ) # determine type of array fid . readline ( ) fid . readline ( ) file_type = int ( fid . readline ( ) . strip ( ) ) # reset file pointer fid . seek ( 0 ) return file_type , fid
Read a res2dinv - file and return the header
111
12
8,301
def add_dat_file ( filename , settings , container = None , * * kwargs ) : # each type is read by a different function importers = { # general array type 11 : _read_general_type , } file_type , content = _read_file ( filename ) if file_type not in importers : raise Exception ( 'type of RES2DINV data file not recognized: {0}' . format ( file_type ) ) header , data = importers [ file_type ] ( content , settings ) timestep = settings . get ( 'timestep' , 0 ) # add timestep column data [ 'timestep' ] = timestep if container is None : container = ERT ( data ) else : container . data = pd . concat ( ( container . data , data ) ) return container
Read a RES2DINV - style file produced by the ABEM export program .
183
18
8,302
def console_input ( default , validation = None , allow_empty = False ) : value = raw_input ( "> " ) or default if value == "" and not allow_empty : print "Invalid: Empty value is not permitted." return console_input ( default , validation ) if validation : try : return validation ( value ) except ValidationError , e : print "Invalid: " , e return console_input ( default , validation ) return value
Get user input value from stdin
94
7
8,303
def correct ( self , calib , temp , we_t , ae_t ) : if not A4TempComp . in_range ( temp ) : return None if self . __algorithm == 1 : return self . __eq1 ( temp , we_t , ae_t ) if self . __algorithm == 2 : return self . __eq2 ( temp , we_t , ae_t , calib . we_cal_mv , calib . ae_cal_mv ) if self . __algorithm == 3 : return self . __eq3 ( temp , we_t , ae_t , calib . we_cal_mv , calib . ae_cal_mv ) if self . __algorithm == 4 : return self . __eq4 ( temp , we_t , calib . we_cal_mv ) raise ValueError ( "A4TempComp.conv: unrecognised algorithm: %d." % self . __algorithm )
Compute weC from weT aeT
211
10
8,304
def cf_t ( self , temp ) : index = int ( ( temp - A4TempComp . __MIN_TEMP ) // A4TempComp . __INTERVAL ) # index of start of interval # on boundary... if temp % A4TempComp . __INTERVAL == 0 : return self . __values [ index ] # all others... y1 = self . __values [ index ] # y value at start of interval y2 = self . __values [ index + 1 ] # y value at end of interval delta_y = y2 - y1 delta_x = float ( temp % A4TempComp . __INTERVAL ) / A4TempComp . __INTERVAL # proportion of interval cf_t = y1 + ( delta_y * delta_x ) # print("A4TempComp.cf_t: alg:%d, temp:%f y1:%f y2:%f delta_y:%f delta_x:%f cf_t:%f " % # (self.__algorithm, temp, y1, y2, delta_y, delta_x, cf_t), file=sys.stderr) return cf_t
Compute the linear - interpolated temperature compensation factor .
257
11
8,305
def run_once ( function , state = { } , errors = { } ) : @ six . wraps ( function ) def _wrapper ( * args , * * kwargs ) : if function in errors : # Deliberate use of LBYL. six . reraise ( * errors [ function ] ) try : return state [ function ] except KeyError : try : state [ function ] = result = function ( * args , * * kwargs ) return result except Exception : errors [ function ] = sys . exc_info ( ) raise return _wrapper
A memoization decorator whose purpose is to cache calls .
117
12
8,306
def _session ( self ) : if self . _http_session is None : self . _http_session = requests . Session ( ) self . _http_session . headers . update ( self . _get_headers ( ) ) self . _http_session . verify = self . _verify_https_request ( ) if all ( self . _credentials ) : username , password = self . _credentials self . _http_session . auth = requests_ntlm . HttpNtlmAuth ( username = username , password = password ) return self . _http_session
The current session used by the client .
127
8
8,307
def get_resource ( self , path ) : response = self . _http_request ( path ) try : return response . json ( ) except ValueError : raise exception . ServiceException ( "Invalid service response." )
Getting the required information from the API .
45
8
8,308
def update_resource ( self , path , data , if_match = None ) : response = self . _http_request ( resource = path , method = "PUT" , body = data , if_match = if_match ) try : return response . json ( ) except ValueError : raise exception . ServiceException ( "Invalid service response." )
Update the required resource .
73
5
8,309
def summarize ( self ) : s = str ( self . allval ( ) ) return self . parse ( s [ : 2 ] + '' . join ( [ 'Z' ] * len ( s [ 2 : ] ) ) )
Convert all of the values to their max values . This form is used to represent the summary level
48
20
8,310
def _filter_schlumberger ( configs ) : # sort configs configs_sorted = np . hstack ( ( np . sort ( configs [ : , 0 : 2 ] , axis = 1 ) , np . sort ( configs [ : , 2 : 4 ] , axis = 1 ) , ) ) . astype ( int ) # determine unique voltage dipoles MN = configs_sorted [ : , 2 : 4 ] . copy ( ) MN_unique = np . unique ( MN . view ( MN . dtype . descr * 2 ) ) MN_unique_reshape = MN_unique . view ( MN . dtype ) . reshape ( - 1 , 2 ) schl_indices_list = [ ] for mn in MN_unique_reshape : # check if there are more than one associated current injections nr_current_binary = ( ( configs_sorted [ : , 2 ] == mn [ 0 ] ) & ( configs_sorted [ : , 3 ] == mn [ 1 ] ) ) if len ( np . where ( nr_current_binary ) [ 0 ] ) < 2 : continue # now which of these configurations have current electrodes on both # sides of the voltage dipole nr_left_right = ( ( configs_sorted [ : , 0 ] < mn [ 0 ] ) & ( configs_sorted [ : , 1 ] > mn [ 0 ] ) & nr_current_binary ) # now check that the left/right distances are equal distance_left = np . abs ( configs_sorted [ nr_left_right , 0 ] - mn [ 0 ] ) . squeeze ( ) distance_right = np . abs ( configs_sorted [ nr_left_right , 1 ] - mn [ 1 ] ) . squeeze ( ) nr_equal_distances = np . where ( distance_left == distance_right ) [ 0 ] indices = np . where ( nr_left_right ) [ 0 ] [ nr_equal_distances ] if indices . size > 2 : schl_indices_list . append ( indices ) # set Schlumberger configs to nan if len ( schl_indices_list ) == 0 : return configs , { 0 : np . array ( [ ] ) } else : schl_indices = np . hstack ( schl_indices_list ) . squeeze ( ) configs [ schl_indices , : ] = np . nan return configs , { 0 : schl_indices }
Filter Schlumberger configurations
557
5
8,311
def _filter_dipole_dipole ( configs ) : # check that dipoles have equal size dist_ab = np . abs ( configs [ : , 0 ] - configs [ : , 1 ] ) dist_mn = np . abs ( configs [ : , 2 ] - configs [ : , 3 ] ) distances_equal = ( dist_ab == dist_mn ) # check that they are not overlapping not_overlapping = ( # either a,b < m,n ( ( configs [ : , 0 ] < configs [ : , 2 ] ) & ( configs [ : , 1 ] < configs [ : , 2 ] ) & ( configs [ : , 0 ] < configs [ : , 3 ] ) & ( configs [ : , 1 ] < configs [ : , 3 ] ) ) | # or m,n < a,b ( ( configs [ : , 2 ] < configs [ : , 0 ] ) & ( configs [ : , 3 ] < configs [ : , 0 ] ) & ( configs [ : , 2 ] < configs [ : , 1 ] ) & ( configs [ : , 3 ] < configs [ : , 1 ] ) ) ) is_dipole_dipole = ( distances_equal & not_overlapping ) dd_indices = np . where ( is_dipole_dipole ) [ 0 ] dd_indices_sorted = _sort_dd_skips ( configs [ dd_indices , : ] , dd_indices ) # set all dd configs to nan configs [ dd_indices , : ] = np . nan return configs , dd_indices_sorted
Filter dipole - dipole configurations
373
7
8,312
def _sort_dd_skips ( configs , dd_indices_all ) : config_current_skips = np . abs ( configs [ : , 1 ] - configs [ : , 0 ] ) if np . all ( np . isnan ( config_current_skips ) ) : return { 0 : [ ] } # determine skips available_skips_raw = np . unique ( config_current_skips ) available_skips = available_skips_raw [ ~ np . isnan ( available_skips_raw ) ] . astype ( int ) # now determine the configurations dd_configs_sorted = { } for skip in available_skips : indices = np . where ( config_current_skips == skip ) [ 0 ] dd_configs_sorted [ skip - 1 ] = dd_indices_all [ indices ] return dd_configs_sorted
Given a set of dipole - dipole configurations sort them according to their current skip .
198
18
8,313
def filter ( configs , settings ) : if isinstance ( configs , pd . DataFrame ) : configs = configs [ [ 'a' , 'b' , 'm' , 'n' ] ] . values # assign short labels to Python functions filter_funcs = { 'dd' : _filter_dipole_dipole , 'schlumberger' : _filter_schlumberger , } # we need a list to fix the call order of filter functions keys = [ 'dd' , 'schlumberger' , ] allowed_keys = settings . get ( 'only_types' , filter_funcs . keys ( ) ) results = { } # we operate iteratively on the configs, set the first round here # rows are iteratively set to nan when filters remove them! configs_filtered = configs . copy ( ) . astype ( float ) for key in keys : if key in allowed_keys : configs_filtered , indices_filtered = filter_funcs [ key ] ( configs_filtered , ) if len ( indices_filtered ) > 0 : results [ key ] = indices_filtered # add all remaining indices to the results dict results [ 'not_sorted' ] = np . where ( ~ np . all ( np . isnan ( configs_filtered ) , axis = 1 ) ) [ 0 ] return results
Main entry function to filtering configuration types
302
7
8,314
def save_block_to_crt ( filename , group , norrec = 'all' , store_errors = False ) : if norrec != 'all' : group = group . query ( 'norrec == "{0}"' . format ( norrec ) ) # todo: we need to fix the global naming scheme for columns! with open ( filename , 'wb' ) as fid : fid . write ( bytes ( '{0}\n' . format ( len ( group ) ) , 'UTF-8' ) ) AB = group [ 'a' ] * 1e4 + group [ 'b' ] MN = group [ 'm' ] * 1e4 + group [ 'n' ] line = [ AB . values . astype ( int ) , MN . values . astype ( int ) , group [ 'r' ] . values , ] if 'rpha' in group : line . append ( group [ 'rpha' ] . values ) else : line . append ( group [ 'r' ] . values * 0.0 ) fmt = '%i %i %f %f' if store_errors : line += ( group [ 'd|Z|_[Ohm]' ] . values , group [ 'dphi_[mrad]' ] . values , ) fmt += ' %f %f' subdata = np . array ( line ) . T np . savetxt ( fid , subdata , fmt = fmt )
Save a dataset to a CRTomo - compatible . crt file
308
14
8,315
def get_label ( parameter , ptype , flavor = None , mpl = None ) : # determine flavor if flavor is not None : if flavor not in ( 'latex' , 'mathml' ) : raise Exception ( 'flavor not recognized: {}' . format ( flavor ) ) else : if mpl is None : raise Exception ( 'either the flavor or mpl must be provided' ) rendering = mpl . rcParams [ 'text.usetex' ] if rendering : flavor = 'latex' else : flavor = 'mathml' # check if the requested label is present if parameter not in labels : raise Exception ( 'parameter not known' ) if ptype not in labels [ parameter ] : raise Exception ( 'ptype not known' ) if flavor not in labels [ parameter ] [ ptype ] : raise Exception ( 'flavor not known' ) return labels [ parameter ] [ ptype ] [ flavor ]
Return the label of a given SIP parameter
198
9
8,316
def _add_labels ( self , axes , dtype ) : for ax in axes [ 1 , : ] . flat : ax . set_xlabel ( 'frequency [Hz]' ) if dtype == 'rho' : axes [ 0 , 0 ] . set_ylabel ( r'$|\rho| [\Omega m]$' ) axes [ 0 , 1 ] . set_ylabel ( r'$-\phi [mrad]$' ) axes [ 1 , 0 ] . set_ylabel ( r"$\sigma' [S/m]$" ) axes [ 1 , 1 ] . set_ylabel ( r"$\sigma'' [S/m]$" ) elif dtype == 'r' : axes [ 0 , 0 ] . set_ylabel ( r'$|R| [\Omega]$' ) axes [ 0 , 1 ] . set_ylabel ( r'$-\phi [mrad]$' ) axes [ 1 , 0 ] . set_ylabel ( r"$Y' [S]$" ) axes [ 1 , 1 ] . set_ylabel ( r"$Y'' [S]$" ) else : raise Exception ( 'dtype not known: {}' . format ( dtype ) )
Given a 2x2 array of axes add x and y labels
283
13
8,317
def add ( self , response , label = None ) : if not isinstance ( response , sip_response . sip_response ) : raise Exception ( 'can only add sip_reponse.sip_response objects' ) self . objects . append ( response ) if label is None : self . labels . append ( 'na' ) else : self . labels . append ( label )
add one response object to the list
80
7
8,318
def split_data ( data , squeeze = False ) : vdata = np . atleast_2d ( data ) nr_freqs = int ( vdata . shape [ 1 ] / 2 ) part1 = vdata [ : , 0 : nr_freqs ] part2 = vdata [ : , nr_freqs : ] if ( squeeze ) : part1 = part1 . squeeze ( ) part2 = part2 . squeeze ( ) return part1 , part2
Split 1D or 2D into two parts using the last axis
104
13
8,319
def convert ( input_format , output_format , data , one_spectrum = False ) : if input_format == output_format : return data if input_format not in from_converters : raise KeyError ( 'Input format {0} not known!' . format ( input_format ) ) if output_format not in to_converters : raise KeyError ( 'Output format {0} not known!' . format ( output_format ) ) # internally we always work with the second axis of double the frequency # size if len ( data . shape ) == 2 and data . shape [ 0 ] == 2 and one_spectrum : work_data = np . hstack ( ( data [ 0 , : ] , data [ 1 , : ] ) ) one_spec_2d = True else : work_data = data one_spec_2d = False cre , cim = from_converters [ input_format ] ( work_data ) converted_data = to_converters [ output_format ] ( cre , cim ) if one_spec_2d : part1 , part2 = split_data ( converted_data , True ) converted_data = np . vstack ( ( part1 , part2 ) ) # reshape to input size (this should only be necessary for 1D data) if len ( data . shape ) == 1 : converted_data = np . squeeze ( converted_data ) return converted_data
Convert from the given format to the requested format
309
10
8,320
def search ( self , params , standardize = False ) : resp = self . _request ( ENDPOINTS [ 'SEARCH' ] , params ) if not standardize : return resp # Standardization logic for res in resp [ 'result_data' ] : res = self . standardize ( res ) return resp
Get a list of person objects for the given search params .
68
12
8,321
def detail_search ( self , params , standardize = False ) : response = self . _request ( ENDPOINTS [ 'SEARCH' ] , params ) result_data = [ ] for person in response [ 'result_data' ] : try : detail = self . person_details ( person [ 'person_id' ] , standardize = standardize ) except ValueError : pass else : result_data . append ( detail ) response [ 'result_data' ] = result_data return response
Get a detailed list of person objects for the given search params .
108
13
8,322
def person_details ( self , person_id , standardize = False ) : resp = self . _request ( path . join ( ENDPOINTS [ 'DETAILS' ] , person_id ) ) if standardize : resp [ 'result_data' ] = [ self . standardize ( res ) for res in resp [ 'result_data' ] ] return resp
Get a detailed person object
81
5
8,323
def plot_ps_extra ( dataobj , key , * * kwargs ) : if isinstance ( dataobj , pd . DataFrame ) : df_raw = dataobj else : df_raw = dataobj . data if kwargs . get ( 'subquery' , False ) : df = df_raw . query ( kwargs . get ( 'subquery' ) ) else : df = df_raw def fancyfy ( axes , N ) : for ax in axes [ 0 : - 1 , : ] . flat : ax . set_xlabel ( '' ) for ax in axes [ : , 1 : ] . flat : ax . set_ylabel ( '' ) g = df . groupby ( 'timestep' ) N = len ( g . groups . keys ( ) ) nrx = min ( ( N , 5 ) ) nry = int ( np . ceil ( N / nrx ) ) # the sizes are heuristics [inches] sizex = nrx * 3 sizey = nry * 4 - 1 fig , axes = plt . subplots ( nry , nrx , sharex = True , sharey = True , figsize = ( sizex , sizey ) , ) axes = np . atleast_2d ( axes ) cbs = [ ] for ax , ( name , group ) in zip ( axes . flat , g ) : fig1 , axes1 , cb1 = plot_pseudosection_type2 ( group , key , ax = ax , log10 = False , cbmin = kwargs . get ( 'cbmin' , None ) , cbmax = kwargs . get ( 'cbmax' , None ) , ) cbs . append ( cb1 ) ax . set_title ( 'timestep: {0}' . format ( int ( name ) ) ) ax . xaxis . set_ticks_position ( 'bottom' ) ax . set_aspect ( 'equal' ) for cb in np . array ( cbs ) . reshape ( axes . shape ) [ : , 0 : - 1 ] . flat : cb . ax . set_visible ( False ) fancyfy ( axes , N ) fig . tight_layout ( ) return fig
Create grouped pseudoplots for one or more time steps
488
11
8,324
def twisted_absolute_path ( path , request ) : parsed = urlparse . urlparse ( request . uri ) if parsed . scheme != '' : path_parts = parsed . path . lstrip ( '/' ) . split ( '/' ) request . prepath = path_parts [ 0 : 1 ] request . postpath = path_parts [ 1 : ] path = request . prepath [ 0 ] return path , request
Hack to fix twisted not accepting absolute URIs
90
9
8,325
def _add_rhoa ( df , spacing ) : df [ 'k' ] = redaK . compute_K_analytical ( df , spacing = spacing ) df [ 'rho_a' ] = df [ 'r' ] * df [ 'k' ] if 'Zt' in df . columns : df [ 'rho_a_complex' ] = df [ 'Zt' ] * df [ 'k' ] return df
a simple wrapper to compute K factors and add rhoa
98
12
8,326
def simplify ( geoids ) : from collections import defaultdict aggregated = defaultdict ( set ) d = { } for g in geoids : if not bool ( g ) : continue av = g . allval ( ) d [ av ] = None aggregated [ av ] . add ( g ) compiled = set ( ) for k , v in aggregated . items ( ) : if len ( v ) >= 5 : compiled . add ( k ) compiled . add ( k . promote ( ) ) else : compiled |= v return compiled
Given a list of geoids reduce it to a simpler set . If there are five or more geoids at one summary level convert them to a single geoid at the higher level .
111
37
8,327
def isimplify ( geoids ) : s0 = list ( geoids ) for i in range ( 10 ) : s1 = simplify ( s0 ) if len ( s1 ) == len ( s0 ) : return s1 s0 = s1
Iteratively simplify until the set stops getting smaller .
54
10
8,328
def regenerate_thumbs ( self ) : Model = self . model instances = Model . objects . all ( ) num_instances = instances . count ( ) # Filenames are keys in here, to help avoid re-genning something that # we have already done. regen_tracker = { } counter = 1 for instance in instances : file = getattr ( instance , self . field ) if not file : print "(%d/%d) ID: %d -- Skipped -- No file" % ( counter , num_instances , instance . id ) counter += 1 continue file_name = os . path . basename ( file . name ) if regen_tracker . has_key ( file_name ) : print "(%d/%d) ID: %d -- Skipped -- Already re-genned %s" % ( counter , num_instances , instance . id , file_name ) counter += 1 continue # Keep them informed on the progress. print "(%d/%d) ID: %d -- %s" % ( counter , num_instances , instance . id , file_name ) try : fdat = file . read ( ) file . close ( ) del file . file except IOError : # Key didn't exist. print "(%d/%d) ID %d -- Error -- File missing on S3" % ( counter , num_instances , instance . id ) counter += 1 continue try : file_contents = ContentFile ( fdat ) except ValueError : # This field has no file associated with it, skip it. print "(%d/%d) ID %d -- Skipped -- No file on field)" % ( counter , num_instances , instance . id ) counter += 1 continue # Saving pumps it back through the thumbnailer, if this is a # ThumbnailField. If not, it's still pretty harmless. try : file . generate_thumbs ( file_name , file_contents ) except IOError , e : print "(%d/%d) ID %d -- Error -- Image may be corrupt)" % ( counter , num_instances , instance . id ) counter += 1 continue regen_tracker [ file_name ] = True counter += 1
Handle re - generating the thumbnails . All this involves is reading the original file then saving the same exact thing . Kind of annoying but it s simple .
478
31
8,329
def count_vowels ( text ) : count = 0 for i in text : if i . lower ( ) in config . AVRO_VOWELS : count += 1 return count
Count number of occurrences of vowels in a given string
40
11
8,330
def count_consonants ( text ) : count = 0 for i in text : if i . lower ( ) in config . AVRO_CONSONANTS : count += 1 return count
Count number of occurrences of consonants in a given string
41
11
8,331
def _pseudodepths_wenner ( configs , spacing = 1 , grid = None ) : if grid is None : xpositions = ( configs - 1 ) * spacing else : xpositions = grid . get_electrode_positions ( ) [ configs - 1 , 0 ] z = np . abs ( np . max ( xpositions , axis = 1 ) - np . min ( xpositions , axis = 1 ) ) * - 0.11 x = np . mean ( xpositions , axis = 1 ) return x , z
Given distances between electrodes compute Wenner pseudo depths for the provided configuration
121
13
8,332
def plot_pseudodepths ( configs , nr_electrodes , spacing = 1 , grid = None , ctypes = None , dd_merge = False , * * kwargs ) : # for each configuration type we have different ways of computing # pseudodepths pseudo_d_functions = { 'dd' : _pseudodepths_dd_simple , 'schlumberger' : _pseudodepths_schlumberger , 'wenner' : _pseudodepths_wenner , } titles = { 'dd' : 'dipole-dipole configurations' , 'schlumberger' : 'Schlumberger configurations' , 'wenner' : 'Wenner configurations' , } # sort the configurations into the various types of configurations only_types = ctypes or [ 'dd' , ] results = fT . filter ( configs , settings = { 'only_types' : only_types , } ) # loop through all measurement types figs = [ ] axes = [ ] for key in sorted ( results . keys ( ) ) : print ( 'plotting: ' , key ) if key == 'not_sorted' : continue index_dict = results [ key ] # it is possible that we want to generate multiple plots for one # type of measurement, i.e., to separate skips of dipole-dipole # measurements. Therefore we generate two lists: # 1) list of list of indices to plot # 2) corresponding labels if key == 'dd' and not dd_merge : plot_list = [ ] labels_add = [ ] for skip in sorted ( index_dict . keys ( ) ) : plot_list . append ( index_dict [ skip ] ) labels_add . append ( ' - skip {0}' . format ( skip ) ) else : # merge all indices plot_list = [ np . hstack ( index_dict . values ( ) ) , ] print ( 'schlumberger' , plot_list ) labels_add = [ '' , ] grid = None # generate plots for indices , label_add in zip ( plot_list , labels_add ) : if len ( indices ) == 0 : continue ddc = configs [ indices ] px , pz = pseudo_d_functions [ key ] ( ddc , spacing , grid ) fig , ax = plt . subplots ( figsize = ( 15 / 2.54 , 5 / 2.54 ) ) ax . scatter ( px , pz , color = 'k' , alpha = 0.5 ) # plot electrodes if grid is not None : electrodes = grid . get_electrode_positions ( ) ax . scatter ( electrodes [ : , 0 ] , electrodes [ : , 1 ] , color = 'b' , label = 'electrodes' , ) else : ax . scatter ( np . arange ( 0 , nr_electrodes ) * spacing , np . zeros ( nr_electrodes ) , color = 'b' , label = 'electrodes' , ) ax . set_title ( titles [ key ] + label_add ) ax . set_aspect ( 'equal' ) ax . set_xlabel ( 'x [m]' ) ax . set_ylabel ( 'x [z]' ) fig . tight_layout ( ) figs . append ( fig ) axes . append ( ax ) if len ( figs ) == 1 : return figs [ 0 ] , axes [ 0 ] else : return figs , axes
Plot pseudodepths for the measurements . If grid is given then the actual electrode positions are used and the parameter spacing is ignored
765
26
8,333
def matplot ( x , y , z , ax = None , colorbar = True , * * kwargs ) : xmin = x . min ( ) xmax = x . max ( ) dx = np . abs ( x [ 0 , 1 ] - x [ 0 , 0 ] ) ymin = y . min ( ) ymax = y . max ( ) dy = np . abs ( y [ 1 , 0 ] - y [ 0 , 0 ] ) x2 , y2 = np . meshgrid ( np . arange ( xmin , xmax + 2 * dx , dx ) - dx / 2. , np . arange ( ymin , ymax + 2 * dy , dy ) - dy / 2. ) if not ax : fig , ax = plt . subplots ( ) else : fig = ax . figure im = ax . pcolormesh ( x2 , y2 , z , * * kwargs ) ax . axis ( [ x2 . min ( ) , x2 . max ( ) , y2 . min ( ) , y2 . max ( ) ] ) ax . set_xticks ( np . arange ( xmin , xmax + dx , dx ) ) ax . set_yticks ( np . arange ( ymin , ymax + dx , dy ) ) if colorbar : cbar = fig . colorbar ( im , ax = ax ) else : cbar = None return ax , cbar
Plot x y z as expected with correct axis labels .
310
11
8,334
def summary ( self ) : return "\n" . join ( [ "Transaction:" , " When: " + self . date . strftime ( "%a %d %b %Y" ) , " Description: " + self . desc . replace ( '\n' , ' ' ) , " For amount: {}" . format ( self . amount ) , " From: {}" . format ( ", " . join ( map ( lambda x : x . account , self . src ) ) if self . src else "UNKNOWN" ) , " To: {}" . format ( ", " . join ( map ( lambda x : x . account , self . dst ) ) if self . dst else "UNKNOWN" ) , "" ] )
Return a string summary of transaction
154
6
8,335
def check ( self ) : if not self . date : raise XnDataError ( "Missing date" ) if not self . desc : raise XnDataError ( "Missing description" ) if not self . dst : raise XnDataError ( "No destination accounts" ) if not self . src : raise XnDataError ( "No source accounts" ) if not self . amount : raise XnDataError ( "No transaction amount" )
Check this transaction for completeness
94
6
8,336
def balance ( self ) : self . check ( ) if not sum ( map ( lambda x : x . amount , self . src ) ) == - self . amount : raise XnBalanceError ( "Sum of source amounts " "not equal to transaction amount" ) if not sum ( map ( lambda x : x . amount , self . dst ) ) == self . amount : raise XnBalanceError ( "Sum of destination amounts " "not equal to transaction amount" ) return True
Check this transaction for correctness
100
5
8,337
def match_rules ( self , rules ) : try : self . check ( ) return None except XnDataError : pass scores = { } for r in rules : outcomes = r . match ( self ) if not outcomes : continue for outcome in outcomes : if isinstance ( outcome , rule . SourceOutcome ) : key = 'src' elif isinstance ( outcome , rule . DestinationOutcome ) : key = 'dst' elif isinstance ( outcome , rule . DescriptionOutcome ) : key = 'desc' elif isinstance ( outcome , rule . DropOutcome ) : key = 'drop' elif isinstance ( outcome , rule . RebateOutcome ) : key = 'rebate' else : raise KeyError if key not in scores : scores [ key ] = score . ScoreSet ( ) # initialise ScoreSet scores [ key ] . append ( ( outcome . value , outcome . score ) ) return scores
Process this transaction against the given ruleset
196
8
8,338
def complete ( self , uio , dropped = False ) : if self . dropped and not dropped : # do nothing for dropped xn, unless specifically told to return for end in [ 'src' , 'dst' ] : if getattr ( self , end ) : continue # we have this information uio . show ( '\nEnter ' + end + ' for transaction:' ) uio . show ( '' ) uio . show ( self . summary ( ) ) try : endpoints = [ ] remaining = self . amount while remaining : account = uio . text ( ' Enter account' , None ) amount = uio . decimal ( ' Enter amount' , default = remaining , lower = 0 , upper = remaining ) endpoints . append ( Endpoint ( account , amount ) ) remaining = self . amount - sum ( map ( lambda x : x . amount , endpoints ) ) except ui . RejectWarning : # bail out sys . exit ( "bye!" ) # flip amounts if it was a src outcome if end == 'src' : endpoints = map ( lambda x : Endpoint ( x . account , - x . amount ) , endpoints ) # set endpoints setattr ( self , end , endpoints )
Query for all missing information in the transaction
259
8
8,339
def process ( self , rules , uio , prevxn = None ) : self . apply_outcomes ( self . match_rules ( rules ) , uio , prevxn = prevxn )
Matches rules and applies outcomes
44
6
8,340
def plot_quadpole_evolution ( dataobj , quadpole , cols , threshold = 5 , rolling = False , ax = None ) : if isinstance ( dataobj , pd . DataFrame ) : df = dataobj else : df = dataobj . data subquery = df . query ( 'a == {0} and b == {1} and m == {2} and n == {3}' . format ( * quadpole ) ) # rhoa = subquery['rho_a'].values # rhoa[30] = 300 # subquery['rho_a'] = rhoa if ax is not None : fig = ax . get_figure ( ) else : fig , ax = plt . subplots ( 1 , 1 , figsize = ( 20 / 2.54 , 7 / 2.54 ) ) ax . plot ( subquery [ 'timestep' ] , subquery [ cols ] , '.' , color = 'blue' , label = 'valid data' , ) if rolling : # rolling mean rolling_m = subquery . rolling ( 3 , center = True , min_periods = 1 ) . median ( ) ax . plot ( rolling_m [ 'timestep' ] . values , rolling_m [ 'rho_a' ] . values , '-' , label = 'rolling median' , ) ax . fill_between ( rolling_m [ 'timestep' ] . values , rolling_m [ 'rho_a' ] . values * ( 1 - threshold ) , rolling_m [ 'rho_a' ] . values * ( 1 + threshold ) , alpha = 0.4 , color = 'blue' , label = '{0}\% confidence region' . format ( threshold * 100 ) , ) # find all values that deviate by more than X percent from the # rolling_m bad_values = ( np . abs ( np . abs ( subquery [ 'rho_a' ] . values - rolling_m [ 'rho_a' ] . values ) / rolling_m [ 'rho_a' ] . values ) > threshold ) bad = subquery . loc [ bad_values ] ax . plot ( bad [ 'timestep' ] . values , bad [ 'rho_a' ] . values , '.' , # s=15, color = 'r' , label = 'discarded data' , ) ax . legend ( loc = 'upper center' , fontsize = 6 ) # ax.set_xlim(10, 20) ax . set_ylabel ( r'$\rho_a$ [$\Omega$m]' ) ax . set_xlabel ( 'timestep' ) return fig , ax
Visualize time - lapse evolution of a single quadropole .
592
13
8,341
def visitSenseFlags ( self , ctx : ShExDocParser . SenseFlagsContext ) : if '!' in ctx . getText ( ) : self . expression . negated = True if '^' in ctx . getText ( ) : self . expression . inverse = True
! ^ ? | ^ ! ?
60
7
8,342
def as_tuple ( self ) : if self . _tuple is None : # extract leading digits from year year = 9999 if self . year : m = self . DIGITS . match ( self . year ) if m : year = int ( m . group ( 0 ) ) month = self . month_num or 99 day = self . day if self . day is not None else 99 # should we include calendar name in tuple too? self . _tuple = year , month , day return self . _tuple
Date as three - tuple of numbers
111
7
8,343
def _cmp_date ( self ) : dates = sorted ( val for val in self . kw . values ( ) if isinstance ( val , CalendarDate ) ) if dates : return dates [ 0 ] # return date very far in the future return CalendarDate ( )
Returns Calendar date used for comparison .
56
7
8,344
def better_sentences ( func ) : @ wraps ( func ) def wrapped ( * args ) : sentences = func ( * args ) new_sentences = [ ] for i , l in enumerate ( sentences ) : if '\n\n' in l : splits = l . split ( '\n\n' ) if len ( splits ) > 1 : for ind , spl in enumerate ( splits ) : if len ( spl ) < 20 : #if DEBUG: print "Discarding: ", spl del splits [ ind ] new_sentences . extend ( splits ) else : new_sentences . append ( l ) return new_sentences return wrapped
takes care of some edge cases of sentence tokenization for cases when websites don t close sentences properly usually after blockquotes image captions or attributions
139
31
8,345
def __we_c ( cls , calib , tc , temp , we_v ) : offset_v = calib . pid_elc_mv / 1000.0 response_v = we_v - offset_v # remove electronic zero response_c = tc . correct ( temp , response_v ) # correct the response component if response_c is None : return None we_c = response_c + offset_v # replace electronic zero return we_c
Compute weC from sensor temperature compensation of weV
99
11
8,346
def __cnc ( cls , calib , we_c ) : if we_c is None : return None offset_v = calib . pid_elc_mv / 1000.0 response_c = we_c - offset_v # remove electronic zero cnc = response_c / calib . pid_sens_mv # pid_sens_mv set for ppb or ppm - see PID.init() return cnc
Compute cnc from weC
95
7
8,347
def add_to_class ( self , model_class ) : model_class . _meta . add_field ( self ) setattr ( model_class , self . name , _FieldDescriptor ( self ) )
Replace the Field attribute with a named _FieldDescriptor .
47
14
8,348
def add_field ( self , field ) : self . remove_field ( field . name ) self . _fields [ field . name ] = field if field . default is not None : if six . callable ( field . default ) : self . _default_callables [ field . key ] = field . default else : self . _defaults [ field . key ] = field . default
Add the received field to the model .
82
8
8,349
def remove_field ( self , field_name ) : field = self . _fields . pop ( field_name , None ) if field is not None and field . default is not None : if six . callable ( field . default ) : self . _default_callables . pop ( field . key , None ) else : self . _defaults . pop ( field . key , None )
Remove the field with the received field name from model .
83
11
8,350
def get_defaults ( self ) : defaults = self . _defaults . copy ( ) for field_key , default in self . _default_callables . items ( ) : defaults [ field_key ] = default ( ) return defaults
Get a dictionary that contains all the available defaults .
51
10
8,351
def speak ( self , textstr , lang = 'en-US' , gender = 'female' , format = 'riff-16khz-16bit-mono-pcm' ) : # print("speak(textstr=%s, lang=%s, gender=%s, format=%s)" % (textstr, lang, gender, format)) concatkey = '%s-%s-%s-%s' % ( textstr , lang . lower ( ) , gender . lower ( ) , format ) key = self . tts_engine + '' + str ( hash ( concatkey ) ) self . filename = '%s-%s.mp3' % ( key , lang ) # check if file exists fileloc = self . directory + self . filename if self . cache and os . path . isfile ( self . directory + self . filename ) : return self . filename else : with open ( fileloc , 'wb' ) as f : self . speech . speak_to_file ( f , textstr , lang , gender , format ) return self . filename return False
Run will call Microsoft Translate API and and produce audio
238
11
8,352
def call ( args ) : b = StringIO ( ) p = subprocess . Popen ( args , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) encoding = getattr ( sys . stdout , 'encoding' , None ) or 'utf-8' # old python has bug in p.stdout, so the following little # hack is required. for stdout in iter ( p . stdout . readline , '' ) : if len ( stdout ) == 0 : break # translate non unicode to unicode stdout = force_unicode ( stdout , encoding ) # StringIO store unicode b . write ( stdout ) # stdout require non unicode sys . stdout . write ( from_unicode ( stdout , encoding ) ) sys . stdout . flush ( ) buf = b . getvalue ( ) p . stdout . close ( ) return p . returncode or 0 , buf
Call terminal command and return exit_code and stdout
204
11
8,353
def get_command_str ( args ) : single_quote = "'" double_quote = '"' for i , value in enumerate ( args ) : if " " in value and double_quote not in value : args [ i ] = '"%s"' % value elif " " in value and single_quote not in value : args [ i ] = "'%s'" % value return " " . join ( args )
Get terminal command string from list of command and arguments
91
10
8,354
def receive_data_chunk ( self , raw_data , start ) : self . file . write ( raw_data ) # CHANGED: This un-hangs us long enough to keep things rolling. eventlet . sleep ( 0 )
Over - ridden method to circumvent the worker timeouts on large uploads .
52
15
8,355
def stoptimes ( self , start_date , end_date ) : params = { 'start' : self . format_date ( start_date ) , 'end' : self . format_date ( end_date ) } response = self . _request ( ENDPOINTS [ 'STOPTIMES' ] , params ) return response
Return all stop times in the date range
74
8
8,356
def setup_logger ( self ) : self . log_list = [ ] handler = ListHandler ( self . log_list ) formatter = logging . Formatter ( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) handler . setFormatter ( formatter ) logger = logging . getLogger ( ) logger . addHandler ( handler ) logger . setLevel ( logging . INFO ) self . handler = handler self . logger = logger
Setup a logger
109
3
8,357
def match_to_dict ( match ) : balance , indent , account_fragment = match . group ( 1 , 2 , 3 ) return { 'balance' : decimal . Decimal ( balance ) , 'indent' : len ( indent ) , 'account_fragment' : account_fragment , 'parent' : None , 'children' : [ ] , }
Convert a match object into a dict .
82
9
8,358
def balance ( output ) : lines = map ( pattern . search , output . splitlines ( ) ) stack = [ ] top = [ ] for item in map ( match_to_dict , itertools . takewhile ( lambda x : x , lines ) ) : # pop items off stack while current item has indent <= while stack and item [ 'indent' ] <= stack [ - 1 ] [ 'indent' ] : stack . pop ( ) # check if this is a top-level item if not stack : stack . append ( item ) top . append ( item ) else : item [ 'parent' ] = stack [ - 1 ] stack [ - 1 ] [ 'children' ] . append ( item ) stack . append ( item ) return top
Convert ledger balance output into an hierarchical data structure .
158
11
8,359
def is_punctuation ( text ) : return not ( text . lower ( ) in config . AVRO_VOWELS or text . lower ( ) in config . AVRO_CONSONANTS )
Check if given string is a punctuation
46
8
8,360
def is_exact ( needle , haystack , start , end , matchnot ) : return ( ( start >= 0 and end < len ( haystack ) and haystack [ start : end ] == needle ) ^ matchnot )
Check exact occurrence of needle in haystack
48
8
8,361
def fix_string_case ( text ) : fixed = [ ] for i in text : if is_case_sensitive ( i ) : fixed . append ( i ) else : fixed . append ( i . lower ( ) ) return '' . join ( fixed )
Converts case - insensitive characters to lower case
54
9
8,362
def _crmod_to_abmn ( self , configs ) : A = configs [ : , 0 ] % 1e4 B = np . floor ( configs [ : , 0 ] / 1e4 ) . astype ( int ) M = configs [ : , 1 ] % 1e4 N = np . floor ( configs [ : , 1 ] / 1e4 ) . astype ( int ) ABMN = np . hstack ( ( A [ : , np . newaxis ] , B [ : , np . newaxis ] , M [ : , np . newaxis ] , N [ : , np . newaxis ] ) ) . astype ( int ) return ABMN
convert crmod - style configurations to a Nx4 array
149
13
8,363
def load_crmod_config ( self , filename ) : with open ( filename , 'r' ) as fid : nr_of_configs = int ( fid . readline ( ) . strip ( ) ) configs = np . loadtxt ( fid ) print ( 'loaded configs:' , configs . shape ) if nr_of_configs != configs . shape [ 0 ] : raise Exception ( 'indicated number of measurements does not equal ' + 'to actual number of measurements' ) ABMN = self . _crmod_to_abmn ( configs [ : , 0 : 2 ] ) self . configs = ABMN
Load a CRMod configuration file
139
6
8,364
def _get_crmod_abmn ( self ) : ABMN = np . vstack ( ( self . configs [ : , 0 ] * 1e4 + self . configs [ : , 1 ] , self . configs [ : , 2 ] * 1e4 + self . configs [ : , 3 ] , ) ) . T . astype ( int ) return ABMN
return a Nx2 array with the measurement configurations formatted CRTomo style
83
15
8,365
def write_crmod_volt ( self , filename , mid ) : ABMN = self . _get_crmod_abmn ( ) if isinstance ( mid , ( list , tuple ) ) : mag_data = self . measurements [ mid [ 0 ] ] pha_data = self . measurements [ mid [ 1 ] ] else : mag_data = self . measurements [ mid ] pha_data = np . zeros ( mag_data . shape ) all_data = np . hstack ( ( ABMN , mag_data [ : , np . newaxis ] , pha_data [ : , np . newaxis ] ) ) with open ( filename , 'wb' ) as fid : fid . write ( bytes ( '{0}\n' . format ( ABMN . shape [ 0 ] ) , 'utf-8' , ) ) np . savetxt ( fid , all_data , fmt = '%i %i %f %f' )
Write the measurements to the output file in the volt . dat file format that can be read by CRTomo .
205
23
8,366
def write_crmod_config ( self , filename ) : ABMN = self . _get_crmod_abmn ( ) with open ( filename , 'wb' ) as fid : fid . write ( bytes ( '{0}\n' . format ( ABMN . shape [ 0 ] ) , 'utf-8' , ) ) np . savetxt ( fid , ABMN . astype ( int ) , fmt = '%i %i' )
Write the configurations to a configuration file in the CRMod format All configurations are merged into one previor to writing to file
97
24
8,367
def gen_dipole_dipole ( self , skipc , skipv = None , stepc = 1 , stepv = 1 , nr_voltage_dipoles = 10 , before_current = False , start_skip = 0 , N = None ) : if N is None and self . nr_electrodes is None : raise Exception ( 'You must provide the number of electrodes' ) elif N is None : N = self . nr_electrodes # by default, current voltage dipoles have the same size if skipv is None : skipv = skipc configs = [ ] # current dipoles for a in range ( 0 , N - skipv - skipc - 3 , stepc ) : b = a + skipc + 1 nr = 0 # potential dipoles before current injection if before_current : for n in range ( a - start_skip - 1 , - 1 , - stepv ) : nr += 1 if nr > nr_voltage_dipoles : continue m = n - skipv - 1 if m < 0 : continue quadpole = np . array ( ( a , b , m , n ) ) + 1 configs . append ( quadpole ) # potential dipoles after current injection nr = 0 for m in range ( b + start_skip + 1 , N - skipv - 1 , stepv ) : nr += 1 if nr > nr_voltage_dipoles : continue n = m + skipv + 1 quadpole = np . array ( ( a , b , m , n ) ) + 1 configs . append ( quadpole ) configs = np . array ( configs ) # now add to the instance if self . configs is None : self . configs = configs else : self . configs = np . vstack ( ( self . configs , configs ) ) return configs
Generate dipole - dipole configurations
408
8
8,368
def gen_gradient ( self , skip = 0 , step = 1 , vskip = 0 , vstep = 1 ) : N = self . nr_electrodes quadpoles = [ ] for a in range ( 1 , N - skip , step ) : b = a + skip + 1 for m in range ( a + 1 , b - vskip - 1 , vstep ) : n = m + vskip + 1 quadpoles . append ( ( a , b , m , n ) ) configs = np . array ( quadpoles ) if configs . size == 0 : return None self . add_to_configs ( configs ) return configs
Generate gradient measurements
146
4
8,369
def remove_duplicates ( self , configs = None ) : if configs is None : c = self . configs else : c = configs struct = c . view ( c . dtype . descr * 4 ) configs_unique = np . unique ( struct ) . view ( c . dtype ) . reshape ( - 1 , 4 ) if configs is None : self . configs = configs_unique else : return configs_unique
remove duplicate entries from 4 - point configurations . If no configurations are provided then use self . configs . Unique configurations are only returned if configs is not None .
99
33
8,370
def gen_schlumberger ( self , M , N , a = None ) : if a is None : a = np . abs ( M - N ) nr_of_steps_left = int ( min ( M , N ) - 1 / a ) nr_of_steps_right = int ( ( self . nr_electrodes - max ( M , N ) ) / a ) configs = [ ] for i in range ( 0 , min ( nr_of_steps_left , nr_of_steps_right ) ) : A = min ( M , N ) - ( i + 1 ) * a B = max ( M , N ) + ( i + 1 ) * a configs . append ( ( A , B , M , N ) ) configs = np . array ( configs ) self . add_to_configs ( configs ) return configs
generate one Schlumberger sounding configuration that is one set of configurations for one potential dipole MN .
193
21
8,371
def add_to_configs ( self , configs ) : if len ( configs ) == 0 : return None if self . configs is None : self . configs = np . atleast_2d ( configs ) else : configs = np . atleast_2d ( configs ) self . configs = np . vstack ( ( self . configs , configs ) ) return self . configs
Add one or more measurement configurations to the stored configurations
92
10
8,372
def split_into_normal_and_reciprocal ( self , pad = False , return_indices = False ) : # for simplicity, we create an array where AB and MN are sorted configs = np . hstack ( ( np . sort ( self . configs [ : , 0 : 2 ] , axis = 1 ) , np . sort ( self . configs [ : , 2 : 4 ] , axis = 1 ) ) ) ab_min = configs [ : , 0 ] mn_min = configs [ : , 2 ] # rule 1 indices_normal = np . where ( ab_min < mn_min ) [ 0 ] # now look for reciprocals indices_used = [ ] normal = [ ] normal_indices = [ ] reciprocal_indices = [ ] reciprocal = [ ] duplicates = [ ] for index in indices_normal : indices_used . append ( index ) normal . append ( self . configs [ index , : ] ) normal_indices . append ( index ) # look for reciprocal configuration index_rec = np . where ( # A == M, B == N, M == A, N == B ( configs [ : , 0 ] == configs [ index , 2 ] ) & ( configs [ : , 1 ] == configs [ index , 3 ] ) & ( configs [ : , 2 ] == configs [ index , 0 ] ) & ( configs [ : , 3 ] == configs [ index , 1 ] ) ) [ 0 ] if len ( index_rec ) == 0 and pad : reciprocal . append ( np . ones ( 4 ) * np . nan ) elif len ( index_rec ) == 1 : reciprocal . append ( self . configs [ index_rec [ 0 ] , : ] ) indices_used . append ( index_rec [ 0 ] ) reciprocal_indices . append ( index_rec [ 0 ] ) elif len ( index_rec > 1 ) : # take the first one reciprocal . append ( self . configs [ index_rec [ 0 ] , : ] ) reciprocal_indices . append ( index_rec [ 0 ] ) duplicates += list ( index_rec [ 1 : ] ) indices_used += list ( index_rec ) # now determine all reciprocal-only parameters set_all_indices = set ( list ( range ( 0 , configs . shape [ 0 ] ) ) ) set_used_indices = set ( indices_used ) reciprocal_only_indices = set_all_indices - set_used_indices for index in reciprocal_only_indices : if pad : normal . append ( np . ones ( 4 ) * np . nan ) reciprocal . append ( self . configs [ index , : ] ) normals = np . array ( normal ) reciprocals = np . array ( reciprocal ) if return_indices : return normals , reciprocals , normal_indices , reciprocal_indices else : return normals , reciprocals
Split the stored configurations into normal and reciprocal measurements
632
9
8,373
def gen_reciprocals ( self , append = False ) : # Switch AB and MN reciprocals = self . configs . copy ( ) [ : , : : - 1 ] reciprocals [ : , 0 : 2 ] = np . sort ( reciprocals [ : , 0 : 2 ] , axis = 1 ) reciprocals [ : , 2 : 4 ] = np . sort ( reciprocals [ : , 2 : 4 ] , axis = 1 ) # # Sort by current dipoles ind = np . lexsort ( ( reciprocals [ : , 3 ] , reciprocals [ : , 2 ] , reciprocals [ : , 1 ] , reciprocals [ : , 0 ] ) ) reciprocals = reciprocals [ ind ] if append : self . configs = np . vstack ( ( self . configs , reciprocals ) ) return reciprocals
Generate reciprocal configurations sort by AB and optionally append to configurations .
177
13
8,374
def gen_configs_permutate ( self , injections_raw , only_same_dipole_length = False , ignore_crossed_dipoles = False , silent = False ) : injections = np . atleast_2d ( injections_raw ) . astype ( int ) N = injections . shape [ 0 ] measurements = [ ] for injection in range ( 0 , N ) : dipole_length = np . abs ( injections [ injection ] [ 1 ] - injections [ injection ] [ 0 ] ) # select all dipole EXCEPT for the injection dipole for i in set ( range ( 0 , N ) ) - set ( [ injection ] ) : test_dipole_length = np . abs ( injections [ i , : ] [ 1 ] - injections [ i , : ] [ 0 ] ) if ( only_same_dipole_length and test_dipole_length != dipole_length ) : continue quadpole = np . array ( [ injections [ injection , : ] , injections [ i , : ] ] ) . flatten ( ) if ignore_crossed_dipoles is True : # check if we need to ignore this dipole # Note: this could be wrong if electrode number are not # ascending! if ( quadpole [ 2 ] > quadpole [ 0 ] and quadpole [ 2 ] < quadpole [ 1 ] ) : if not silent : print ( 'A - ignoring' , quadpole ) elif ( quadpole [ 3 ] > quadpole [ 0 ] and quadpole [ 3 ] < quadpole [ 1 ] ) : if not silent : print ( 'B - ignoring' , quadpole ) else : measurements . append ( quadpole ) else : # add very quadpole measurements . append ( quadpole ) # check and remove double use of electrodes filtered = [ ] for quadpole in measurements : if ( not set ( quadpole [ 0 : 2 ] ) . isdisjoint ( set ( quadpole [ 2 : 4 ] ) ) ) : if not silent : print ( 'Ignoring quadrupole because of ' , 'repeated electrode use:' , quadpole ) else : filtered . append ( quadpole ) self . add_to_configs ( filtered ) return np . array ( filtered )
Create measurement configurations out of a pool of current injections . Use only the provided dipoles for potential dipole selection . This means that we have always reciprocal measurements .
479
32
8,375
def remove_max_dipole_sep ( self , maxsep = 10 ) : sep = np . abs ( self . configs [ : , 1 ] - self . configs [ : , 2 ] ) self . configs = self . configs [ sep <= maxsep ]
Remove configurations with dipole separations higher than maxsep .
63
13
8,376
def to_pg_scheme ( self , container = None , positions = None ) : if container is None and positions is None : raise Exception ( 'electrode positions are required for BERT export' ) if container is not None and container . electrodes is None : raise Exception ( 'container does not contain electrode positions' ) if container is not None and positions is not None : raise Exception ( 'only one of container OR positions must be provided' ) if container is not None : elec_positions = container . electrodes . values elif positions is not None : elec_positions = positions opt_import ( "pybert" , requiredFor = "" ) import pybert # Initialize BERT DataContainer data = pybert . DataContainerERT ( ) # Define electrodes (48 electrodes spaced by 0.5 m) for nr , ( x , y , z ) in enumerate ( elec_positions ) : data . createSensor ( ( x , y , z ) ) # Define number of measurements data . resize ( self . configs . shape [ 0 ] ) for index , token in enumerate ( "abmn" ) : data . set ( token , self . configs [ : , index ] . tolist ( ) ) # account for zero indexing for token in "abmn" : data . set ( token , data ( token ) - 1 ) # np.vstack([data.get(x).array() for x in ("abmn")]).T return data
Convert the configuration to a pygimli measurement scheme
315
12
8,377
def to_iris_syscal ( self , filename ) : with open ( filename , 'w' ) as fid : # fprintf(fod, '#\t X\t Y\t Z\n'); fid . write ( '#\t X\t Y\t Z\n' ) # fprintf(fod, '%d\t %.1f\t %d\t %d\n', D'); # loop over electrodes and assign increasing x-positions # TODO: use proper electrode positions, if available for nr in range ( 0 , self . configs . max ( ) ) : fid . write ( '{} {} 0 0\n' . format ( nr + 1 , nr ) ) # fprintf(fod, '#\t A\t B\t M\t N\n'); fid . write ( '#\t A\t B\t M\t N\n' ) # fprintf(fod, '%d\t %d\t %d\t %d\t %d\n', C'); for nr , config in enumerate ( self . configs ) : fid . write ( '{} {} {} {} {}\n' . format ( nr + 1 , * config ) )
Export to IRIS Instrument configuration file
277
7
8,378
def create_plan ( self , * , plan_code , description , interval , interval_count , max_payments_allowed , payment_attempts_delay , plan_value , plan_tax , plan_tax_return_base , currency , max_payment_attempts = None , max_pending_payments = None , trial_days = None ) : payload = { "accountId" : self . client . account_id , "planCode" : plan_code , "description" : description , "interval" : interval , "intervalCount" : interval_count , "maxPaymentsAllowed" : max_payments_allowed , "paymentAttemptsDelay" : payment_attempts_delay , "additionalValues" : [ { "name" : "PLAN_VALUE" , "value" : plan_value , "currency" : currency } , { "name" : "PLAN_TAX" , "value" : plan_tax , "currency" : currency } , { "name" : "PLAN_TAX_RETURN_BASE" , "value" : plan_tax_return_base , "currency" : currency } ] , "maxPaymentAttempts" : max_payment_attempts , "maxPendingPayments" : max_pending_payments , "trialDays" : trial_days } return self . client . _post ( self . url + 'plans' , json = payload , headers = self . get_headers ( ) )
Creating a new plan for subscriptions associated with the merchant .
331
11
8,379
def get_plan ( self , plan_code ) : return self . client . _get ( self . url + 'plans/{}' . format ( plan_code ) , headers = self . get_headers ( ) )
Check all the information of a plan for subscriptions associated with the merchant .
49
14
8,380
def delete_plan ( self , plan_code ) : return self . client . _delete ( self . url + 'plans/{}' . format ( plan_code ) , headers = self . get_headers ( ) )
Delete an entire subscription plan associated with the merchant .
49
10
8,381
def create_customer ( self , * , full_name , email ) : payload = { "fullName" : full_name , "email" : email } return self . client . _post ( self . url + 'customers' , json = payload , headers = self . get_headers ( ) )
Creation of a customer in the system .
66
9
8,382
def get_customer ( self , customer_id ) : return self . client . _get ( self . url + 'customers/{}' . format ( customer_id ) , headers = self . get_headers ( ) )
Queries the information related to the customer .
50
9
8,383
def delete_customer ( self , customer_id ) : return self . client . _delete ( self . url + 'customers/{}' . format ( customer_id ) , headers = self . get_headers ( ) )
Removes a user from the system .
50
8
8,384
def create_subscription ( self , * , customer_id , credit_card_token , plan_code , quantity = None , installments = None , trial_days = None , immediate_payment = None , extra1 = None , extra2 = None , delivery_address = None , notify_url = None , recurring_bill_items = None ) : payload = { "quantity" : quantity , "installments" : installments , "trialDays" : trial_days , "immediatePayment" : immediate_payment , "extra1" : extra1 , "extra2" : extra2 , "customer" : { "id" : customer_id , "creditCards" : [ { "token" : credit_card_token } ] } , "plan" : { "planCode" : plan_code } , "deliveryAddress" : delivery_address , "notifyUrl" : notify_url , "recurringBillItems" : recurring_bill_items } return self . client . _post ( self . url + 'subscriptions' , json = payload , headers = self . get_headers ( ) )
Creating a new subscription of a client to a plan .
243
11
8,385
def get_subscription ( self , subscription_id ) : return self . client . _put ( self . url + 'subscriptions/{}' . format ( subscription_id ) , headers = self . get_headers ( ) )
Check the basic information associated with the specified subscription .
51
10
8,386
def update_subscription ( self , * , subscription_id , credit_card_token ) : payload = { "creditCardToken" : credit_card_token } fmt = 'subscriptions/{}' . format ( subscription_id ) return self . client . _put ( self . url + fmt , json = payload , headers = self . get_headers ( ) )
Update information associated with the specified subscription . At the moment it is only possible to update the token of the credit card to which the charge of the subscription is made .
81
33
8,387
def delete_subscription ( self , subscription_id ) : return self . client . _delete ( self . url + 'subscriptions/{}' . format ( subscription_id ) , headers = self . get_headers ( ) )
Unsubscribe delete the relationship of the customer with the plan .
51
13
8,388
def create_additional_charge ( self , * , subscription_id , description , plan_value , plan_tax , plan_tax_return_base , currency ) : payload = { "description" : description , "additionalValues" : [ { "name" : "ITEM_VALUE" , "value" : plan_value , "currency" : currency } , { "name" : "ITEM_TAX" , "value" : plan_tax , "currency" : currency } , { "name" : "ITEM_TAX_RETURN_BASE" , "value" : plan_tax_return_base , "currency" : currency } ] } fmt = 'subscriptions/{}/recurringBillItems' . format ( subscription_id ) return self . client . _post ( self . url + fmt , json = payload , headers = self . get_headers ( ) )
Adds extra charges to the respective invoice for the current period .
197
12
8,389
def get_additional_charge_by_identifier ( self , recurring_billing_id ) : fmt = 'recurringBillItems/{}' . format ( recurring_billing_id ) return self . client . _get ( self . url + fmt , headers = self . get_headers ( ) )
Query extra charge information of an invoice from its identifier .
68
11
8,390
def update_additional_charge ( self , * , recurring_billing_id , description , plan_value , plan_tax , plan_tax_return_base , currency ) : payload = { "description" : description , "additionalValues" : [ { "name" : "ITEM_VALUE" , "value" : plan_value , "currency" : currency } , { "name" : "ITEM_TAX" , "value" : plan_tax , "currency" : currency } , { "name" : "ITEM_TAX_RETURN_BASE" , "value" : plan_tax_return_base , "currency" : currency } ] } fmt = 'recurringBillItems/{}' . format ( recurring_billing_id ) return self . client . _put ( self . url + fmt , payload = payload , headers = self . get_headers ( ) )
Updates the information from an additional charge in an invoice .
199
12
8,391
def delete_additional_charge ( self , recurring_billing_id ) : fmt = 'recurringBillItems/{}' . format ( recurring_billing_id ) return self . client . _delete ( self . url + fmt , headers = self . get_headers ( ) )
Remove an extra charge from an invoice .
63
8
8,392
def thumbnail ( parser , token ) : args = token . split_contents ( ) tag = args [ 0 ] # Check to see if we're setting to a context variable. if len ( args ) > 4 and args [ - 2 ] == 'as' : context_name = args [ - 1 ] args = args [ : - 2 ] else : context_name = None if len ( args ) < 3 : raise TemplateSyntaxError ( "Invalid syntax. Expected " "'{%% %s source size [option1 option2 ...] %%}' or " "'{%% %s source size [option1 option2 ...] as variable %%}'" % ( tag , tag ) ) # Get the source image path and requested size. source_var = args [ 1 ] # If the size argument was a correct static format, wrap it in quotes so # that it is compiled correctly. m = REGEXP_THUMB_SIZES . match ( args [ 2 ] ) if m : args [ 2 ] = '"%s"' % args [ 2 ] size_var = args [ 2 ] # Get the options. args_list = split_args ( args [ 3 : ] ) . items ( ) # Check the options. opts = { } kwargs = { } # key,values here override settings and defaults for arg , value in args_list : value = value and parser . compile_filter ( value ) if arg in TAG_SETTINGS and value is not None : kwargs [ str ( arg ) ] = value continue else : raise TemplateSyntaxError ( "'%s' tag received a bad argument: " "'%s'" % ( tag , arg ) ) return ThumbnailNode ( source_var , size_var , opts = opts , context_name = context_name , * * kwargs )
Creates a thumbnail of for an ImageField .
390
10
8,393
def printStats ( self ) : print ( "--- Imagestats Results ---" ) if ( self . fields . find ( 'npix' ) != - 1 ) : print ( "Number of pixels : " , self . npix ) if ( self . fields . find ( 'min' ) != - 1 ) : print ( "Minimum value : " , self . min ) if ( self . fields . find ( 'max' ) != - 1 ) : print ( "Maximum value : " , self . max ) if ( self . fields . find ( 'stddev' ) != - 1 ) : print ( "Standard Deviation: " , self . stddev ) if ( self . fields . find ( 'mean' ) != - 1 ) : print ( "Mean : " , self . mean ) if ( self . fields . find ( 'mode' ) != - 1 ) : print ( "Mode : " , self . mode ) if ( self . fields . find ( 'median' ) != - 1 ) : print ( "Median : " , self . median ) if ( self . fields . find ( 'midpt' ) != - 1 ) : print ( "Midpt : " , self . midpt )
Print the requested statistics values for those fields specified on input .
260
12
8,394
def raw_request ( self , method , uri , * * kwargs ) : with warnings . catch_warnings ( ) : # catch warning about certs not being verified warnings . simplefilter ( "ignore" , urllib3 . exceptions . InsecureRequestWarning ) warnings . simplefilter ( "ignore" , urllib3 . exceptions . InsecurePlatformWarning ) try : response = self . _get_session ( ) . request ( method , self . _get_ws_url ( uri ) , * * kwargs ) except requests . RequestException as e : # e.g. raise new_exc from old_exc six . raise_from ( WVAHttpRequestError ( e ) , e ) else : return response
Perform a WVA web services request and return the raw response object
157
14
8,395
def request ( self , method , uri , * * kwargs ) : response = self . raw_request ( method , uri , * * kwargs ) if response . status_code != 200 : exception_class = HTTP_STATUS_EXCEPTION_MAP . get ( response . status_code , WVAHttpError ) raise exception_class ( response ) if response . headers . get ( "content-type" ) == "application/json" : return json . loads ( response . text ) else : return response . text
Perform a WVA web services request and return the decoded value if successful
115
16
8,396
def post ( self , uri , data , * * kwargs ) : return self . request ( "POST" , uri , data = data , * * kwargs )
POST the provided data to the specified path
39
8
8,397
def post_json ( self , uri , data , * * kwargs ) : encoded_data = json . dumps ( data ) kwargs . setdefault ( "headers" , { } ) . update ( { "Content-Type" : "application/json" , # tell server we are sending json } ) return self . post ( uri , data = encoded_data , * * kwargs )
POST the provided data as json to the specified path
88
10
8,398
def put ( self , uri , data , * * kwargs ) : return self . request ( "PUT" , uri , data = data , * * kwargs )
PUT the provided data to the specified path
39
8
8,399
def put_json ( self , uri , data , * * kwargs ) : encoded_data = json . dumps ( data ) kwargs . setdefault ( "headers" , { } ) . update ( { "Content-Type" : "application/json" , # tell server we are sending json } ) return self . put ( uri , data = encoded_data , * * kwargs )
PUT the provided data as json to the specified path
88
10