idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
6,200
def trim_sparse ( M , n_std = 3 , s_min = None , s_max = None ) : try : from scipy . sparse import coo_matrix except ImportError as e : print ( str ( e ) ) print ( "I am peforming dense normalization by default." ) return trim_dense ( M . todense ( ) ) r = M . tocoo ( ) sparsity = np . array ( r . sum ( axis = 1 ) ) . ...
Apply the trimming procedure to a sparse matrix .
301
10
6,201
def normalize_dense ( M , norm = "frag" , order = 1 , iterations = 3 ) : s = np . array ( M , np . float64 ) floatorder = np . float64 ( order ) if norm == "SCN" : for _ in range ( 0 , iterations ) : sumrows = s . sum ( axis = 1 ) maskrows = ( sumrows != 0 ) [ : , None ] * ( sumrows != 0 ) [ None , : ] sums_row = sumro...
Apply one of the many normalization types to input dense matrix . Will also apply any callable norms such as a user - made or a lambda function .
572
31
6,202
def normalize_sparse ( M , norm = "frag" , order = 1 , iterations = 3 ) : try : from scipy . sparse import csr_matrix except ImportError as e : print ( str ( e ) ) print ( "I am peforming dense normalization by default." ) return normalize_dense ( M . todense ( ) ) r = csr_matrix ( M ) if norm == "SCN" : for _ in range...
Applies a normalization type to a sparse matrix .
316
11
6,203
def GC_wide ( genome , window = 1000 ) : GC = [ ] from Bio import SeqIO with open ( genome ) as handle : sequence = "" . join ( [ str ( record . seq ) for record in SeqIO . parse ( handle , "fasta" ) ] ) n = len ( sequence ) for i in range ( 0 , n , window ) : portion = sequence [ i : min ( i + window , n ) ] GC . appe...
Compute GC across a window of given length .
107
10
6,204
def to_dade_matrix ( M , annotations = "" , filename = None ) : n , m = M . shape A = np . zeros ( ( n + 1 , m + 1 ) ) A [ 1 : , 1 : ] = M if not annotations : annotations = np . array ( [ "" for _ in n ] , dtype = str ) A [ 0 , : ] = annotations A [ : , 0 ] = annotations . T if filename : try : np . savetxt ( filename...
Returns a Dade matrix from input numpy matrix . Any annotations are added as header . If filename is provided and valid said matrix is also saved as text .
165
32
6,205
def largest_connected_component ( matrix ) : try : import scipy . sparse n , components = scipy . sparse . csgraph . connected_components ( matrix , directed = False ) print ( "I found " + str ( n ) + " connected components." ) component_dist = collections . Counter ( components ) print ( "Distribution of components: "...
Compute the adjacency matrix of the largest connected component of the graph whose input matrix is adjacent .
172
21
6,206
def to_structure ( matrix , alpha = 1 ) : connected = largest_connected_component ( matrix ) distances = to_distance ( connected , alpha ) n , m = connected . shape bary = np . sum ( np . triu ( distances , 1 ) ) / ( n ** 2 ) # barycenters d = np . array ( np . sum ( distances ** 2 , 0 ) / n - bary ) # distances to ori...
Compute best matching 3D genome structure from underlying input matrix using ShRec3D - derived method from Lesne et al . 2014 .
344
28
6,207
def get_missing_bins ( original , trimmed ) : original_diag = np . diag ( original ) trimmed_diag = np . diag ( trimmed ) index = [ ] m = min ( original . shape ) for j in range ( min ( trimmed . shape ) ) : k = 0 while original_diag [ j + k ] != trimmed_diag [ j ] and k < 2 * m : k += 1 index . append ( k + j ) return...
Retrieve indices of a trimmed matrix with respect to the original matrix . Fairly fast but is only correct if diagonal values are different which is always the case in practice .
108
34
6,208
def distance_to_contact ( D , alpha = 1 ) : if callable ( alpha ) : distance_function = alpha else : try : a = np . float64 ( alpha ) def distance_function ( x ) : return 1 / ( x ** ( 1 / a ) ) except TypeError : print ( "Alpha parameter must be callable or an array-like" ) raise except ZeroDivisionError : raise ValueE...
Compute contact matrix from input distance matrix . Distance values of zeroes are given the largest contact count otherwise inferred non - zero distance values .
157
29
6,209
def pdb_to_structure ( filename ) : try : from Bio . PDB import PDB except ImportError : print ( "I can't import Biopython which is needed to handle PDB files." ) raise p = PDB . PDBParser ( ) structure = p . get_structure ( 'S' , filename ) for _ in structure . get_chains ( ) : atoms = [ np . array ( atom . get_coord ...
Import a structure object from a PDB file .
112
10
6,210
def positions_to_contigs ( positions ) : if isinstance ( positions , np . ndarray ) : flattened_positions = positions . flatten ( ) else : try : flattened_positions = np . array ( [ pos for contig in positions for pos in contig ] ) except TypeError : flattened_positions = np . array ( positions ) if ( np . diff ( posit...
Flattens and converts a positions array to a contigs array if applicable .
186
16
6,211
def distance_diagonal_law ( matrix , positions = None ) : n = min ( matrix . shape ) if positions is None : return np . array ( [ np . average ( np . diagonal ( matrix , j ) ) for j in range ( n ) ] ) else : contigs = positions_to_contigs ( positions ) def is_intra ( i , j ) : return contigs [ i ] == contigs [ j ] max_...
Compute a distance law trend using the contact averages of equal distances . Specific positions can be supplied if needed .
308
22
6,212
def rippe_parameters ( matrix , positions , lengths = None , init = None , circ = False ) : n , _ = matrix . shape if lengths is None : lengths = np . abs ( np . diff ( positions ) ) measurements , bins = [ ] , [ ] for i in range ( n ) : for j in range ( 1 , i ) : mean_length = ( lengths [ i ] + lengths [ j ] ) / 2. if...
Estimate parameters from the model described in Rippe et al . 2001 .
218
16
6,213
def scalogram ( M , circ = False ) : # Sanity checks if not type ( M ) is np . ndarray : M = np . array ( M ) if M . shape [ 0 ] != M . shape [ 1 ] : raise ValueError ( "Matrix is not square." ) try : n = min ( M . shape ) except AttributeError : n = M . size N = np . zeros ( M . shape ) for i in range ( n ) : for j in...
Computes so - called scalograms used to easily visualize contacts at different distance scales . Edge cases have been painstakingly taken care of .
315
28
6,214
def asd ( M1 , M2 ) : from scipy . fftpack import fft2 spectra1 = np . abs ( fft2 ( M1 ) ) spectra2 = np . abs ( fft2 ( M2 ) ) return np . linalg . norm ( spectra2 - spectra1 )
Compute a Fourier transform based distance between two matrices .
72
13
6,215
def remove_intra ( M , contigs ) : N = np . copy ( M ) n = len ( N ) assert n == len ( contigs ) # Naive implmentation for now for ( i , j ) in itertools . product ( range ( n ) , range ( n ) ) : if contigs [ i ] == contigs [ j ] : N [ i , j ] = 0 return N
Remove intrachromosomal contacts
88
7
6,216
def positions_to_contigs ( positions ) : contig_labels = np . zeros_like ( positions ) contig_index = 0 for i , p in enumerate ( positions ) : if p == 0 : contig_index += 1 contig_labels [ i ] = contig_index return contig_labels
Label contigs according to relative positions
73
7
6,217
def contigs_to_positions ( contigs , binning = 10000 ) : positions = np . zeros_like ( contigs ) index = 0 for _ , chunk in itertools . groubpy ( contigs ) : l = len ( chunk ) positions [ index : index + l ] = np . arange ( list ( chunk ) ) * binning index += l return positions
Build positions from contig labels
83
6
6,218
def split_matrix ( M , contigs ) : index = 0 for _ , chunk in itertools . groubpy ( contigs ) : l = len ( chunk ) yield M [ index : index + l , index : index + l ] index += l
Split multiple chromosome matrix
56
4
6,219
def find_nearest ( sorted_list , x ) : if x <= sorted_list [ 0 ] : return sorted_list [ 0 ] elif x >= sorted_list [ - 1 ] : return sorted_list [ - 1 ] else : lower = find_le ( sorted_list , x ) upper = find_ge ( sorted_list , x ) if ( x - lower ) > ( upper - x ) : return upper else : return lower
Find the nearest item of x from sorted array .
95
10
6,220
def format_x_tick ( axis , major_locator = None , major_formatter = None , minor_locator = None , minor_formatter = None ) : if major_locator : axis . xaxis . set_major_locator ( major_locator ) if major_formatter : axis . xaxis . set_major_formatter ( major_formatter ) if minor_locator : axis . xaxis . set_minor_locat...
Set x axis s format .
197
6
6,221
def set_legend ( axis , lines , legend ) : try : if legend : axis . legend ( lines , legend ) except Exception as e : raise ValueError ( "invalid 'legend', Error: %s" % e )
Set line legend .
50
4
6,222
def get_max ( array ) : largest = - np . inf for i in array : try : if i > largest : largest = i except : pass if np . isinf ( largest ) : raise ValueError ( "there's no numeric value in array!" ) else : return largest
Get maximum value of an array . Automatically ignore invalid data .
59
13
6,223
def get_min ( array ) : smallest = np . inf for i in array : try : if i < smallest : smallest = i except : pass if np . isinf ( smallest ) : raise ValueError ( "there's no numeric value in array!" ) else : return smallest
Get minimum value of an array . Automatically ignore invalid data .
58
13
6,224
def get_yAxis_limit ( y , lower = 0.05 , upper = 0.2 ) : smallest = get_min ( y ) largest = get_max ( y ) gap = largest - smallest if gap >= 0.000001 : y_min = smallest - lower * gap y_max = largest + upper * gap else : y_min = smallest - lower * abs ( smallest ) y_max = largest + upper * abs ( largest ) return y_min ,...
Find optimal y_min and y_max that guarantee enough space for legend and plot .
105
18
6,225
def create_figure ( width = 20 , height = 10 ) : figure = plt . figure ( figsize = ( width , height ) ) axis = figure . add_subplot ( 1 , 1 , 1 ) return figure , axis
Create a figure instance .
49
5
6,226
def preprocess_x_y ( x , y ) : def is_iterable_slicable ( a ) : if hasattr ( a , "__iter__" ) and hasattr ( a , "__getitem__" ) : return True else : return False if is_iterable_slicable ( x ) : if is_iterable_slicable ( x [ 0 ] ) : return x , y else : return ( x , ) , ( y , ) else : raise ValueError ( "invalid input!" ...
Preprocess x y input data . Returns list of list style .
115
13
6,227
def execute ( input_params , engine , cwd = None ) : try : taskengine_exe = config . get ( 'engine' ) except NoConfigOptionError : raise TaskEngineNotFoundError ( "Task Engine config option not set." + "\nPlease verify the 'engine' configuration setting." ) if not os . path . exists ( taskengine_exe ) : raise TaskEngin...
Execute a task with the provided input parameters
465
9
6,228
def run ( self , wrappers = [ "" , "" ] ) : opened_file = open ( self . lyfile , 'w' ) lilystring = self . piece_obj . toLily ( ) opened_file . writelines ( wrappers [ 0 ] + "\\version \"2.18.2\" \n" + lilystring + wrappers [ 1 ] ) opened_file . close ( ) # subprocess.Popen(['sudo', self.lily_script," --output=" + # se...
run the lilypond script on the hierarchy class
154
11
6,229
def extract_fasta ( partition_file , fasta_file , output_dir , chunk_size = DEFAULT_CHUNK_SIZE , max_cores = DEFAULT_MAX_CORES , ) : genome = { record . id : record . seq for record in SeqIO . parse ( fasta_file , "fasta" ) } data_chunks = list ( zip ( * np . genfromtxt ( partition_file , usecols = ( 0 , 1 ) , dtype = ...
Extract sequences from bins
362
5
6,230
def merge_fasta ( fasta_file , output_dir ) : # First, define some functions for ordering chunks and detecting # consecutive chunk sequences def chunk_lexicographic_order ( chunk ) : """A quick callback to sort chunk ids lexicographically (first on original names alphabetically, then on relative position on the origina...
Merge chunks into complete FASTA bins
706
9
6,231
def monitor ( ) : log = logging . getLogger ( __name__ ) loop = asyncio . get_event_loop ( ) asyncio . ensure_future ( console ( loop , log ) ) loop . run_forever ( )
Wrapper to call console with a loop .
51
9
6,232
def make_object ( cls , data ) : if issubclass ( cls , Object ) : self = object . __new__ ( cls ) self . _data = data else : self = data return self
Creates an API object of class cls setting its _data to data . Subclasses of Object are required to use this to build a new empty instance without using their constructor .
46
36
6,233
def String ( length = None , * * kwargs ) : return Property ( length = length , types = stringy_types , convert = to_string , * * kwargs )
A string valued property with max . length .
40
9
6,234
def Datetime ( null = True , * * kwargs ) : return Property ( types = datetime . datetime , convert = util . local_timezone , load = dateutil . parser . parse , null = null , * * kwargs )
A datetime property .
54
5
6,235
def InstanceOf ( cls , * * kwargs ) : return Property ( types = cls , load = cls . load , * * kwargs )
A property that is an instance of cls .
36
10
6,236
def ListOf ( cls , * * kwargs ) : def _list_load ( value ) : return [ cls . load ( d ) for d in value ] return Property ( types = list , load = _list_load , default = list , * * kwargs )
A property that is a list of cls .
61
10
6,237
def add_dimension ( self , name , data = None ) : self . dimensions . add ( name ) if data is None : valobj = self . __dimtype__ ( ) else : valobj = make_object ( self . __dimtype__ , data ) self . _data [ name ] = valobj setattr ( self , name , valobj ) return valobj
Add a named dimension to this entity .
79
8
6,238
def print_block ( self , section_key , f = sys . stdout , file_format = "mwtab" ) : if file_format == "mwtab" : for key , value in self [ section_key ] . items ( ) : if section_key == "METABOLOMICS WORKBENCH" and key not in ( "VERSION" , "CREATED_ON" ) : continue if key in ( "VERSION" , "CREATED_ON" ) : cw = 20 - len (...
Print mwtab section into a file or stdout .
731
12
6,239
def _is_mwtab ( string ) : if isinstance ( string , str ) : lines = string . split ( "\n" ) elif isinstance ( string , bytes ) : lines = string . decode ( "utf-8" ) . split ( "\n" ) else : raise TypeError ( "Expecting <class 'str'> or <class 'bytes'>, but {} was passed" . format ( type ( string ) ) ) lines = [ line for...
Test if input string is in mwtab format .
142
11
6,240
def getTraceIdsBySpanName ( self , service_name , span_name , end_ts , limit , order ) : self . send_getTraceIdsBySpanName ( service_name , span_name , end_ts , limit , order ) return self . recv_getTraceIdsBySpanName ( )
Fetch trace ids by service and span name . Gets limit number of entries from before the end_ts .
77
23
6,241
def getTraceIdsByServiceName ( self , service_name , end_ts , limit , order ) : self . send_getTraceIdsByServiceName ( service_name , end_ts , limit , order ) return self . recv_getTraceIdsByServiceName ( )
Fetch trace ids by service name . Gets limit number of entries from before the end_ts .
66
21
6,242
def getTraceIdsByAnnotation ( self , service_name , annotation , value , end_ts , limit , order ) : self . send_getTraceIdsByAnnotation ( service_name , annotation , value , end_ts , limit , order ) return self . recv_getTraceIdsByAnnotation ( )
Fetch trace ids with a particular annotation . Gets limit number of entries from before the end_ts .
74
22
6,243
def getTracesByIds ( self , trace_ids , adjust ) : self . send_getTracesByIds ( trace_ids , adjust ) return self . recv_getTracesByIds ( )
Get the full traces associated with the given trace ids .
45
12
6,244
def getTraceSummariesByIds ( self , trace_ids , adjust ) : self . send_getTraceSummariesByIds ( trace_ids , adjust ) return self . recv_getTraceSummariesByIds ( )
Fetch trace summaries for the given trace ids .
54
12
6,245
def getTraceCombosByIds ( self , trace_ids , adjust ) : self . send_getTraceCombosByIds ( trace_ids , adjust ) return self . recv_getTraceCombosByIds ( )
Not content with just one of traces summaries or timelines? Want it all? This is the method for you .
51
23
6,246
def setTraceTimeToLive ( self , trace_id , ttl_seconds ) : self . send_setTraceTimeToLive ( trace_id , ttl_seconds ) self . recv_setTraceTimeToLive ( )
Change the TTL of a trace . If we find an interesting trace we want to keep around for further investigation .
53
22
6,247
def discover_datasource_columns ( datastore_str , datasource_id ) : datastore = DataStore ( datastore_str ) datasource = datastore . get_datasource ( datasource_id ) if datasource . type != "RASTER" : return datasource . list_columns ( ) else : return [ ]
Loop through the datastore s datasources to find the datasource identified by datasource_id return the matching datasource s columns .
80
28
6,248
def _get_column_type ( self , column ) : ctype = column . GetType ( ) if ctype in [ ogr . OFTInteger , ogr . OFTReal ] : return 'numeric' else : return 'string'
Return numeric if the column is of type integer or real otherwise return string .
53
15
6,249
def _get_default_mapfile_excerpt ( self ) : layerobj = self . _get_layer_stub ( ) classobj = mapscript . classObj ( ) layerobj . insertClass ( classobj ) styleobj = self . _get_default_style ( ) classobj . insertStyle ( styleobj ) return mapserializer . layerobj_to_dict ( layerobj , None )
Given an OGR string an OGR connection and an OGR layer create and return a representation of a MapFile LAYER block .
87
28
6,250
def _get_layer_stub ( self ) : layerobj = mapscript . layerObj ( ) layerobj . name = self . name layerobj . status = mapscript . MS_ON projection = self . ogr_layer . GetSpatialRef ( ) featureIdColumn = self . _get_featureId_column ( ) if featureIdColumn is not None and featureIdColumn != '' : layerobj . metadata . set...
builds a minimal mapscript layerobj with no styling
498
11
6,251
def reelect_app ( self , request , app ) : # disconnect app explicitly to break possibly existing connection app . disconnect ( ) endpoints_size = len ( app . locator . endpoints ) # try x times, where x is the number of different endpoints in app locator. for _ in xrange ( 0 , endpoints_size + 1 ) : # last chance to t...
tries to connect to the same app on differnet host from dist - info
540
17
6,252
def RecordHelloWorld ( handler , t ) : url = "%s/receive_recording.py" % THIS_URL t . startRecording ( url ) t . say ( "Hello, World." ) t . stopRecording ( ) json = t . RenderJson ( ) logging . info ( "RecordHelloWorld json: %s" % json ) handler . response . out . write ( json )
Demonstration of recording a message .
87
7
6,253
def RedirectDemo ( handler , t ) : # t.say ("One moment please.") t . redirect ( SIP_PHONE ) json = t . RenderJson ( ) logging . info ( "RedirectDemo json: %s" % json ) handler . response . out . write ( json )
Demonstration of redirecting to another number .
66
9
6,254
def TransferDemo ( handler , t ) : t . say ( "One moment please." ) t . transfer ( MY_PHONE ) t . say ( "Hi. I am a robot" ) json = t . RenderJson ( ) logging . info ( "TransferDemo json: %s" % json ) handler . response . out . write ( json )
Demonstration of transfering to another number
77
8
6,255
def retry ( ExceptionToCheck , tries = 4 , delay = 3 , backoff = 2 , status_codes = [ ] , logger = None ) : if backoff is None or backoff <= 0 : raise ValueError ( "backoff must be a number greater than 0" ) tries = math . floor ( tries ) if tries < 0 : raise ValueError ( "tries must be a number 0 or greater" ) if dela...
Decorator function for retrying the decorated function using an exponential or fixed backoff .
279
18
6,256
def _custom_response_edit ( self , method , url , headers , body , response ) : if self . get_implementation ( ) . is_mock ( ) : delay = self . get_setting ( "MOCKDATA_DELAY" , 0.0 ) time . sleep ( delay ) self . _edit_mock_response ( method , url , headers , body , response )
This method allows a service to edit a response .
86
10
6,257
def postURL ( self , url , headers = { } , body = None ) : return self . _load_resource ( "POST" , url , headers , body )
Request a URL using the HTTP method POST .
36
9
6,258
def putURL ( self , url , headers , body = None ) : return self . _load_resource ( "PUT" , url , headers , body )
Request a URL using the HTTP method PUT .
33
10
6,259
def patchURL ( self , url , headers , body ) : return self . _load_resource ( "PATCH" , url , headers , body )
Request a URL using the HTTP method PATCH .
32
10
6,260
def setup_dir ( f ) : setup_dir = os . path . dirname ( os . path . abspath ( __file__ ) ) def wrapped ( * args , * * kwargs ) : with chdir ( setup_dir ) : return f ( * args , * * kwargs ) return wrapped
Decorate f to run inside the directory where setup . py resides .
67
14
6,261
def feedback_form ( context ) : user = None url = None if context . get ( 'request' ) : url = context [ 'request' ] . path if context [ 'request' ] . user . is_authenticated ( ) : user = context [ 'request' ] . user return { 'form' : FeedbackForm ( url = url , user = user ) , 'background_color' : FEEDBACK_FORM_COLOR , ...
Template tag to render a feedback form .
124
8
6,262
def select ( self , * itms ) : if not itms : itms = [ '*' ] self . terms . append ( "select %s from %s" % ( ', ' . join ( itms ) , self . table ) ) return self
Joins the items to be selected and inserts the current table name
55
13
6,263
def _in ( self , * lst ) : self . terms . append ( 'in (%s)' % ', ' . join ( [ '"%s"' % x for x in lst ] ) ) return self
Build out the in clause . Using _in due to shadowing for in
46
15
6,264
def compile ( self ) : cs = "" for term in self . terms : if cs : cs += " " cs += term self . compiled_str = urllib . parse . quote ( cs ) return self
Take all of the parts components and build the complete query to be passed to Yahoo YQL
44
18
6,265
def read_files ( * sources , * * kwds ) : filenames = _generate_filenames ( sources ) filehandles = _generate_handles ( filenames ) for fh , source in filehandles : try : f = mwtab . MWTabFile ( source ) f . read ( fh ) if kwds . get ( 'validate' ) : validator . validate_file ( mwtabfile = f , section_schema_mapping = ...
Construct a generator that yields file instances .
204
8
6,266
def is_url ( path ) : try : parse_result = urlparse ( path ) return all ( ( parse_result . scheme , parse_result . netloc , parse_result . path ) ) except ValueError : return False
Test if path represents a valid URL .
49
8
6,267
def AuthMiddleware ( app ) : # url_for mustn't be used here because AuthMiddleware is built once at startup, # url path can be reconstructed only on http requests (based on environ) basic_redirect_form = BasicRedirectFormPlugin ( login_form_url = "/signin" , login_handler_path = "/login" , post_login_url = "/" , logout...
Add authentication and authorization middleware to the app .
265
10
6,268
def _get_full_path ( self , path , environ ) : if path . startswith ( '/' ) : path = environ . get ( 'SCRIPT_NAME' , '' ) + path return path
Return the full path to path by prepending the SCRIPT_NAME . If path is a URL do nothing .
47
23
6,269
def _replace_qs ( self , url , qs ) : url_parts = list ( urlparse ( url ) ) url_parts [ 4 ] = qs return urlunparse ( url_parts )
Replace the query string of url with qs and return the new URL .
44
16
6,270
def write ( self ) : with open ( storage . config_file , 'w' ) as cfg : yaml . dump ( self . as_dict ( ) , cfg , default_flow_style = False ) storage . refresh ( )
write the current settings to the config file
52
8
6,271
def process_bind_param ( self , value , dialect ) : if value is not None : value = simplejson . dumps ( value ) return value
convert value from python object to json
31
8
6,272
def process_result_value ( self , value , dialect ) : if value is not None : value = simplejson . loads ( value ) return value
convert value from json to a python object
31
9
6,273
def getBriefModuleInfoFromFile ( fileName ) : modInfo = BriefModuleInfo ( ) _cdmpyparser . getBriefModuleInfoFromFile ( modInfo , fileName ) modInfo . flush ( ) return modInfo
Builds the brief module info from file
50
8
6,274
def getBriefModuleInfoFromMemory ( content ) : modInfo = BriefModuleInfo ( ) _cdmpyparser . getBriefModuleInfoFromMemory ( modInfo , content ) modInfo . flush ( ) return modInfo
Builds the brief module info from memory
48
8
6,275
def getDisplayName ( self ) : if self . alias == "" : return self . name return self . name + " as " + self . alias
Provides a name for display purpose respecting the alias
31
10
6,276
def flush ( self ) : self . __flushLevel ( 0 ) if self . __lastImport is not None : self . imports . append ( self . __lastImport )
Flushes the collected information
36
5
6,277
def __flushLevel ( self , level ) : objectsCount = len ( self . objectsStack ) while objectsCount > level : lastIndex = objectsCount - 1 if lastIndex == 0 : # We have exactly one element in the stack if self . objectsStack [ 0 ] . __class__ . __name__ == "Class" : self . classes . append ( self . objectsStack [ 0 ] ) e...
Merge the found objects to the required level
199
9
6,278
def _onEncoding ( self , encString , line , pos , absPosition ) : self . encoding = Encoding ( encString , line , pos , absPosition )
Memorizes module encoding
36
5
6,279
def _onGlobal ( self , name , line , pos , absPosition , level ) : # level is ignored for item in self . globals : if item . name == name : return self . globals . append ( Global ( name , line , pos , absPosition ) )
Memorizes a global variable
58
6
6,280
def _onClass ( self , name , line , pos , absPosition , keywordLine , keywordPos , colonLine , colonPos , level ) : self . __flushLevel ( level ) c = Class ( name , line , pos , absPosition , keywordLine , keywordPos , colonLine , colonPos ) if self . __lastDecorators is not None : c . decorators = self . __lastDecorat...
Memorizes a class
106
5
6,281
def _onWhat ( self , name , line , pos , absPosition ) : self . __lastImport . what . append ( ImportWhat ( name , line , pos , absPosition ) )
Memorizes an imported item
40
6
6,282
def _onClassAttribute ( self , name , line , pos , absPosition , level ) : # A class must be on the top of the stack attributes = self . objectsStack [ level ] . classAttributes for item in attributes : if item . name == name : return attributes . append ( ClassAttribute ( name , line , pos , absPosition ) )
Memorizes a class attribute
73
6
6,283
def _onInstanceAttribute ( self , name , line , pos , absPosition , level ) : # Instance attributes may appear in member functions only so we already # have a function on the stack of objects. To get the class object one # more step is required so we -1 here. attributes = self . objectsStack [ level - 1 ] . instanceAtt...
Memorizes a class instance attribute
105
7
6,284
def _onArgument ( self , name , annotation ) : self . objectsStack [ - 1 ] . arguments . append ( Argument ( name , annotation ) )
Memorizes a function argument
33
6
6,285
def _onError ( self , message ) : self . isOK = False if message . strip ( ) != "" : self . errors . append ( message )
Memorizies a parser error message
33
8
6,286
def _onLexerError ( self , message ) : self . isOK = False if message . strip ( ) != "" : self . lexerErrors . append ( message )
Memorizes a lexer error message
38
8
6,287
def gen_mapname ( ) : filepath = None while ( filepath is None ) or ( os . path . exists ( os . path . join ( config [ 'mapfiles_dir' ] , filepath ) ) ) : filepath = '%s.map' % _gen_string ( ) return filepath
Generate a uniq mapfile pathname .
68
10
6,288
def config_content ( self , command , vars ) : settable_vars = [ var ( 'db_url' , 'Database url for sqlite, postgres or mysql' , default = 'sqlite:///%(here)s/studio.db' ) , var ( 'ms_url' , 'Url to the mapserv CGI' , default = 'http://localhost/cgi-bin/mapserv' ) , var ( 'admin_password' , 'Password for default admin ...
Called by self . write_config this returns the text content for the config file given the provided variables .
258
22
6,289
def _resolve_definitions ( self , schema , definitions ) : if not definitions : return schema if not isinstance ( schema , dict ) : return schema ref = schema . pop ( '$ref' , None ) if ref : path = ref . split ( '/' ) [ 2 : ] definition = definitions for component in path : definition = definitions [ component ] if de...
Interpolates definitions from the top - level definitions key into the schema . This is performed in a cut - down way similar to JSON schema .
145
29
6,290
def _get_serializer ( self , _type ) : if _type in _serializers : # _serializers is module level return _serializers [ _type ] # array and object are special types elif _type == 'array' : return self . _get_array_serializer ( ) elif _type == 'object' : return self . _get_object_serializer ( ) raise ValueError ( 'Unknow...
Gets a serializer for a particular type . For primitives returns the serializer from the module - level serializers . For arrays and objects uses the special _get_T_serializer methods to build the encoders and decoders .
102
51
6,291
def _get_array_serializer ( self ) : if not self . _items : raise ValueError ( 'Must specify \'items\' for \'array\' type' ) field = SchemaField ( self . _items ) def encode ( value , field = field ) : if not isinstance ( value , list ) : value = [ value ] return [ field . encode ( i ) for i in value ] def decode ( val...
Gets the encoder and decoder for an array . Uses the items key to build the encoders and decoders for the specified type .
114
31
6,292
def encode ( self , value ) : if value is None and self . _default is not None : value = self . _default for encoder in self . _encoders : try : return encoder ( value ) except ValueError as ex : pass raise ValueError ( 'Value \'{}\' is invalid. {}' . format ( value , ex . message ) )
The encoder for this schema . Tries each encoder in order of the types specified for this schema .
78
22
6,293
def decode ( self , value ) : # Use the default value unless the field accepts None types has_null_encoder = bool ( encode_decode_null in self . _decoders ) if value is None and self . _default is not None and not has_null_encoder : value = self . _default for decoder in self . _decoders : try : return decoder ( value ...
The decoder for this schema . Tries each decoder in order of the types specified for this schema .
120
22
6,294
def _fail_early ( message , * * kwds ) : import json output = dict ( kwds ) output . update ( { 'msg' : message , 'failed' : True , } ) print ( json . dumps ( output ) ) sys . exit ( 1 )
The module arguments are dynamically generated based on the Opsview version . This means that fail_json isn t available until after the module has been properly initialized and the schemas have been loaded .
59
38
6,295
def _compare_recursive ( old , new ) : if isinstance ( new , dict ) : for key in six . iterkeys ( new ) : try : if _compare_recursive ( old [ key ] , new [ key ] ) : return True except ( KeyError , TypeError ) : return True elif isinstance ( new , list ) or isinstance ( new , tuple ) : for i , item in enumerate ( new )...
Deep comparison between objects ; assumes that new contains user defined parameters so only keys which exist in new will be compared . Returns True if they differ . Else False .
135
32
6,296
def _requires_update ( self , old_object , new_object ) : old_encoded = self . manager . _encode ( old_object ) new_encoded = self . manager . _encode ( new_object ) return _compare_recursive ( old_encoded , new_encoded )
Checks whether the old object and new object differ ; only checks keys which exist in the new object
69
20
6,297
def url2domain ( url ) : parsed_uri = urlparse . urlparse ( url ) domain = '{uri.netloc}' . format ( uri = parsed_uri ) domain = re . sub ( "^.+@" , "" , domain ) domain = re . sub ( ":.+$" , "" , domain ) return domain
extract domain from url
76
5
6,298
def init_model ( engine ) : if meta . Session is None : sm = orm . sessionmaker ( autoflush = True , autocommit = False , bind = engine ) meta . engine = engine meta . Session = orm . scoped_session ( sm )
Call me before using any of the tables or classes in the model
60
13
6,299
def register_prop ( name , handler_get , handler_set ) : global props_get , props_set if handler_get : props_get [ name ] = handler_get if handler_set : props_set [ name ] = handler_set
register a property handler
54
4