idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
10,700
def get_token ( user , secret , timestamp = None ) : timestamp = int ( timestamp or time ( ) ) secret = to_bytes ( secret ) key = '|' . join ( [ hashlib . sha1 ( secret ) . hexdigest ( ) , str ( user . id ) , get_hash_extract ( user . password ) , str ( getattr ( user , 'last_sign_in' , 0 ) ) , str ( timestamp ) , ] ) key = key . encode ( 'utf8' , 'ignore' ) mac = hmac . new ( key , msg = None , digestmod = hashlib . sha512 ) mac = mac . hexdigest ( ) [ : 50 ] token = '{0}${1}${2}' . format ( user . id , to36 ( timestamp ) , mac ) return token
Make a timestamped one - time - use token that can be used to identifying the user .
183
20
10,701
def __get_user ( self ) : storage = object . __getattribute__ ( self , '_LazyUser__storage' ) user = getattr ( self . __auth , 'get_user' ) ( ) setattr ( storage , self . __user_name , user ) return user
Return the real user object .
63
6
10,702
def _expand_filename ( self , line ) : # expand . newline = line path = os . getcwd ( ) if newline . startswith ( "." ) : newline = newline . replace ( "." , path , 1 ) # expand ~ newline = os . path . expanduser ( newline ) return newline
expands the filename if there is a . as leading path
74
12
10,703
def setCustomField ( mambuentity , customfield = "" , * args , * * kwargs ) : from . import mambuuser from . import mambuclient try : customFieldValue = mambuentity [ customfield ] # find the dataType customfield by name or id datatype = [ l [ 'customField' ] [ 'dataType' ] for l in mambuentity [ mambuentity . customFieldName ] if ( l [ 'name' ] == customfield or l [ 'id' ] == customfield ) ] [ 0 ] except IndexError as ierr : # if no customfield found with the given name, assume it is a # grouped custom field, name must have an index suffix that must # be removed try : # find the dataType customfield by name or id datatype = [ l [ 'customField' ] [ 'dataType' ] for l in mambuentity [ mambuentity . customFieldName ] if ( l [ 'name' ] == customfield . split ( '_' ) [ 0 ] or l [ 'id' ] == customfield . split ( '_' ) [ 0 ] ) ] [ 0 ] except IndexError : err = MambuError ( "Object %s has no custom field '%s'" % ( mambuentity [ 'id' ] , customfield ) ) raise err except AttributeError : err = MambuError ( "Object does not have a custom field to set" ) raise err if datatype == "USER_LINK" : mambuentity [ customfield ] = mambuuser . MambuUser ( entid = customFieldValue , * args , * * kwargs ) elif datatype == "CLIENT_LINK" : mambuentity [ customfield ] = mambuclient . MambuClient ( entid = customFieldValue , * args , * * kwargs ) else : mambuentity [ customfield ] = customFieldValue return 0 return 1
Modifies the customField field for the given object with something related to the value of the given field .
439
21
10,704
def serializeFields ( data ) : if isinstance ( data , MambuStruct ) : return data . serializeStruct ( ) try : it = iter ( data ) except TypeError as terr : return unicode ( data ) if type ( it ) == type ( iter ( [ ] ) ) : l = [ ] for e in it : l . append ( MambuStruct . serializeFields ( e ) ) return l elif type ( it ) == type ( iter ( { } ) ) : d = { } for k in it : d [ k ] = MambuStruct . serializeFields ( data [ k ] ) return d # elif ... tuples? sets? return unicode ( data )
Turns every attribute of the Mambu object in to a string representation .
154
16
10,705
def init ( self , attrs = { } , * args , * * kwargs ) : self . attrs = attrs self . preprocess ( ) self . convertDict2Attrs ( * args , * * kwargs ) self . postprocess ( ) try : for meth in kwargs [ 'methods' ] : try : getattr ( self , meth ) ( ) except Exception : pass except Exception : pass try : for propname , propval in kwargs [ 'properties' ] . items ( ) : setattr ( self , propname , propval ) except Exception : pass
Default initialization from a dictionary responded by Mambu
129
10
10,706
def connect ( self , * args , * * kwargs ) : from copy import deepcopy if args : self . __args = deepcopy ( args ) if kwargs : for k , v in kwargs . items ( ) : self . __kwargs [ k ] = deepcopy ( v ) jsresp = { } if not self . __urlfunc : return # Pagination window, Mambu restricts at most 500 elements in response offset = self . __offset window = True jsresp = { } while window : if not self . __limit or self . __limit > OUT_OF_BOUNDS_PAGINATION_LIMIT_VALUE : limit = OUT_OF_BOUNDS_PAGINATION_LIMIT_VALUE else : limit = self . __limit # Retry mechanism, for awful connections retries = 0 while retries < MambuStruct . RETRIES : try : # Basic authentication user = self . __kwargs . get ( 'user' , apiuser ) pwd = self . __kwargs . get ( 'pwd' , apipwd ) if self . __data : headers = { 'content-type' : 'application/json' } data = json . dumps ( encoded_dict ( self . __data ) ) url = iriToUri ( self . __urlfunc ( self . entid , limit = limit , offset = offset , * self . __args , * * self . __kwargs ) ) # PATCH if self . __method == "PATCH" : resp = requests . patch ( url , data = data , headers = headers , auth = ( user , pwd ) ) # POST else : resp = requests . post ( url , data = data , headers = headers , auth = ( user , pwd ) ) # GET else : url = iriToUri ( self . __urlfunc ( self . entid , limit = limit , offset = offset , * self . __args , * * self . __kwargs ) ) resp = requests . get ( url , auth = ( user , pwd ) ) # Always count a new request when done! self . rc . add ( datetime . now ( ) ) try : jsonresp = json . loads ( resp . content ) # Returns list: extend list for offset if type ( jsonresp ) == list : try : jsresp . extend ( jsonresp ) except AttributeError : # First window, forget that jsresp was a dict, turn it in to a list jsresp = jsonresp if len ( jsonresp ) < limit : window = False # Returns dict: in theory Mambu REST API doesn't takes limit/offset in to account else : jsresp = jsonresp window = False except ValueError as ex : # json.loads invalid data argument raise ex except Exception as ex : # any other json error raise MambuError ( "JSON Error: %s" % repr ( ex ) ) # if we reach here, we're done and safe break except MambuError as merr : raise merr except requests . exceptions . RequestException : retries += 1 except Exception as ex : raise ex else : raise MambuCommError ( "ERROR I can't communicate with Mambu" ) # next window, moving offset... offset = offset + limit if self . __limit : self . __limit -= limit if self . __limit <= 0 : window = False self . __limit = self . __inilimit try : if u'returnCode' in jsresp and u'returnStatus' in jsresp and jsresp [ u'returnCode' ] != 0 : raise MambuError ( jsresp [ u'returnStatus' ] ) except AttributeError : pass if self . __method != "PATCH" : self . init ( attrs = jsresp , * self . __args , * * self . __kwargs )
Connect to Mambu make the request to the REST API .
828
13
10,707
def convertDict2Attrs ( self , * args , * * kwargs ) : constantFields = [ 'id' , 'groupName' , 'name' , 'homePhone' , 'mobilePhone1' , 'phoneNumber' , 'postcode' , 'emailAddress' ] def convierte ( data ) : """Recursively convert the fields on the data given to a python object.""" # Iterators, lists and dictionaries # Here comes the recursive calls! try : it = iter ( data ) if type ( it ) == type ( iter ( { } ) ) : d = { } for k in it : if k in constantFields : d [ k ] = data [ k ] else : d [ k ] = convierte ( data [ k ] ) data = d if type ( it ) == type ( iter ( [ ] ) ) : l = [ ] for e in it : l . append ( convierte ( e ) ) data = l except TypeError as terr : pass except Exception as ex : raise ex # Python built-in types: ints, floats, or even datetimes. If it # cannot convert it to a built-in type, leave it as string, or # as-is. There may be nested Mambu objects here! # This are the recursion base cases! try : d = int ( data ) if str ( d ) != data : # if string has trailing 0's, leave it as string, to not lose them return data return d except ( TypeError , ValueError ) as tverr : try : return float ( data ) except ( TypeError , ValueError ) as tverr : try : return self . util_dateFormat ( data ) except ( TypeError , ValueError ) as tverr : return data return data self . attrs = convierte ( self . attrs )
Each element on the atttrs attribute gest converted to a proper python object depending on type .
396
19
10,708
def util_dateFormat ( self , field , formato = None ) : if not formato : try : formato = self . __formatoFecha except AttributeError : formato = "%Y-%m-%dT%H:%M:%S+0000" return datetime . strptime ( datetime . strptime ( field , "%Y-%m-%dT%H:%M:%S+0000" ) . strftime ( formato ) , formato )
Converts a datetime field to a datetime using some specified format .
111
15
10,709
def create ( self , data , * args , * * kwargs ) : # if module of the function is diferent from the module of the object # that means create is not implemented in child class if self . create . __func__ . __module__ != self . __module__ : raise Exception ( "Child method not implemented" ) self . _MambuStruct__method = "POST" self . _MambuStruct__data = data self . connect ( * args , * * kwargs ) self . _MambuStruct__method = "GET" self . _MambuStruct__data = None
Creates an entity in Mambu
133
8
10,710
def make ( self , cmd_args , db_args ) : with NamedTemporaryFile ( delete = True ) as f : format_file = f . name + '.bcp-format' format_args = cmd_args + [ 'format' , NULL_FILE , '-c' , '-f' , format_file , '-t,' ] + db_args _run_cmd ( format_args ) self . load ( format_file ) return format_file
Runs bcp FORMAT command to create a format file that will assist in creating the bulk data file
102
21
10,711
def load ( self , filename = None ) : fields = [ ] with open ( filename , 'r' ) as f : format_data = f . read ( ) . strip ( ) lines = format_data . split ( '\n' ) self . _sql_version = lines . pop ( 0 ) self . _num_fields = int ( lines . pop ( 0 ) ) for line in lines : # Get rid of mulitple spaces line = re . sub ( ' +' , ' ' , line . strip ( ) ) row_format = BCPFormatRow ( line . split ( ' ' ) ) fields . append ( row_format ) self . fields = fields self . filename = filename
Reads a non - XML bcp FORMAT file and parses it into fields list used for creating bulk data file
148
24
10,712
def retrieve_content ( self ) : path = self . _construct_path_to_source_content ( ) res = self . _http . get ( path ) self . _populated_fields [ 'content' ] = res [ 'content' ] return res [ 'content' ]
Retrieve the content of a resource .
61
8
10,713
def _update ( self , * * kwargs ) : if 'content' in kwargs : content = kwargs . pop ( 'content' ) path = self . _construct_path_to_source_content ( ) self . _http . put ( path , json . dumps ( { 'content' : content } ) ) super ( Resource , self ) . _update ( * * kwargs )
Use separate URL for updating the source file .
88
9
10,714
def all ( ) : dir ( ) cmd3 ( ) banner ( "CLEAN PREVIOUS CLOUDMESH INSTALLS" ) r = int ( local ( "pip freeze |fgrep cloudmesh | wc -l" , capture = True ) ) while r > 0 : local ( 'echo "y\n" | pip uninstall cloudmesh' ) r = int ( local ( "pip freeze |fgrep cloudmesh | wc -l" , capture = True ) )
clean the dis and uninstall cloudmesh
107
8
10,715
def find ( cls , text ) : if isinstance ( cls . pattern , string_types ) : cls . pattern = re . compile ( cls . pattern ) return cls . pattern . finditer ( text )
This method should return an iterable containing matches of this element .
48
13
10,716
def main ( ) : parser = argparse . ArgumentParser ( description = 'Monitor your crons with cronitor.io & sentry.io' , epilog = 'https://github.com/youversion/crony' , prog = 'crony' ) parser . add_argument ( '-c' , '--cronitor' , action = 'store' , help = 'Cronitor link identifier. This can be found in your Cronitor unique' ' ping URL right after https://cronitor.link/' ) parser . add_argument ( '-e' , '--venv' , action = 'store' , help = 'Path to virtualenv to source before running script. May be passed' ' as an argument or loaded from an environment variable or config file.' ) parser . add_argument ( '-d' , '--cd' , action = 'store' , help = 'If the script needs ran in a specific directory, than can be passed' ' or cd can be ran prior to running crony.' ) parser . add_argument ( '-l' , '--log' , action = 'store' , help = 'Log file to direct stdout of script run to. Can be passed or ' 'defined in config file with "log_file"' ) parser . add_argument ( '-o' , '--config' , action = 'store' , help = 'Path to a crony config file to use.' ) parser . add_argument ( '-p' , '--path' , action = 'store' , help = 'Paths to append to the PATH environment variable before running. ' ' Can be passed as an argument or loaded from config file.' ) parser . add_argument ( '-s' , '--dsn' , action = 'store' , help = 'Sentry DSN. May be passed or loaded from an environment variable ' 'or a config file.' ) parser . add_argument ( '-t' , '--timeout' , action = 'store' , default = 10 , help = 'Timeout to use when' ' sending requests to Cronitor' , type = int ) parser . add_argument ( '-v' , '--verbose' , action = 'store_true' , help = 'Increase level of verbosity' ' output by crony' ) parser . add_argument ( '--version' , action = 'store_true' , help = 'Output crony version # and exit' ) parser . add_argument ( 'cmd' , nargs = argparse . REMAINDER , help = 'Command to run and monitor' ) cc = CommandCenter ( parser . parse_args ( ) ) sys . exit ( cc . log ( * cc . func ( ) ) )
Entry point for running crony .
593
7
10,717
def cronitor ( self ) : url = f'https://cronitor.link/{self.opts.cronitor}/{{}}' try : run_url = url . format ( 'run' ) self . logger . debug ( f'Pinging {run_url}' ) requests . get ( run_url , timeout = self . opts . timeout ) except requests . exceptions . RequestException as e : self . logger . exception ( e ) # Cronitor may be having an outage, but we still want to run our stuff output , exit_status = self . run ( ) endpoint = 'complete' if exit_status == 0 else 'fail' try : ping_url = url . format ( endpoint ) self . logger . debug ( 'Pinging {}' . format ( ping_url ) ) requests . get ( ping_url , timeout = self . opts . timeout ) except requests . exceptions . RequestException as e : self . logger . exception ( e ) return output , exit_status
Wrap run with requests to cronitor .
215
10
10,718
def load_config ( self , custom_config ) : self . config = configparser . ConfigParser ( ) if custom_config : self . config . read ( custom_config ) return f'Loading config from file {custom_config}.' home = os . path . expanduser ( '~{}' . format ( getpass . getuser ( ) ) ) home_conf_file = os . path . join ( home , '.cronyrc' ) system_conf_file = '/etc/crony.conf' conf_precedence = ( home_conf_file , system_conf_file ) for conf_file in conf_precedence : if os . path . exists ( conf_file ) : self . config . read ( conf_file ) return f'Loading config from file {conf_file}.' self . config [ 'crony' ] = { } return 'No config file found.'
Attempt to load config from file .
198
7
10,719
def log ( self , output , exit_status ) : if exit_status != 0 : self . logger . error ( f'Error running command! Exit status: {exit_status}, {output}' ) return exit_status
Log given CompletedProcess and return exit status code .
48
10
10,720
def run ( self ) : self . logger . debug ( f'Running command: {self.cmd}' ) def execute ( cmd ) : output = "" popen = subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , universal_newlines = True , shell = True ) for stdout_line in iter ( popen . stdout . readline , "" ) : stdout_line = stdout_line . strip ( '\n' ) output += stdout_line yield stdout_line popen . stdout . close ( ) return_code = popen . wait ( ) if return_code : raise subprocess . CalledProcessError ( return_code , cmd , output ) try : for out in execute ( self . cmd ) : self . logger . info ( out ) return "" , 0 except subprocess . CalledProcessError as e : return e . output , e . returncode
Run command and report errors to Sentry .
206
9
10,721
def setup_dir ( self ) : cd = self . opts . cd or self . config [ 'crony' ] . get ( 'directory' ) if cd : self . logger . debug ( f'Adding cd to {cd}' ) self . cmd = f'cd {cd} && {self.cmd}'
Change directory for script if necessary .
70
7
10,722
def setup_logging ( self ) : date_format = '%Y-%m-%dT%H:%M:%S' log_format = '%(asctime)s %(levelname)s: %(message)s' if self . opts . verbose : lvl = logging . DEBUG else : lvl = logging . INFO # Requests is a bit chatty logging . getLogger ( 'requests' ) . setLevel ( 'WARNING' ) self . logger . setLevel ( lvl ) stdout = logging . StreamHandler ( sys . stdout ) stdout . setLevel ( lvl ) formatter = logging . Formatter ( log_format , date_format ) stdout . setFormatter ( formatter ) self . logger . addHandler ( stdout ) # Decided not to use stderr # stderr = logging.StreamHandler(sys.stderr) # stderr.setLevel(logging.ERROR) # Error and above go to both stdout & stderr # formatter = logging.Formatter(log_format, date_format) # stderr.setFormatter(formatter) # self.logger.addHandler(stderr) log = self . opts . log or self . config [ 'crony' ] . get ( 'log_file' ) if log : logfile = logging . FileHandler ( log ) logfile . setLevel ( lvl ) formatter = logging . Formatter ( log_format , date_format ) logfile . setFormatter ( formatter ) self . logger . addHandler ( logfile ) if self . sentry_client : sentry = SentryHandler ( self . sentry_client ) sentry . setLevel ( logging . ERROR ) self . logger . addHandler ( sentry ) self . logger . debug ( 'Logging setup complete.' )
Setup python logging handler .
404
5
10,723
def setup_path ( self ) : path = self . opts . path or self . config [ 'crony' ] . get ( 'path' ) if path : self . logger . debug ( f'Adding {path} to PATH environment variable' ) self . cmd = f'export PATH={path}:$PATH && {self.cmd}'
Setup PATH env var if necessary .
75
7
10,724
def setup_venv ( self ) : venv = self . opts . venv if not venv : venv = os . environ . get ( 'CRONY_VENV' ) if not venv and self . config [ 'crony' ] : venv = self . config [ 'crony' ] . get ( 'venv' ) if venv : if not venv . endswith ( 'activate' ) : add_path = os . path . join ( 'bin' , 'activate' ) self . logger . debug ( f'Venv directory given, adding {add_path}' ) venv = os . path . join ( venv , add_path ) self . logger . debug ( f'Adding sourcing virtualenv {venv}' ) self . cmd = f'. {venv} && {self.cmd}'
Setup virtualenv if necessary .
187
6
10,725
def get_repos ( path ) : p = str ( path ) ret = [ ] if not os . path . exists ( p ) : return ret for d in os . listdir ( p ) : pd = os . path . join ( p , d ) if os . path . exists ( pd ) and is_repo ( pd ) : ret . append ( Local ( pd ) ) return ret
Returns list of found branches .
88
6
10,726
def get_repo_parent ( path ) : # path is a repository if is_repo ( path ) : return Local ( path ) # path is inside a repository elif not os . path . isdir ( path ) : _rel = '' while path and path != '/' : if is_repo ( path ) : return Local ( path ) else : _rel = os . path . join ( os . path . basename ( path ) , _rel ) path = os . path . dirname ( path ) return path
Returns parent repo or input path if none found .
112
10
10,727
def setVersion ( self , version ) : try : sha = self . versions ( version ) . commit . sha self . git . reset ( "--hard" , sha ) except Exception , e : raise RepoError ( e )
Checkout a version of the repo .
51
8
10,728
def _commits ( self , head = 'HEAD' ) : pending_commits = [ head ] history = [ ] while pending_commits != [ ] : head = pending_commits . pop ( 0 ) try : commit = self [ head ] except KeyError : raise KeyError ( head ) if type ( commit ) != Commit : raise TypeError ( commit ) if commit in history : continue i = 0 for known_commit in history : if known_commit . commit_time > commit . commit_time : break i += 1 history . insert ( i , commit ) pending_commits += commit . parents return history
Returns a list of the commits reachable from head .
131
11
10,729
def versions ( self , version = None ) : try : versions = [ Version ( self , c ) for c in self . _commits ( ) ] except Exception , e : log . debug ( 'No versions exist' ) return [ ] if version is not None and versions : try : versions = versions [ version ] except IndexError : raise VersionError ( 'Version %s does not exist' % version ) return versions
List of Versions of this repository .
87
8
10,730
def setDescription ( self , desc = 'No description' ) : try : self . _put_named_file ( 'description' , desc ) except Exception , e : raise RepoError ( e )
sets repository description
43
3
10,731
def new ( self , path , desc = None , bare = True ) : if os . path . exists ( path ) : raise RepoError ( 'Path already exists: %s' % path ) try : os . mkdir ( path ) if bare : Repo . init_bare ( path ) else : Repo . init ( path ) repo = Local ( path ) if desc : repo . setDescription ( desc ) version = repo . addVersion ( ) version . save ( 'Repo Initialization' ) return repo except Exception , e : traceback . print_exc ( ) raise RepoError ( 'Error creating repo' )
Create a new bare repo . Local instance .
133
9
10,732
def branch ( self , name , desc = None ) : return Local . new ( path = os . path . join ( self . path , name ) , desc = desc , bare = True )
Create a branch of this repo at name .
40
9
10,733
def addItem ( self , item , message = None ) : if message is None : message = 'Adding item %s' % item . path try : v = Version . new ( repo = self ) v . addItem ( item ) v . save ( message ) except VersionError , e : raise RepoError ( e )
add a new Item class object
68
6
10,734
def items ( self , path = None , version = None ) : if version is None : version = - 1 items = { } for item in self . versions ( version ) . items ( ) : items [ item . path ] = item parent = self . parent # get latest committed items from parents while parent : for item in parent . items ( path = path ) : if item . path not in items . keys ( ) : items [ item . path ] = item parent = parent . parent # filter items matching path regex if path is not None : path += '$' regex = re . compile ( path ) return [ item for path , item in items . items ( ) if regex . match ( path ) ] else : return items . values ( )
Returns a list of items .
155
6
10,735
async def set_reply_markup ( msg : Dict , request : 'Request' , stack : 'Stack' ) -> None : from bernard . platforms . telegram . layers import InlineKeyboard , ReplyKeyboard , ReplyKeyboardRemove try : keyboard = stack . get_layer ( InlineKeyboard ) except KeyError : pass else : msg [ 'reply_markup' ] = await keyboard . serialize ( request ) try : keyboard = stack . get_layer ( ReplyKeyboard ) except KeyError : pass else : msg [ 'reply_markup' ] = await keyboard . serialize ( request ) try : remove = stack . get_layer ( ReplyKeyboardRemove ) except KeyError : pass else : msg [ 'reply_markup' ] = remove . serialize ( )
Add the reply markup to a message from the layers
172
10
10,736
def split_locale ( locale : Text ) -> Tuple [ Text , Optional [ Text ] ] : items = re . split ( r'[_\-]' , locale . lower ( ) , 1 ) try : return items [ 0 ] , items [ 1 ] except IndexError : return items [ 0 ] , None
Decompose the locale into a normalized tuple .
65
10
10,737
def compare_locales ( a , b ) : if a is None or b is None : if a == b : return 2 else : return 0 a = split_locale ( a ) b = split_locale ( b ) if a == b : return 2 elif a [ 0 ] == b [ 0 ] : return 1 else : return 0
Compares two locales to find the level of compatibility
74
11
10,738
def list_locales ( self ) -> List [ Optional [ Text ] ] : locales = list ( self . dict . keys ( ) ) if not locales : locales . append ( None ) return locales
Returns the list of available locales . The first locale is the default locale to be used . If no locales are known then None will be the first item .
45
33
10,739
def choose_locale ( self , locale : Text ) -> Text : if locale not in self . _choice_cache : locales = self . list_locales ( ) best_choice = locales [ 0 ] best_level = 0 for candidate in locales : cmp = compare_locales ( locale , candidate ) if cmp > best_level : best_choice = candidate best_level = cmp self . _choice_cache [ locale ] = best_choice return self . _choice_cache [ locale ]
Returns the best matching locale in what is available .
111
10
10,740
def update ( self , new_data : Dict [ Text , Dict [ Text , Text ] ] ) : for locale , data in new_data . items ( ) : if locale not in self . dict : self . dict [ locale ] = { } self . dict [ locale ] . update ( data )
Receive an update from a loader .
65
8
10,741
async def _make_url ( self , url : Text , request : 'Request' ) -> Text : if self . sign_webview : return await request . sign_url ( url ) return url
Signs the URL if needed
43
6
10,742
def is_sharable ( self ) : if self . buttons : return ( all ( b . is_sharable ( ) for b in self . buttons ) and self . default_action and self . default_action . is_sharable ( ) )
Make sure that nothing inside blocks sharing .
56
8
10,743
def check_bounds_variables ( self , dataset ) : recommended_ctx = TestCtx ( BaseCheck . MEDIUM , 'Recommended variables to describe grid boundaries' ) bounds_map = { 'lat_bounds' : { 'units' : 'degrees_north' , 'comment' : 'latitude values at the north and south bounds of each pixel.' } , 'lon_bounds' : { 'units' : 'degrees_east' , 'comment' : 'longitude values at the west and east bounds of each pixel.' } , 'z_bounds' : { 'comment' : 'z bounds for each z value' , } , 'time_bounds' : { 'comment' : 'time bounds for each time value' } } bounds_variables = [ v . bounds for v in dataset . get_variables_by_attributes ( bounds = lambda x : x is not None ) ] for variable in bounds_variables : ncvar = dataset . variables . get ( variable , { } ) recommended_ctx . assert_true ( ncvar != { } , 'a variable {} should exist as indicated by a bounds attribute' . format ( variable ) ) if ncvar == { } : continue units = getattr ( ncvar , 'units' , '' ) if variable in bounds_map and 'units' in bounds_map [ variable ] : recommended_ctx . assert_true ( units == bounds_map [ variable ] [ 'units' ] , 'variable {} should have units {}' . format ( variable , bounds_map [ variable ] [ 'units' ] ) ) else : recommended_ctx . assert_true ( units != '' , 'variable {} should have a units attribute that is not empty' . format ( variable ) ) comment = getattr ( ncvar , 'comment' , '' ) recommended_ctx . assert_true ( comment != '' , 'variable {} should have a comment and not be empty' ) return recommended_ctx . to_result ( )
Checks the grid boundary variables .
430
7
10,744
def geocode ( self , string , bounds = None , region = None , language = None , sensor = False ) : if isinstance ( string , unicode ) : string = string . encode ( 'utf-8' ) params = { 'address' : self . format_string % string , 'sensor' : str ( sensor ) . lower ( ) } if bounds : params [ 'bounds' ] = bounds if region : params [ 'region' ] = region if language : params [ 'language' ] = language if not self . premier : url = self . get_url ( params ) else : url = self . get_signed_url ( params ) return self . GetService_url ( url )
Geocode an address . Pls refer to the Google Maps Web API for the details of the parameters
151
21
10,745
def reverse ( self , point , language = None , sensor = False ) : params = { 'latlng' : point , 'sensor' : str ( sensor ) . lower ( ) } if language : params [ 'language' ] = language if not self . premier : url = self . get_url ( params ) else : url = self . get_signed_url ( params ) return self . GetService_url ( url )
Reverse geocode a point . Pls refer to the Google Maps Web API for the details of the parameters
92
24
10,746
def GetDirections ( self , origin , destination , sensor = False , mode = None , waypoints = None , alternatives = None , avoid = None , language = None , units = None , region = None , departure_time = None , arrival_time = None ) : params = { 'origin' : origin , 'destination' : destination , 'sensor' : str ( sensor ) . lower ( ) } if mode : params [ 'mode' ] = mode if waypoints : params [ 'waypoints' ] = waypoints if alternatives : params [ 'alternatives' ] = alternatives if avoid : params [ 'avoid' ] = avoid if language : params [ 'language' ] = language if units : params [ 'units' ] = units if region : params [ 'region' ] = region if departure_time : params [ 'departure_time' ] = departure_time if arrival_time : params [ 'arrival_time' ] = arrival_time if not self . premier : url = self . get_url ( params ) else : url = self . get_signed_url ( params ) return self . GetService_url ( url )
Get Directions Service Pls refer to the Google Maps Web API for the details of the remained parameters
245
19
10,747
def get ( self ) : self . _cast = type ( [ ] ) source_value = os . getenv ( self . env_name ) # set the environment if it is not set if source_value is None : os . environ [ self . env_name ] = json . dumps ( self . default ) return self . default try : val = json . loads ( source_value ) except JSONDecodeError as e : click . secho ( str ( e ) , err = True , color = 'red' ) sys . exit ( 1 ) except ValueError as e : click . secho ( e . message , err = True , color = 'red' ) sys . exit ( 1 ) if self . validator : val = self . validator ( val ) return val
convert json env variable if set to list
165
9
10,748
def parse_ppi_graph ( path : str , min_edge_weight : float = 0.0 ) -> Graph : logger . info ( "In parse_ppi_graph()" ) graph = igraph . read ( os . path . expanduser ( path ) , format = "ncol" , directed = False , names = True ) graph . delete_edges ( graph . es . select ( weight_lt = min_edge_weight ) ) graph . delete_vertices ( graph . vs . select ( _degree = 0 ) ) logger . info ( f"Loaded PPI network.\n" f"Number of proteins: {len(graph.vs)}\n" f"Number of interactions: {len(graph.es)}\n" ) return graph
Build an undirected graph of gene interactions from edgelist file .
167
15
10,749
def parse_excel ( file_path : str , entrez_id_header , log_fold_change_header , adjusted_p_value_header , entrez_delimiter , base_mean_header = None ) -> List [ Gene ] : logger . info ( "In parse_excel()" ) df = pd . read_excel ( file_path ) return handle_dataframe ( df , entrez_id_name = entrez_id_header , log2_fold_change_name = log_fold_change_header , adjusted_p_value_name = adjusted_p_value_header , entrez_delimiter = entrez_delimiter , base_mean = base_mean_header , )
Read an excel file on differential expression values as Gene objects .
163
12
10,750
def parse_csv ( file_path : str , entrez_id_header , log_fold_change_header , adjusted_p_value_header , entrez_delimiter , base_mean_header = None , sep = "," ) -> List [ Gene ] : logger . info ( "In parse_csv()" ) df = pd . read_csv ( file_path , sep = sep ) return handle_dataframe ( df , entrez_id_name = entrez_id_header , log2_fold_change_name = log_fold_change_header , adjusted_p_value_name = adjusted_p_value_header , entrez_delimiter = entrez_delimiter , base_mean = base_mean_header , )
Read a csv file on differential expression values as Gene objects .
169
13
10,751
def handle_dataframe ( df : pd . DataFrame , entrez_id_name , log2_fold_change_name , adjusted_p_value_name , entrez_delimiter , base_mean = None , ) -> List [ Gene ] : logger . info ( "In _handle_df()" ) if base_mean is not None and base_mean in df . columns : df = df [ pd . notnull ( df [ base_mean ] ) ] df = df [ pd . notnull ( df [ entrez_id_name ] ) ] df = df [ pd . notnull ( df [ log2_fold_change_name ] ) ] df = df [ pd . notnull ( df [ adjusted_p_value_name ] ) ] # try: # import bio2bel_hgnc # except ImportError: # logger.debug('skipping mapping') # else: # manager = bio2bel_hgnc.Manager() # # TODO @cthoyt return [ Gene ( entrez_id = entrez_id , log2_fold_change = data [ log2_fold_change_name ] , padj = data [ adjusted_p_value_name ] ) for _ , data in df . iterrows ( ) for entrez_id in str ( data [ entrez_id_name ] ) . split ( entrez_delimiter ) ]
Convert data frame on differential expression values as Gene objects .
309
12
10,752
def parse_gene_list ( path : str , graph : Graph , anno_type : str = "name" ) -> list : # read the file genes = pd . read_csv ( path , header = None ) [ 0 ] . tolist ( ) genes = [ str ( int ( gene ) ) for gene in genes ] # get those genes which are in the network ind = [ ] if anno_type == "name" : ind = graph . vs . select ( name_in = genes ) . indices elif anno_type == "symbol" : ind = graph . vs . select ( symbol_in = genes ) . indices else : raise Exception ( "The type can either be name or symbol, {} is not " "supported" . format ( anno_type ) ) genes = graph . vs [ ind ] [ anno_type ] return genes
Parse a list of genes and return them if they are in the network .
186
16
10,753
def parse_disease_ids ( path : str ) : if os . path . isdir ( path ) or not os . path . exists ( path ) : logger . info ( "Couldn't find the disease identifiers file. Returning empty list." ) return [ ] df = pd . read_csv ( path , names = [ "ID" ] ) return set ( df [ "ID" ] . tolist ( ) )
Parse the disease identifier file .
91
7
10,754
def parse_disease_associations ( path : str , excluded_disease_ids : set ) : if os . path . isdir ( path ) or not os . path . exists ( path ) : logger . info ( "Couldn't find the disease associations file. Returning empty list." ) return { } disease_associations = defaultdict ( list ) with open ( path ) as input_file : for line in input_file : target_id , disease_id = line . strip ( ) . split ( " " ) if disease_id not in excluded_disease_ids : disease_associations [ target_id ] . append ( disease_id ) return disease_associations
Parse the disease - drug target associations file .
153
10
10,755
def run_server ( chatrooms , use_default_logging = True ) : if use_default_logging : configure_logging ( ) logger . info ( 'Starting Hermes chatroom server...' ) bots = [ ] for name , params in chatrooms . items ( ) : bot_class = params . get ( 'CLASS' , 'hermes.Chatroom' ) if type ( bot_class ) == type : pass else : bot_class_path = bot_class . split ( '.' ) if len ( bot_class_path ) == 1 : module , classname = '__main__' , bot_class_path [ - 1 ] else : module , classname = '.' . join ( bot_class_path [ : - 1 ] ) , bot_class_path [ - 1 ] _ = __import__ ( module , globals ( ) , locals ( ) , [ classname ] ) bot_class = getattr ( _ , classname ) bot = bot_class ( name , params ) bots . append ( bot ) while True : try : logger . info ( "Connecting to servers..." ) sockets = _get_sockets ( bots ) if len ( sockets . keys ( ) ) == 0 : logger . info ( 'No chatrooms defined. Exiting.' ) return _listen ( sockets ) except socket . error , ex : if ex . errno == 9 : logger . exception ( 'broken socket detected' ) else : logger . exception ( 'Unknown socket error %d' % ( ex . errno , ) ) except Exception : logger . exception ( 'Unexpected exception' ) time . sleep ( 1 )
Sets up and serves specified chatrooms . Main entrypoint to Hermes .
349
15
10,756
def _get_sockets ( bots ) : sockets = { } #sockets[sys.stdin] = 'stdio' for bot in bots : bot . connect ( ) sockets [ bot . client . Connection . _sock ] = bot return sockets
Connects and gathers sockets for all chatrooms
54
9
10,757
def _listen ( sockets ) : while True : ( i , o , e ) = select . select ( sockets . keys ( ) , [ ] , [ ] , 1 ) for socket in i : if isinstance ( sockets [ socket ] , Chatroom ) : data_len = sockets [ socket ] . client . Process ( 1 ) if data_len is None or data_len == 0 : raise Exception ( 'Disconnected from server' ) #elif sockets[socket] == 'stdio': # msg = sys.stdin.readline().rstrip('\r\n') # logger.info('stdin: [%s]' % (msg,)) else : raise Exception ( "Unknown socket type: %s" % repr ( sockets [ socket ] ) )
Main server loop . Listens for incoming events and dispatches them to appropriate chatroom
163
17
10,758
def _send ( self , method , path , data , filename ) : if filename is None : return self . _send_json ( method , path , data ) else : return self . _send_file ( method , path , data , filename )
Send data to a remote server either with a POST or a PUT request .
52
16
10,759
def get_platform_settings ( ) : s = settings . PLATFORMS if hasattr ( settings , 'FACEBOOK' ) and settings . FACEBOOK : s . append ( { 'class' : 'bernard.platforms.facebook.platform.Facebook' , 'settings' : settings . FACEBOOK , } ) return s
Returns the content of settings . PLATFORMS with a twist .
70
14
10,760
async def run_checks ( self ) : async for check in self . fsm . health_check ( ) : yield check async for check in self . self_check ( ) : yield check for check in MiddlewareManager . health_check ( ) : yield check
Run checks on itself and on the FSM
56
9
10,761
async def self_check ( self ) : platforms = set ( ) for platform in get_platform_settings ( ) : try : name = platform [ 'class' ] cls : Type [ Platform ] = import_class ( name ) except KeyError : yield HealthCheckFail ( '00004' , 'Missing platform `class` name in configuration.' ) except ( AttributeError , ImportError , ValueError ) : yield HealthCheckFail ( '00003' , f'Platform "{name}" cannot be imported.' ) else : if cls in platforms : yield HealthCheckFail ( '00002' , f'Platform "{name}" is imported more than once.' ) platforms . add ( cls ) # noinspection PyTypeChecker async for check in cls . self_check ( ) : yield check
Checks that the platforms configuration is all right .
170
10
10,762
def _index_classes ( self ) -> Dict [ Text , Type [ Platform ] ] : out = { } for p in get_platform_settings ( ) : cls : Type [ Platform ] = import_class ( p [ 'class' ] ) if 'name' in p : out [ p [ 'name' ] ] = cls else : out [ cls . NAME ] = cls return out
Build a name index for all platform classes
87
8
10,763
async def build_platform ( self , cls : Type [ Platform ] , custom_id ) : from bernard . server . http import router p = cls ( ) if custom_id : p . _id = custom_id await p . async_init ( ) p . on_message ( self . fsm . handle_message ) p . hook_up ( router ) return p
Build the Facebook platform . Nothing fancy .
84
8
10,764
def get_class ( self , platform ) -> Type [ Platform ] : if platform in self . _classes : return self . _classes [ platform ] raise PlatformDoesNotExist ( 'Platform "{}" is not in configuration' . format ( platform ) )
For a given platform name gets the matching class
53
9
10,765
async def get_platform ( self , name : Text ) : if not self . _is_init : await self . init ( ) if name not in self . platforms : self . platforms [ name ] = await self . build_platform ( self . get_class ( name ) , name ) return self . platforms [ name ]
Get a valid instance of the specified platform . Do not cache this object it might change with configuration changes .
69
21
10,766
async def get_all_platforms ( self ) -> AsyncIterator [ Platform ] : for name in self . _classes . keys ( ) : yield await self . get_platform ( name )
Returns all platform instances
42
4
10,767
async def message_from_token ( self , token : Text , payload : Any ) -> Tuple [ Optional [ BaseMessage ] , Optional [ Platform ] ] : async for platform in self . get_all_platforms ( ) : m = await platform . message_from_token ( token , payload ) if m : return m , platform return None , None
Given an authentication token find the right platform that can recognize this token and create a message for this platform .
76
21
10,768
def add_args ( parser , positional = False ) : group = parser . add_argument_group ( "read loading" ) group . add_argument ( "reads" if positional else "--reads" , nargs = "+" , default = [ ] , help = "Paths to bam files. Any number of paths may be specified." ) group . add_argument ( "--read-source-name" , nargs = "+" , help = "Names for each read source. The number of names specified " "must match the number of bam files. If not specified, filenames are " "used for names." ) # Add filters group = parser . add_argument_group ( "read filtering" , "A number of read filters are available. See the pysam " "documentation (http://pysam.readthedocs.org/en/latest/api.html) " "for details on what these fields mean. When multiple filter " "options are specified, reads must match *all* filters." ) for ( name , ( kind , message , function ) ) in READ_FILTERS . items ( ) : extra = { } if kind is bool : extra [ "action" ] = "store_true" extra [ "default" ] = None elif kind is int : extra [ "type" ] = int extra [ "metavar" ] = "N" elif kind is str : extra [ "metavar" ] = "STRING" group . add_argument ( "--" + name . replace ( "_" , "-" ) , help = message , * * extra )
Extends a commandline argument parser with arguments for specifying read sources .
348
14
10,769
def load_from_args ( args ) : if not args . reads : return None if args . read_source_name : read_source_names = util . expand ( args . read_source_name , 'read_source_name' , 'read source' , len ( args . reads ) ) else : read_source_names = util . drop_prefix ( args . reads ) filters = [ ] for ( name , info ) in READ_FILTERS . items ( ) : value = getattr ( args , name ) if value is not None : filters . append ( functools . partial ( info [ - 1 ] , value ) ) return [ load_bam ( filename , name , filters ) for ( filename , name ) in zip ( args . reads , read_source_names ) ]
Given parsed commandline arguments returns a list of ReadSource objects
171
12
10,770
def get_int ( config , key , default ) : try : return int ( config [ key ] ) except ( KeyError , ValueError ) : return default
A helper to retrieve an integer value from a given dictionary containing string values . If the requested value is not present in the dictionary or if it cannot be converted to an integer a default value will be returned instead .
33
42
10,771
def compact_bucket ( db , buck_key , limit ) : # Suck in the bucket records and generate our bucket records = db . lrange ( str ( buck_key ) , 0 , - 1 ) loader = limits . BucketLoader ( limit . bucket_class , db , limit , str ( buck_key ) , records , stop_summarize = True ) # We now have the bucket loaded in; generate a 'bucket' record buck_record = msgpack . dumps ( dict ( bucket = loader . bucket . dehydrate ( ) , uuid = str ( uuid . uuid4 ( ) ) ) ) # Now we need to insert it into the record list result = db . linsert ( str ( buck_key ) , 'after' , loader . last_summarize_rec , buck_record ) # Were we successful? if result < 0 : # Insert failed; we'll try again when max_age is hit LOG . warning ( "Bucket compaction on %s failed; will retry" % buck_key ) return # OK, we have confirmed that the compacted bucket record has been # inserted correctly; now all we need to do is trim off the # outdated update records db . ltrim ( str ( buck_key ) , loader . last_summarize_idx + 1 , - 1 )
Perform the compaction operation . This reads in the bucket information from the database builds a compacted bucket record inserts that record in the appropriate place in the database then removes outdated updates .
285
37
10,772
def compactor ( conf ) : # Get the database handle db = conf . get_database ( 'compactor' ) # Get the limits container limit_map = LimitContainer ( conf , db ) # Get the compactor configuration config = conf [ 'compactor' ] # Make sure compaction is enabled if get_int ( config , 'max_updates' , 0 ) <= 0 : # We'll just warn about it, since they could be running # the compactor with a different configuration file LOG . warning ( "Compaction is not enabled. Enable it by " "setting a positive integer value for " "'compactor.max_updates' in the configuration." ) # Select the bucket key getter key_getter = GetBucketKey . factory ( config , db ) LOG . info ( "Compactor initialized" ) # Now enter our loop while True : # Get a bucket key to compact try : buck_key = limits . BucketKey . decode ( key_getter ( ) ) except ValueError as exc : # Warn about invalid bucket keys LOG . warning ( "Error interpreting bucket key: %s" % exc ) continue # Ignore version 1 keys--they can't be compacted if buck_key . version < 2 : continue # Get the corresponding limit class try : limit = limit_map [ buck_key . uuid ] except KeyError : # Warn about missing limits LOG . warning ( "Unable to compact bucket for limit %s" % buck_key . uuid ) continue LOG . debug ( "Compacting bucket %s" % buck_key ) # OK, we now have the limit (which we really only need for # the bucket class); let's compact the bucket try : compact_bucket ( db , buck_key , limit ) except Exception : LOG . exception ( "Failed to compact bucket %s" % buck_key ) else : LOG . debug ( "Finished compacting bucket %s" % buck_key )
The compactor daemon . This fuction watches the sorted set containing bucket keys that need to be compacted performing the necessary compaction .
411
27
10,773
def factory ( cls , config , db ) : # Make sure that the client supports register_script() if not hasattr ( db , 'register_script' ) : LOG . debug ( "Redis client does not support register_script()" ) return GetBucketKeyByLock ( config , db ) # OK, the client supports register_script(); what about the # server? info = db . info ( ) if version_greater ( '2.6' , info [ 'redis_version' ] ) : LOG . debug ( "Redis server supports register_script()" ) return GetBucketKeyByScript ( config , db ) # OK, use our fallback... LOG . debug ( "Redis server does not support register_script()" ) return GetBucketKeyByLock ( config , db )
Given a configuration and database select and return an appropriate instance of a subclass of GetBucketKey . This will ensure that both client and server support are available for the Lua script feature of Redis and if not a lock will be used .
175
48
10,774
def get ( self , now ) : with self . lock : items = self . db . zrangebyscore ( self . key , 0 , now - self . min_age , start = 0 , num = 1 ) # Did we get any items? if not items : return None # Drop the item we got item = items [ 0 ] self . db . zrem ( item ) return item
Get a bucket key to compact . If none are available returns None . This uses a configured lock to ensure that the bucket key is popped off the sorted set in an atomic fashion .
82
36
10,775
def get ( self , now ) : items = self . script ( keys = [ self . key ] , args = [ now - self . min_age ] ) return items [ 0 ] if items else None
Get a bucket key to compact . If none are available returns None . This uses a Lua script to ensure that the bucket key is popped off the sorted set in an atomic fashion .
43
36
10,776
def parse ( text , elements , fallback ) : # this is a raw list of elements that may contain overlaps. tokens = [ ] for etype in elements : for match in etype . find ( text ) : tokens . append ( Token ( etype , match , text , fallback ) ) tokens . sort ( ) tokens = _resolve_overlap ( tokens ) return make_elements ( tokens , text , fallback = fallback )
Parse given text and produce a list of inline elements .
95
12
10,777
def make_elements ( tokens , text , start = 0 , end = None , fallback = None ) : result = [ ] end = end or len ( text ) prev_end = start for token in tokens : if prev_end < token . start : result . append ( fallback ( text [ prev_end : token . start ] ) ) result . append ( token . as_element ( ) ) prev_end = token . end if prev_end < end : result . append ( fallback ( text [ prev_end : end ] ) ) return result
Make elements from a list of parsed tokens . It will turn all unmatched holes into fallback elements .
119
20
10,778
def main_cli ( ) : # Get params args = _cli_argument_parser ( ) delta_secs = args . delay i2cbus = args . bus i2c_address = args . address sensor_key = args . sensor sensor_params = args . params params = { } if sensor_params : def _parse_param ( str_param ) : key , value = str_param . split ( '=' ) try : value = int ( value ) except ValueError : pass return { key . strip ( ) : value } [ params . update ( _parse_param ( sp ) ) for sp in sensor_params ] if sensor_key : from time import sleep # Bus init try : # noinspection PyUnresolvedReferences import smbus bus_handler = smbus . SMBus ( i2cbus ) except ImportError as exc : print ( exc , "\n" , "Please install smbus-cffi before." ) sys . exit ( - 1 ) # Sensor selection try : sensor_handler , i2c_default_address = SENSORS [ sensor_key ] except KeyError : print ( "'%s' is not recognized as an implemented i2c sensor." % sensor_key ) sys . exit ( - 1 ) if i2c_address : i2c_address = hex ( int ( i2c_address , 0 ) ) else : i2c_address = i2c_default_address # Sensor init sensor = sensor_handler ( bus_handler , i2c_address , * * params ) # Infinite loop try : while True : sensor . update ( ) if not sensor . sample_ok : print ( "An error has occured." ) break print ( sensor . current_state_str ) sleep ( delta_secs ) except KeyboardInterrupt : print ( "Bye!" ) else : # Run detection mode from subprocess import check_output cmd = '/usr/sbin/i2cdetect -y {}' . format ( i2cbus ) try : output = check_output ( cmd . split ( ) ) print ( "Running i2cdetect utility in i2c bus {}:\n" "The command '{}' has returned:\n{}" . format ( i2cbus , cmd , output . decode ( ) ) ) except FileNotFoundError : print ( "Please install i2cdetect before." ) sys . exit ( - 1 ) # Parse output addresses = [ '0x' + l for line in output . decode ( ) . splitlines ( ) [ 1 : ] for l in line . split ( ) [ 1 : ] if l != '--' ] if addresses : print ( "{} sensors detected in {}" . format ( len ( addresses ) , ', ' . join ( addresses ) ) ) else : print ( "No i2c sensors detected." )
CLI minimal interface .
610
5
10,779
def extract_domain ( var_name , output ) : var = getenv ( var_name ) if var : p = urlparse ( var ) output . append ( p . hostname )
Extracts just the domain name from an URL and adds it to a list
40
16
10,780
def numchannels ( samples : np . ndarray ) -> int : if len ( samples . shape ) == 1 : return 1 else : return samples . shape [ 1 ]
return the number of channels present in samples
37
8
10,781
def turnstile_filter ( global_conf , * * local_conf ) : # Select the appropriate middleware class to return klass = TurnstileMiddleware if 'turnstile' in local_conf : klass = utils . find_entrypoint ( 'turnstile.middleware' , local_conf [ 'turnstile' ] , required = True ) def wrapper ( app ) : return klass ( app , local_conf ) return wrapper
Factory function for turnstile .
99
7
10,782
def format_delay ( self , delay , limit , bucket , environ , start_response ) : # Set up the default status status = self . conf . status # Set up the retry-after header... headers = HeadersDict ( [ ( 'Retry-After' , "%d" % math . ceil ( delay ) ) ] ) # Let format fiddle with the headers status , entity = limit . format ( status , headers , environ , bucket , delay ) # Return the response start_response ( status , headers . items ( ) ) return entity
Formats the over - limit response for the request . May be overridden in subclasses to allow alternate responses .
119
23
10,783
def find_entrypoint ( group , name , compat = True , required = False ) : if group is None or ( compat and ':' in name ) : try : return pkg_resources . EntryPoint . parse ( "x=" + name ) . load ( False ) except ( ImportError , pkg_resources . UnknownExtra ) as exc : pass else : for ep in pkg_resources . iter_entry_points ( group , name ) : try : # Load and return the object return ep . load ( ) except ( ImportError , pkg_resources . UnknownExtra ) : # Couldn't load it; try the next one continue # Raise an ImportError if requested if required : raise ImportError ( "Cannot import %r entrypoint %r" % ( group , name ) ) # Couldn't find one... return None
Finds the first available entrypoint with the given name in the given group .
176
16
10,784
def transfer ( self , transfer_payload = None , * , from_user , to_user ) : if self . persist_id is None : raise EntityNotYetPersistedError ( ( 'Entities cannot be transferred ' 'until they have been ' 'persisted' ) ) return self . plugin . transfer ( self . persist_id , transfer_payload , from_user = from_user , to_user = to_user )
Transfer this entity to another owner on the backing persistence layer
94
11
10,785
def transfer ( self , rights_assignment_data = None , * , from_user , to_user , rights_assignment_format = 'jsonld' ) : rights_assignment = RightsAssignment . from_data ( rights_assignment_data or { } , plugin = self . plugin ) transfer_payload = rights_assignment . _to_format ( data_format = rights_assignment_format ) transfer_id = super ( ) . transfer ( transfer_payload , from_user = from_user , to_user = to_user ) rights_assignment . persist_id = transfer_id return rights_assignment
Transfer this Right to another owner on the backing persistence layer .
140
12
10,786
def _set_repo ( self , url ) : if url . startswith ( 'http' ) : try : self . repo = Proxy ( url ) except ProxyError , e : log . exception ( 'Error setting repo: %s' % url ) raise GritError ( e ) else : try : self . repo = Local ( url ) except NotGitRepository : raise GritError ( 'Invalid url: %s' % url ) except Exception , e : log . exception ( 'Error setting repo: %s' % url ) raise GritError ( e )
sets the underlying repo object
123
5
10,787
def new ( self , url , clone_from = None , bare = True ) : #note to self: look into using templates (--template) if clone_from : self . clone ( path = url , bare = bare ) else : if url . startswith ( 'http' ) : proxy = Proxy ( url ) proxy . new ( path = url , bare = bare ) else : local = Local . new ( path = url , bare = bare ) return Repo ( url )
Creates a new Repo instance .
102
8
10,788
def CheckEmails ( self , checkTypo = False , fillWrong = True ) : self . wrong_emails = [ ] for email in self . emails : if self . CheckEmail ( email , checkTypo ) is False : self . wrong_emails . append ( email )
Checks Emails in List Wether they are Correct or not
62
12
10,789
def CheckEmail ( self , email , checkTypo = False ) : contents = email . split ( '@' ) if len ( contents ) == 2 : if contents [ 1 ] in self . valid : return True return False
Checks a Single email if it is correct
47
9
10,790
def CorrectWrongEmails ( self , askInput = True ) : for email in self . wrong_emails : corrected_email = self . CorrectEmail ( email ) self . emails [ self . emails . index ( email ) ] = corrected_email self . wrong_emails = [ ]
Corrects Emails in wrong_emails
62
8
10,791
def CorrectEmail ( self , email ) : print ( "Wrong Email : " + email ) contents = email . split ( '@' ) if len ( contents ) == 2 : domain_data = contents [ 1 ] . split ( '.' ) for vemail in self . valid : alters = perms ( vemail . split ( '.' , 1 ) [ 0 ] ) if domain_data [ 0 ] in alters and qyn . query_yes_no ( "Did you mean : " + contents [ 0 ] + '@' + vemail ) is True : return contents [ 0 ] + '@' + vemail corrected = input ( 'Enter Corrected Email : ' ) while self . CheckEmail ( corrected ) is False : corrected = input ( 'PLEASE Enter "Corrected" Email : ' ) return corrected else : print ( 'Looks like you missed/overused `@`' ) if len ( contents ) == 1 : for vemail in self . valid : if email [ len ( email ) - len ( vemail ) : ] == vemail and qyn . query_yes_no ( "Did you mean : " + email [ : len ( email ) - len ( vemail ) ] + '@' + vemail ) is True : return email [ : len ( email ) - len ( vemail ) ] + '@' + vemail corrected = input ( 'Enter Corrected Email : ' ) while self . CheckEmail ( corrected ) is False : corrected = input ( 'PLEASE Enter "Corrected" Email : ' ) return corrected
Returns a Corrected email USER INPUT REQUIRED
329
12
10,792
def add_element ( self , element , override = False ) : if issubclass ( element , inline . InlineElement ) : dest = self . inline_elements elif issubclass ( element , block . BlockElement ) : dest = self . block_elements else : raise TypeError ( 'The element should be a subclass of either `BlockElement` or ' '`InlineElement`.' ) if not override : dest [ element . __name__ ] = element else : for cls in element . __bases__ : if cls in dest . values ( ) : dest [ cls . __name__ ] = element break else : dest [ element . __name__ ] = element
Add an element to the parser .
148
7
10,793
def parse ( self , source_or_text ) : if isinstance ( source_or_text , string_types ) : block . parser = self inline . parser = self return self . block_elements [ 'Document' ] ( source_or_text ) element_list = self . _build_block_element_list ( ) ast = [ ] while not source_or_text . exhausted : for ele_type in element_list : if ele_type . match ( source_or_text ) : result = ele_type . parse ( source_or_text ) if not hasattr ( result , 'priority' ) : result = ele_type ( result ) ast . append ( result ) break else : # Quit the current parsing and go back to the last level. break return ast
Do the actual parsing and returns an AST or parsed element .
168
12
10,794
def parse_inline ( self , text ) : element_list = self . _build_inline_element_list ( ) return inline_parser . parse ( text , element_list , fallback = self . inline_elements [ 'RawText' ] )
Parses text into inline elements . RawText is not considered in parsing but created as a wrapper of holes that don t match any other elements .
55
30
10,795
def _build_block_element_list ( self ) : return sorted ( [ e for e in self . block_elements . values ( ) if not e . virtual ] , key = lambda e : e . priority , reverse = True )
Return a list of block elements ordered from highest priority to lowest .
51
13
10,796
def make_app ( * args , * * kw ) : default_options = [ [ 'content_path' , '.' ] , [ 'uri_marker' , '' ] ] args = list ( args ) options = dict ( default_options ) options . update ( kw ) while default_options and args : _d = default_options . pop ( 0 ) _a = args . pop ( 0 ) options [ _d [ 0 ] ] = _a options [ 'content_path' ] = os . path . abspath ( options [ 'content_path' ] . decode ( 'utf8' ) ) options [ 'uri_marker' ] = options [ 'uri_marker' ] . decode ( 'utf8' ) selector = WSGIHandlerSelector ( ) git_inforefs_handler = GitHTTPBackendInfoRefs ( * * options ) git_rpc_handler = GitHTTPBackendSmartHTTP ( * * options ) static_handler = StaticServer ( * * options ) file_handler = FileServer ( * * options ) json_handler = JSONServer ( * * options ) ui_handler = UIServer ( * * options ) if options [ 'uri_marker' ] : marker_regex = r'(?P<decorative_path>.*?)(?:/' + options [ 'uri_marker' ] + ')' else : marker_regex = '' selector . add ( marker_regex + r'(?P<working_path>.*?)/info/refs\?.*?service=(?P<git_command>git-[^&]+).*$' , GET = git_inforefs_handler , HEAD = git_inforefs_handler ) selector . add ( marker_regex + r'(?P<working_path>.*)/(?P<git_command>git-[^/]+)$' , POST = git_rpc_handler ) selector . add ( marker_regex + r'/static/(?P<working_path>.*)$' , GET = static_handler , HEAD = static_handler ) selector . add ( marker_regex + r'(?P<working_path>.*)/file$' , GET = file_handler , HEAD = file_handler ) selector . add ( marker_regex + r'(?P<working_path>.*)$' , GET = ui_handler , POST = json_handler , HEAD = ui_handler ) return selector
Assembles basic WSGI - compatible application providing functionality of git - http - backend .
543
18
10,797
def now ( tzinfo = True ) : if dj_now : return dj_now ( ) if tzinfo : # timeit shows that datetime.now(tz=utc) is 24% slower return datetime . utcnow ( ) . replace ( tzinfo = utc ) return datetime . now ( )
Return an aware or naive datetime . datetime depending on settings . USE_TZ .
71
19
10,798
def match_unit ( data , p , m = 'a' ) : if data is None : return p is None # compile search value only once for non exact search if m != 'e' and isinstance ( p , six . string_types ) : p = re . compile ( p ) if isinstance ( data , Sequence ) and not isinstance ( data , six . string_types ) : return any ( [ match_unit ( field , p , m = m ) for field in data ] ) elif isinstance ( data , MutableMapping ) : return any ( [ match_unit ( field , p , m = m ) for field in data . values ( ) ] ) # Inclusive range query if isinstance ( p , tuple ) : left , right = p return ( left <= data ) and ( data <= right ) if m == 'e' : return six . text_type ( data ) == p return p . search ( six . text_type ( data ) ) is not None
Match data to basic match unit .
211
7
10,799
def generate_ppi_network ( ppi_graph_path : str , dge_list : List [ Gene ] , max_adj_p : float , max_log2_fold_change : float , min_log2_fold_change : float , ppi_edge_min_confidence : Optional [ float ] = None , current_disease_ids_path : Optional [ str ] = None , disease_associations_path : Optional [ str ] = None , ) -> Network : # Compilation of a protein-protein interaction (PPI) graph (HIPPIE) protein_interactions = parsers . parse_ppi_graph ( ppi_graph_path , ppi_edge_min_confidence ) protein_interactions = protein_interactions . simplify ( ) if disease_associations_path is not None and current_disease_ids_path is not None : current_disease_ids = parsers . parse_disease_ids ( current_disease_ids_path ) disease_associations = parsers . parse_disease_associations ( disease_associations_path , current_disease_ids ) else : disease_associations = None # Build an undirected weighted graph with the remaining interactions based on Entrez gene IDs network = Network ( protein_interactions , max_adj_p = max_adj_p , max_l2fc = max_log2_fold_change , min_l2fc = min_log2_fold_change , ) network . set_up_network ( dge_list , disease_associations = disease_associations ) return network
Generate the protein - protein interaction network .
367
9