signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def countDirectlyConnected ( port : LPort , result : dict ) -> int : """Count how many ports are directly connected to other nodes : return : cumulative sum of port counts"""
inEdges = port . incomingEdges outEdges = port . outgoingEdges if port . children : ch_cnt = 0 # try : # assert not inEdges , ( port , port . children , inEdges ) # assert not outEdges , ( port , port . children , outEdges ) # except AssertionError : # raise for ch in port . children : ...
def rooms ( self , sid , namespace = None ) : """Return the rooms a client is in . The only difference with the : func : ` socketio . Server . rooms ` method is that when the ` ` namespace ` ` argument is not given the namespace associated with the class is used ."""
return self . server . rooms ( sid , namespace = namespace or self . namespace )
def b58decode ( v , length ) : """decode v into a string of len bytes ."""
long_value = 0 for ( i , c ) in enumerate ( v [ : : - 1 ] ) : long_value += __b58chars . find ( c ) * ( __b58base ** i ) result = b'' while long_value >= 256 : div , mod = divmod ( long_value , 256 ) result = struct . pack ( 'B' , mod ) + result long_value = div result = struct . pack ( 'B' , long_value...
def submit_job ( self , halt_on_error = True ) : """Submit Batch request to ThreatConnect API ."""
# check global setting for override if self . halt_on_batch_error is not None : halt_on_error = self . halt_on_batch_error try : r = self . tcex . session . post ( '/v2/batch' , json = self . settings ) except Exception as e : self . tcex . handle_error ( 10505 , [ e ] , halt_on_error ) if not r . ok or 'ap...
def all_linked_artifacts_exist ( self ) : """All of the artifact paths for this resolve point to existing files ."""
if not self . has_resolved_artifacts : return False for path in self . resolved_artifact_paths : if not os . path . isfile ( path ) : return False else : return True
def _add_links ( self , links , key = "href" , proxy_key = "proxyURL" , endpoints = None ) : """Parses and adds block of links"""
if endpoints is None : endpoints = [ "likes" , "replies" , "shares" , "self" , "followers" , "following" , "lists" , "favorites" , "members" ] if links . get ( "links" ) : for endpoint in links [ 'links' ] : # It would seem occasionally the links [ " links " ] [ endpoint ] is # just a string ( what would be...
def urls_old ( self , protocol = Resource . Protocol . http ) : '''Iterate through all resources registered with this router and create a list endpoint and a detail endpoint for each one . Uses the router name as prefix and endpoint name of the resource when registered , to assemble the url pattern . Uses the...
url_patterns = [ ] for endpoint , resource_class in self . _registry . items ( ) : setattr ( resource_class , 'api_name' , self . name ) setattr ( resource_class , 'resource_name' , endpoint ) # append any nested resources the resource may have nested = [ ] for route in resource_class . nested_route...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'field' ) and self . field is not None : _dict [ 'field' ] = self . field if hasattr ( self , 'value' ) and self . value is not None : _dict [ 'value' ] = self . value return _dict
def download_era5_for_gssha ( main_directory , start_datetime , end_datetime , leftlon = - 180 , rightlon = 180 , toplat = 90 , bottomlat = - 90 , precip_only = False ) : """Function to download ERA5 data for GSSHA . . note : : https : / / software . ecmwf . int / wiki / display / WEBAPI / Access + ECMWF + Public...
# parameters : https : / / software . ecmwf . int / wiki / display / CKB / ERA5 _ test + data + documentation # ERA5 _ testdatadocumentation - Parameterlistings # import here to make sure it is not required to run from ecmwfapi import ECMWFDataServer server = ECMWFDataServer ( ) try : mkdir ( main_directory ) excep...
def reactions ( self , tag , data , reactors ) : '''Render a list of reactor files and returns a reaction struct'''
log . debug ( 'Compiling reactions for tag %s' , tag ) high = { } chunks = [ ] try : for fn_ in reactors : high . update ( self . render_reaction ( fn_ , tag , data ) ) if high : errors = self . verify_high ( high ) if errors : log . error ( 'Unable to render reactions for ev...
def _update_pdf ( population , fitnesses , pdfs , quantile ) : """Find a better pdf , based on fitnesses ."""
# First we determine a fitness threshold based on a quantile of fitnesses fitness_threshold = _get_quantile_cutoff ( fitnesses , quantile ) # Then check all of our possible pdfs with a stochastic program return _best_pdf ( pdfs , population , fitnesses , fitness_threshold )
def query_single_page ( query , lang , pos , retry = 50 , from_user = False ) : """Returns tweets from the given URL . : param query : The query parameter of the query url : param lang : The language parameter of the query url : param pos : The query url parameter that determines where to start looking : pa...
url = get_query_url ( query , lang , pos , from_user ) try : response = requests . get ( url , headers = HEADER ) if pos is None : # html response html = response . text or '' json_resp = None else : html = '' try : json_resp = json . loads ( response . text ) ...
def _decode_var ( cls , string ) : """Decodes a given string into the appropriate type in Python . : param str string : The string to decode : return : The decoded value"""
str_match = cls . quoted_string_regex . match ( string ) if str_match : return string . strip ( "'" if str_match . groups ( ) [ 0 ] else '"' ) # NOTE : " 1 " . isdigit ( ) results in True because they are idiots elif string . isdigit ( ) and cls . is_digit_regex . match ( string ) is not None : return int ( str...
def size ( self ) : """The size of this parameter , equivalent to self . value . size"""
return np . multiply . reduce ( self . shape , dtype = np . int32 )
def validate_work_spec ( cls , work_spec ) : '''Check that ` work _ spec ` is valid . It must at the very minimum contain a ` ` name ` ` and ` ` min _ gb ` ` . : raise rejester . exceptions . ProgrammerError : if it isn ' t valid'''
if 'name' not in work_spec : raise ProgrammerError ( 'work_spec lacks "name"' ) if 'min_gb' not in work_spec or not isinstance ( work_spec [ 'min_gb' ] , ( float , int , long ) ) : raise ProgrammerError ( 'work_spec["min_gb"] must be a number' )
def list_datastores_full ( kwargs = None , call = None ) : '''List all the datastores for this VMware environment , with extra information CLI Example : . . code - block : : bash salt - cloud - f list _ datastores _ full my - vmware - config'''
if call != 'function' : raise SaltCloudSystemExit ( 'The list_datastores_full function must be called with ' '-f or --function.' ) return { 'Datastores' : salt . utils . vmware . list_datastores_full ( _get_si ( ) ) }
def owner ( self , owner ) : """Sets the owner of this OauthTokenReference . User name of the owner of the OAuth token within data . world . : param owner : The owner of this OauthTokenReference . : type : str"""
if owner is None : raise ValueError ( "Invalid value for `owner`, must not be `None`" ) if owner is not None and len ( owner ) > 31 : raise ValueError ( "Invalid value for `owner`, length must be less than or equal to `31`" ) if owner is not None and len ( owner ) < 3 : raise ValueError ( "Invalid value for...
def get_random_condcount ( mode ) : """HITs can be in one of three states : - jobs that are finished - jobs that are started but not finished - jobs that are never going to finish ( user decided not to do it ) Our count should be based on the first two , so we count any tasks finished or any tasks not fin...
cutofftime = datetime . timedelta ( minutes = - CONFIG . getint ( 'Server Parameters' , 'cutoff_time' ) ) starttime = datetime . datetime . now ( ) + cutofftime try : conditions = json . load ( open ( os . path . join ( app . root_path , 'conditions.json' ) ) ) numconds = len ( conditions . keys ( ) ) numco...
def all_conditional_state_variables_read ( self , include_loop = True ) : """Return the state variable used in a condition Over approximate and also return index access It won ' t work if the variable is assigned to a temp variable"""
if include_loop : if self . _all_conditional_state_variables_read_with_loop is None : self . _all_conditional_state_variables_read_with_loop = self . _explore_functions ( lambda x : self . _explore_func_cond_read ( x , include_loop ) ) return self . _all_conditional_state_variables_read_with_loop else :...
def make_query ( self , return_score = False ) : """Return the index of the sample to be queried and labeled and selection score of each sample . Read - only . No modification to the internal states . Returns ask _ id : int The index of the next unlabeled sample to be queried and labeled . score : list ...
dataset = self . dataset self . model . train ( dataset ) unlabeled_entry_ids , X_pool = zip ( * dataset . get_unlabeled_entries ( ) ) if isinstance ( self . model , ProbabilisticModel ) : dvalue = self . model . predict_proba ( X_pool ) elif isinstance ( self . model , ContinuousModel ) : dvalue = self . model...
def firstVariant ( ) : """first variant of Variants Read - only"""
def fget ( self ) : if self . variants : return self . variants [ 0 ] else : variant = Variant ( ) return variant return locals ( )
def get_errvar_dataframe ( self , singular_values = None ) : """get a pandas dataframe of error variance results indexed on singular value and ( prediction name , < errvar term > ) Parameters singular _ values : list singular values to test . defaults to range ( 0 , min ( nnz _ obs , nadj _ par ) + 1) R...
if singular_values is None : singular_values = np . arange ( 0 , min ( self . pst . nnz_obs , self . pst . npar_adj ) + 1 ) if not isinstance ( singular_values , list ) and not isinstance ( singular_values , np . ndarray ) : singular_values = [ singular_values ] results = { } for singular_value in singular_valu...
def close_transport ( self ) : """Forcibly close previously acquired media transport . . . note : : The user should first make sure any transport event handlers are unregistered first ."""
if ( self . path ) : self . _release_media_transport ( self . path , self . access_type ) self . path = None
def init_app ( self , app ) : '''Initializes the Flask application with this extension . It grabs the necessary configuration values from ` ` app . config ` ` , those being HASHING _ METHOD and HASHING _ ROUNDS . HASHING _ METHOD defaults to ` ` sha256 ` ` but can be any one of ` ` hashlib . algorithms ` ` . ...
self . algorithm = app . config . get ( 'HASHING_METHOD' , 'sha256' ) if self . algorithm not in algs : raise ValueError ( '{} not one of {}' . format ( self . algorithm , algs ) ) self . rounds = app . config . get ( 'HASHING_ROUNDS' , 1 ) if not isinstance ( self . rounds , int ) : raise TypeError ( 'HASHING_...
def checkout_commit ( repo_path : str , commit : Any = None ) -> None : # pylint : disable = redefined - outer - name """Checkout to a specific commit . If commit is None then checkout to master ."""
commit = commit or 'master' run_command ( cmd = 'git checkout {}' . format ( commit ) , data = None , location = repo_path , chw = True )
def _item_to_metric ( iterator , log_metric_pb ) : """Convert a metric protobuf to the native object . : type iterator : : class : ` ~ google . api _ core . page _ iterator . Iterator ` : param iterator : The iterator that is currently in use . : type log _ metric _ pb : : class : ` . logging _ metrics _ pb...
# NOTE : LogMetric message type does not have an ` ` Any ` ` field # so ` MessageToDict ` ` can safely be used . resource = MessageToDict ( log_metric_pb ) return Metric . from_api_repr ( resource , iterator . client )
def discordian_calendar ( season = None , year = None , dtobj = None ) : """Prints a discordian calendar for a particular season and year . Args : : season : integer cardinal season from 1 to 5 year : integer discordian year from 1166 to MAXYEAR + 1166 dtobj : datetime object to instatiate the calendar from...
now = DDate ( dtobj ) moved_year = None if season is None : season = now . season elif season . lower ( ) == "next" : season , moved_year = _season_overflow ( now . season or 0 + 1 , moved_year , now ) else : # allow for + 1 , - 2 , for seasons . . . for symbol , oper in zip ( ( "+" , "-" ) , ( operator . a...
def _get_all_resourcescenarios ( network_id , user_id ) : """Get all the resource scenarios in a network , across all scenarios returns a dictionary of dict objects , keyed on scenario _ id"""
rs_qry = db . DBSession . query ( Dataset . type , Dataset . unit_id , Dataset . name , Dataset . hash , Dataset . cr_date , Dataset . created_by , Dataset . hidden , Dataset . value , ResourceScenario . dataset_id , ResourceScenario . scenario_id , ResourceScenario . resource_attr_id , ResourceScenario . source , Reso...
def file_upload_notification ( self , area_uuid , filename ) : """Notify Upload Service that a file has been placed in an Upload Area : param str area _ uuid : A RFC4122 - compliant ID for the upload area : param str filename : The name the file in the Upload Area : return : True : rtype : bool : raises U...
url_safe_filename = urlparse . quote ( filename ) path = ( "/area/{area_uuid}/{filename}" . format ( area_uuid = area_uuid , filename = url_safe_filename ) ) response = self . _make_request ( 'post' , path = path ) return response . ok
def deltas ( self , start , height ) : """Return a list - like ( i . e . iterable ) object of ( y , x ) tuples"""
for y in range ( start , min ( start + height , self . _height ) ) : for x in range ( self . _width ) : old_cell = self . _screen_buffer [ y ] [ x ] new_cell = self . _double_buffer [ y ] [ x ] if old_cell != new_cell : yield y , x
def _structure_set ( self , obj , cl ) : """Convert an iterable into a potentially generic set ."""
if is_bare ( cl ) or cl . __args__ [ 0 ] is Any : return set ( obj ) else : elem_type = cl . __args__ [ 0 ] return { self . _structure_func . dispatch ( elem_type ) ( e , elem_type ) for e in obj }
def execute ( self , connection_id , statement_id , signature , parameter_values = None , first_frame_max_size = None ) : """Returns a frame of rows . The frame describes whether there may be another frame . If there is not another frame , the current iteration is done when we have finished the rows in the th...
request = requests_pb2 . ExecuteRequest ( ) request . statementHandle . id = statement_id request . statementHandle . connection_id = connection_id request . statementHandle . signature . CopyFrom ( signature ) if parameter_values is not None : request . parameter_values . extend ( parameter_values ) request . ...
def drop_constant_column_levels ( df ) : """drop the levels of a multi - level column dataframe which are constant operates in place"""
columns = df . columns constant_levels = [ i for i , level in enumerate ( columns . levels ) if len ( level ) <= 1 ] constant_levels . reverse ( ) for i in constant_levels : columns = columns . droplevel ( i ) df . columns = columns
async def proxy ( self , port , proxied_path ) : '''This serverextension handles : { base _ url } / proxy / { port ( [ 0-9 ] + ) } / { proxied _ path } { base _ url } / proxy / absolute / { port ( [ 0-9 ] + ) } / { proxied _ path } { base _ url } / { proxy _ base } / { proxied _ path }'''
if 'Proxy-Connection' in self . request . headers : del self . request . headers [ 'Proxy-Connection' ] self . _record_activity ( ) if self . request . headers . get ( "Upgrade" , "" ) . lower ( ) == 'websocket' : # We wanna websocket ! # jupyterhub / jupyter - server - proxy @ 36b3214 self . log . info ( "we w...
def set_primary_contact ( self , email ) : """assigns the primary contact for this client"""
params = { "email" : email } response = self . _put ( self . uri_for ( 'primarycontact' ) , params = params ) return json_to_py ( response )
def argument ( self , * args , ** kwargs ) : """Registers a click . argument which falls back to a configmanager Item if user hasn ' t provided a value in the command line . Item must be the last of ` ` args ` ` ."""
if kwargs . get ( 'required' , True ) : raise TypeError ( 'In click framework, arguments are mandatory, unless marked required=False. ' 'Attempt to use configmanager as a fallback provider suggests that this is an optional option, ' 'not a mandatory argument.' ) args , kwargs = _config_parameter ( args , kwargs ) r...
async def write ( self ) : """Code borrowed from StrictRedis so it can be fixed"""
connection = self . connection commands = self . commands # We are going to clobber the commands with the write , so go ahead # and ensure that nothing is sitting there from a previous run . for c in commands : c . result = None # build up all commands into a single request to increase network perf # send all the c...
def show ( self ) : """Create the Toplevel widget and its child widgets to show in the spot of the cursor . This is the callback for the delayed : obj : ` < Enter > ` event ( see : meth : ` ~ Balloon . _ on _ enter ` ) ."""
self . _toplevel = tk . Toplevel ( self . master ) self . _canvas = tk . Canvas ( self . _toplevel , background = self . __background ) self . header_label = ttk . Label ( self . _canvas , text = self . __headertext , background = self . __background , image = self . _photo_image , compound = tk . LEFT ) self . text_la...
def update_voice_model ( self , customization_id , name = None , description = None , words = None , ** kwargs ) : """Update a custom model . Updates information for the specified custom voice model . You can update metadata such as the name and description of the voice model . You can also update the words i...
if customization_id is None : raise ValueError ( 'customization_id must be provided' ) if words is not None : words = [ self . _convert_model ( x , Word ) for x in words ] headers = { } if 'headers' in kwargs : headers . update ( kwargs . get ( 'headers' ) ) sdk_headers = get_sdk_headers ( 'text_to_speech' ...
def get_performance_data ( self , project , ** params ) : '''Gets a dictionary of PerformanceSeries objects You can specify which signatures to get by passing signature to this function'''
results = self . _get_json ( self . PERFORMANCE_DATA_ENDPOINT , project , ** params ) return { k : PerformanceSeries ( v ) for k , v in results . items ( ) }
def _unpack_object_array ( inp , source , prescatter ) : """Unpack Array [ Object ] with a scatter for referencing in input calls . There is no shorthand syntax for referencing all items in an array , so we explicitly unpack them with a scatter ."""
raise NotImplementedError ( "Currently not used with record/struct/object improvements" ) base_rec , attr = source . rsplit ( "." , 1 ) new_name = "%s_%s_unpack" % ( inp [ "name" ] , base_rec . replace ( "." , "_" ) ) prescatter [ base_rec ] . append ( ( new_name , attr , _to_variable_type ( inp [ "type" ] [ "items" ] ...
def __definitions_descriptor ( self ) : """Describes the definitions section of the OpenAPI spec . Returns : Dictionary describing the definitions of the spec ."""
# Filter out any keys that aren ' t ' properties ' or ' type ' result = { } for def_key , def_value in self . __parser . schemas ( ) . iteritems ( ) : if 'properties' in def_value or 'type' in def_value : key_result = { } required_keys = set ( ) if 'type' in def_value : key_resul...
def create ( self , check , notification_plan , criteria = None , disabled = False , label = None , name = None , metadata = None ) : """Creates an alarm that binds the check on the given entity with a notification plan . Note that the ' criteria ' parameter , if supplied , should be a string representing the...
uri = "/%s" % self . uri_base body = { "check_id" : utils . get_id ( check ) , "notification_plan_id" : utils . get_id ( notification_plan ) , } if criteria : body [ "criteria" ] = criteria if disabled is not None : body [ "disabled" ] = disabled label_name = label or name if label_name : body [ "label" ] =...
def do_WhoHasRequest ( self , apdu ) : """Respond to a Who - Has request ."""
if _debug : WhoHasIHaveServices . _debug ( "do_WhoHasRequest, %r" , apdu ) # ignore this if there ' s no local device if not self . localDevice : if _debug : WhoIsIAmServices . _debug ( " - no local device" ) return # if this has limits , check them like Who - Is if apdu . limits is not None : # ...
def set_promisc ( self , value ) : """Set the interface in promiscuous mode"""
try : fcntl . ioctl ( self . ins , BIOCPROMISC , struct . pack ( 'i' , value ) ) except IOError : raise Scapy_Exception ( "Cannot set promiscuous mode on interface " "(%s)!" % self . iface )
def interp_value ( self , lat , lon , indexed = False ) : """Lookup a pixel value in the raster data , performing linear interpolation if necessary . Indexed = = > nearest neighbor ( * fast * ) ."""
( px , py ) = self . grid_coordinates . projection_to_raster_coords ( lat , lon ) if indexed : return self . raster_data [ round ( py ) , round ( px ) ] else : # from scipy . interpolate import interp2d # f _ interp = interp2d ( self . grid _ coordinates . x _ axis , self . grid _ coordinates . y _ axis , self . ra...
def project_geometry ( geometry , crs = None , to_crs = None , to_latlong = False ) : """Project a shapely Polygon or MultiPolygon from lat - long to UTM , or vice - versa Parameters geometry : shapely Polygon or MultiPolygon the geometry to project crs : dict the starting coordinate reference system of...
if crs is None : crs = settings . default_crs gdf = gpd . GeoDataFrame ( ) gdf . crs = crs gdf . gdf_name = 'geometry to project' gdf [ 'geometry' ] = None gdf . loc [ 0 , 'geometry' ] = geometry gdf_proj = project_gdf ( gdf , to_crs = to_crs , to_latlong = to_latlong ) geometry_proj = gdf_proj [ 'geometry' ] . ilo...
def port_profile_vlan_profile_switchport_access_mac_vlan_classification_access_vlan_access_vlan_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) port_profile = ET . SubElement ( config , "port-profile" , xmlns = "urn:brocade.com:mgmt:brocade-port-profile" ) name_key = ET . SubElement ( port_profile , "name" ) name_key . text = kwargs . pop ( 'name' ) vlan_profile = ET . SubElement ( port_profile , "vlan-profile" ) switchport =...
def _get_region ( self , contig , start , end , fout , min_length = 250 ) : '''Writes reads mapping to given region of contig , trimming part of read not in the region'''
sam_reader = pysam . Samfile ( self . bam , "rb" ) trimming_end = ( start == 0 ) for read in sam_reader . fetch ( contig , start , end ) : read_interval = pyfastaq . intervals . Interval ( read . pos , read . reference_end - 1 ) seq = mapping . aligned_read_to_read ( read , ignore_quality = not self . fastq_out...
def _isin ( expr , values ) : """Return a boolean sequence or scalar showing whether each element is exactly contained in the passed ` values ` . : param expr : sequence or scalar : param values : ` list ` object or sequence : return : boolean sequence or scalar"""
from . merge import _make_different_sources if isinstance ( values , SequenceExpr ) : expr , values = _make_different_sources ( expr , values ) if isinstance ( expr , SequenceExpr ) : return IsIn ( _input = expr , _values = values , _data_type = types . boolean ) elif isinstance ( expr , Scalar ) : return I...
def ValidateEmail ( email , column_name = None , problems = None ) : """checks the basic validity of email : - an empty email is considered valid and no error or warning is issued . - should start with any string not including @ - then should match a single @ - then matches any string not including @ - th...
if IsEmpty ( email ) or re . match ( r'[^@]+@[^@]+\.[^@]+' , email ) : return True else : if problems : problems . InvalidValue ( column_name , email ) return False
def _safe_squeeze ( arr , * args , ** kwargs ) : """numpy . squeeze will reduce a 1 - item array down to a zero - dimensional " array " , which is not necessarily desirable . This function does the squeeze operation , but ensures that there is at least 1 dimension in the output ."""
out = np . squeeze ( arr , * args , ** kwargs ) if np . ndim ( out ) == 0 : out = out . reshape ( ( 1 , ) ) return out
def tag_name ( cls , tag ) : """return the name of the tag , with the namespace removed"""
while isinstance ( tag , etree . _Element ) : tag = tag . tag return tag . split ( '}' ) [ - 1 ]
def parse_codons ( ref , start , end , strand ) : """parse codon nucleotide positions in range start - > end , wrt strand"""
codon = [ ] c = cycle ( [ 1 , 2 , 3 ] ) ref = ref [ start - 1 : end ] if strand == - 1 : ref = rc_stats ( ref ) for pos in ref : n = next ( c ) codon . append ( pos ) if n == 3 : yield codon codon = [ ]
def _neighbour_to_path_call ( neig_type , neighbour , element ) : """Get : class : ` PathCall ` from ` neighbour ` and ` element ` . Args : neigh _ type ( str ) : ` left ` for left neighbour , ` right ` for . . This is used to determine : attr : ` PathCall . call _ type ` of returned object . neighbour ( ...
params = [ None , None , neighbour . getContent ( ) . strip ( ) ] if neighbour . isTag ( ) : params = [ neighbour . getTagName ( ) , _params_or_none ( neighbour . params ) , neighbour . getContent ( ) . strip ( ) ] return PathCall ( neig_type + "_neighbour_tag" , 0 , # TODO : Dynamic lookup NeighCall ( element . ge...
def preston_bin ( data , max_num ) : """Bins data on base 2 using Preston ' s method Parameters data : array - like Data to be binned max _ num : float The maximum upper value of the data Returns tuple ( binned _ data , bin _ edges ) Notes Uses Preston ' s method of binning , which has exclusive...
log_ub = np . ceil ( np . log2 ( max_num ) ) # Make an exclusive lower bound in keeping with Preston if log_ub == 0 : boundaries = np . array ( [ 0 , 1 ] ) elif log_ub == 1 : boundaries = np . arange ( 1 , 4 ) else : boundaries = 2 ** np . arange ( 0 , log_ub + 1 ) boundaries = np . insert ( boundaries ...
def execute ( self , i , o ) : """Executes the command . : type i : cleo . inputs . input . Input : type o : cleo . outputs . output . Output"""
config = self . _get_config ( i ) self . _resolver = DatabaseManager ( config )
def fit_tip_labels ( self ) : """Modifies display range to ensure tip labels fit . This is a bit hackish still . The problem is that the ' extents ' range of the rendered text is totally correct . So we add a little buffer here . Should add for user to be able to modify this if needed . If not using edge leng...
# user entered values # if self . style . axes . x _ domain _ max or self . style . axes . y _ domain _ min : # self . axes . x . domain . max = self . style . axes . x _ domain _ max # self . axes . y . domain . min = self . style . axes . y _ domain _ min # IF USE WANTS TO CHANGE IT THEN DO IT AFTER USING AXES # or a...
def string_sequence ( n : int ) -> str : """Return a string containing space - delimited numbers starting from 0 upto n inclusive . Parameters : n ( int ) : The end of the sequence ( inclusive ) . Returns : str : A string representing the sequence . Examples : > > > string _ sequence ( 0) > > > string...
return ' ' . join ( str ( i ) for i in range ( n + 1 ) )
def load_logos ( filename ) : '''Load logos from a geologos archive from < filename > < filename > can be either a local path or a remote URL .'''
if filename . startswith ( 'http' ) : log . info ( 'Downloading GeoLogos bundle: %s' , filename ) filename , _ = urlretrieve ( filename , tmp . path ( 'geologos.tar.xz' ) ) log . info ( 'Extracting GeoLogos bundle' ) with contextlib . closing ( lzma . LZMAFile ( filename ) ) as xz : with tarfile . open ( fi...
def decline_strong_feminine_noun ( ns : str , gs : str , np : str ) : """Gives the full declension of strong feminine nouns . o macron - stem Most of strong feminine nouns follows the declension of rún and för . > > > decline _ strong _ feminine _ noun ( " rún " , " rúnar " , " rúnar " ) rún rún ...
# nominative singular print ( ns ) # accusative singular if len ( ns ) > 2 and ns [ - 1 ] == "r" and ns [ - 2 ] in CONSONANTS : print ( ns [ : - 1 ] + "i" ) else : print ( ns ) # dative singular if len ( ns ) > 2 and ns [ - 1 ] == "r" and ns [ - 2 ] in CONSONANTS : print ( ns [ : - 1 ] + "i" ) elif ns . end...
async def get_connections ( self , data = True ) : """Return connections for all the agents in the slave environments . This is a managing function for : meth : ` ~ creamas . mp . MultiEnvironment . get _ connections ` ."""
return await self . menv . get_connections ( data = data , as_coro = True )
def batch_face_locations ( images , number_of_times_to_upsample = 1 , batch_size = 128 ) : """Returns an 2d array of bounding boxes of human faces in a image using the cnn face detector If you are using a GPU , this can give you much faster results since the GPU can process batches of images at once . If you ar...
def convert_cnn_detections_to_css ( detections ) : return [ _trim_css_to_bounds ( _rect_to_css ( face . rect ) , images [ 0 ] . shape ) for face in detections ] raw_detections_batched = _raw_face_locations_batched ( images , number_of_times_to_upsample , batch_size ) return list ( map ( convert_cnn_detections_to_cs...
def match ( self , pattern , screen = None , rect = None , offset = None , threshold = None , method = None ) : """Check if image position in screen Args : - pattern : Image file name or opencv image object - screen ( PIL . Image ) : optional , if not None , screenshot method will be called - threshold ( fl...
pattern = self . pattern_open ( pattern ) search_img = pattern . image pattern_scale = self . _cal_scale ( pattern ) if pattern_scale != 1.0 : search_img = cv2 . resize ( search_img , ( 0 , 0 ) , fx = pattern_scale , fy = pattern_scale , interpolation = cv2 . INTER_CUBIC ) screen = screen or self . region_screensho...
def sortJobs ( jobTypes , options ) : """Return a jobTypes all sorted ."""
longforms = { "med" : "median" , "ave" : "average" , "min" : "min" , "total" : "total" , "max" : "max" , } sortField = longforms [ options . sortField ] if ( options . sortCategory == "time" or options . sortCategory == "clock" or options . sortCategory == "wait" or options . sortCategory == "memory" ) : return sor...
def append_underlying_workflow_describe ( globalworkflow_desc ) : """Adds the " workflowDescribe " field to the config for each region of the global workflow . The value is the description of an underlying workflow in that region ."""
if not globalworkflow_desc or globalworkflow_desc [ 'class' ] != 'globalworkflow' or not 'regionalOptions' in globalworkflow_desc : return globalworkflow_desc for region , config in globalworkflow_desc [ 'regionalOptions' ] . items ( ) : workflow_id = config [ 'workflow' ] workflow_desc = dxpy . api . workf...
def compile_regex_from_str ( self , ft_str ) : """Given a string describing features masks for a sequence of segments , return a regex matching the corresponding strings . Args : ft _ str ( str ) : feature masks , each enclosed in square brackets , in which the features are delimited by any standard delimit...
sequence = [ ] for m in re . finditer ( r'\[([^]]+)\]' , ft_str ) : ft_mask = fts ( m . group ( 1 ) ) segs = self . all_segs_matching_fts ( ft_mask ) sub_pat = '({})' . format ( '|' . join ( segs ) ) sequence . append ( sub_pat ) pattern = '' . join ( sequence ) regex = re . compile ( pattern ) return r...
def _get_db ( ) : """Get database from server"""
with cd ( env . remote_path ) : file_path = '/tmp/' + _sql_paths ( 'remote' , str ( base64 . urlsafe_b64encode ( uuid . uuid4 ( ) . bytes ) ) . replace ( '=' , '' ) ) run ( env . python + ' manage.py dump_database | gzip > ' + file_path ) local_file_path = './backups/' + _sql_paths ( 'remote' , datetime . n...
def vcirc ( self , R , phi = None ) : """NAME : vcirc PURPOSE : calculate the circular velocity at R in potential Pot INPUT : Pot - Potential instance or list of such instances R - Galactocentric radius ( can be Quantity ) phi = ( None ) azimuth to use for non - axisymmetric potentials OUTPUT : ci...
return nu . sqrt ( R * - self . Rforce ( R , phi = phi , use_physical = False ) )
def workflow ( ctx , client ) : """List or manage workflows with subcommands ."""
if ctx . invoked_subcommand is None : from renku . models . refs import LinkReference names = defaultdict ( list ) for ref in LinkReference . iter_items ( client , common_path = 'workflows' ) : names [ ref . reference . name ] . append ( ref . name ) for path in client . workflow_path . glob ( '...
def write_cookies_to_cache ( cj , username ) : """Save RequestsCookieJar to disk in Mozilla ' s cookies . txt file format . This prevents us from repeated authentications on the accounts . coursera . org and class . coursera . org / class _ name sites ."""
mkdir_p ( PATH_COOKIES , 0o700 ) path = get_cookies_cache_path ( username ) cached_cj = cookielib . MozillaCookieJar ( ) for cookie in cj : cached_cj . set_cookie ( cookie ) cached_cj . save ( path )
def _init_pval_name ( self , ** kws ) : """Initialize pvalue attribute name ."""
if 'pval_name' in kws : return kws [ 'pval_name' ] # If go2res contains GO Terms if self . is_goterm : return "p_{M}" . format ( M = next ( iter ( self . go2res . values ( ) ) ) . get_method_name ( ) ) # If go2res contains GO namedtuples for fld in next ( iter ( self . go2res . values ( ) ) ) . _fields : if...
def sync_table ( model ) : """Inspects the model and creates / updates the corresponding table and columns . Note that the attributes removed from the model are not deleted on the database . They become effectively ignored by ( will not show up on ) the model ."""
if not issubclass ( model , Model ) : raise CQLEngineException ( "Models must be derived from base Model." ) if model . __abstract__ : raise CQLEngineException ( "cannot create table from abstract model" ) # construct query string cf_name = model . column_family_name ( ) raw_cf_name = model . column_family_name...
def write_virtual_memory ( self , cpu_id , address , size , bytes_p ) : """Writes guest virtual memory , access handles ( MMIO + + ) are ignored . This feature is not implemented in the 4.0.0 release but may show up in a dot release . in cpu _ id of type int The identifier of the Virtual CPU . in address ...
if not isinstance ( cpu_id , baseinteger ) : raise TypeError ( "cpu_id can only be an instance of type baseinteger" ) if not isinstance ( address , baseinteger ) : raise TypeError ( "address can only be an instance of type baseinteger" ) if not isinstance ( size , baseinteger ) : raise TypeError ( "size can...
def ave_laplacian ( self ) : '''Another kind of laplacian normalization , used in the matlab PVF code . Uses the formula : L = I - D ^ { - 1 } * W'''
W = self . matrix ( 'dense' ) # calculate - inv ( D ) Dinv = W . sum ( axis = 0 ) mask = Dinv != 0 Dinv [ mask ] = - 1. / Dinv [ mask ] # calculate - inv ( D ) * W lap = ( Dinv * W . T ) . T # add I lap . flat [ : : W . shape [ 0 ] + 1 ] += 1 # symmetrize return ( lap + lap . T ) / 2.0
def is_mount ( self , name ) : """Test that ` name ` is a mount name"""
if self . mount_prefix . startswith ( self . module_prefix ) : return name . startswith ( self . mount_prefix ) return name . startswith ( self . mount_prefix ) and not name . startswith ( self . module_prefix )
def sorted_names ( names ) : """Sort a list of names but keep the word ' default ' first if it ' s there ."""
names = list ( names ) have_default = False if 'default' in names : names . remove ( 'default' ) have_default = True sorted_names = sorted ( names ) if have_default : sorted_names = [ 'default' ] + sorted_names return sorted_names
def rotate_around ( self , axis , theta ) : """Return the vector rotated around axis through angle theta . Right hand rule applies ."""
# Adapted from equations published by Glenn Murray . # http : / / inside . mines . edu / ~ gmurray / ArbitraryAxisRotation / ArbitraryAxisRotation . html x , y , z = self . x , self . y , self . z u , v , w = axis . x , axis . y , axis . z # Extracted common factors for simplicity and efficiency r2 = u ** 2 + v ** 2 + ...
def begin_x ( self ) : """Return the X - position of the begin point of this connector , in English Metric Units ( as a | Length | object ) ."""
cxnSp = self . _element x , cx , flipH = cxnSp . x , cxnSp . cx , cxnSp . flipH begin_x = x + cx if flipH else x return Emu ( begin_x )
def district_events ( self , district , simple = False , keys = False ) : """Return list of events in a given district . : param district : Key of district whose events you want . : param simple : Get only vital data . : param keys : Return list of event keys only rather than full data on every event . : re...
if keys : return self . _get ( 'district/%s/events/keys' % district ) else : return [ Event ( raw ) for raw in self . _get ( 'district/%s/events%s' % ( district , '/simple' if simple else '' ) ) ]
def get_default_query_from_module ( module ) : """Given a % % sql module return the default ( last ) query for the module . Args : module : the % % sql module . Returns : The default query associated with this module ."""
if isinstance ( module , types . ModuleType ) : return module . __dict__ . get ( _SQL_MODULE_LAST , None ) return None
def upload_hub ( hub , host , remote_dir , user = None , port = 22 , rsync_options = RSYNC_OPTIONS , staging = None ) : """Renders , stages , and uploads a hub ."""
hub . render ( ) if staging is None : staging = tempfile . mkdtemp ( ) staging , linknames = stage_hub ( hub , staging = staging ) local_dir = os . path . join ( staging ) upload ( host , user , local_dir = local_dir , remote_dir = remote_dir , rsync_options = rsync_options ) return linknames
def _graph_successors ( self , graph , node ) : """Return the successors of a node in the graph . This method can be overriden in case there are special requirements with the graph and the successors . For example , when we are dealing with a control flow graph , we may not want to get the FakeRet successors . ...
if self . _graph_successors_func is not None : return self . _graph_successors_func ( graph , node ) return graph . successors ( node )
def contains_container ( self , path ) : """Returns True if a container exists at the specified path , otherwise False . : param path : str or Path instance : return : : rtype : bool : raises ValueError : A component of path is a field name ."""
path = make_path ( path ) try : self . get_container ( path ) return True except KeyError : return False
def apply_u_umlaut ( stem : str ) : """Changes the vowel of the last syllable of the given stem if the vowel is affected by an u - umlaut . > > > apply _ u _ umlaut ( " far " ) ' för ' > > > apply _ u _ umlaut ( " ör " ) ' ör ' > > > apply _ u _ umlaut ( " axl " ) ' öxl ' > > > apply _ u _ umlaut ...
assert len ( stem ) > 0 s_stem = s . syllabify_ssp ( stem . lower ( ) ) if len ( s_stem ) == 1 : last_syllable = OldNorseSyllable ( s_stem [ - 1 ] , VOWELS , CONSONANTS ) last_syllable . apply_u_umlaut ( ) return "" . join ( s_stem [ : - 1 ] ) + str ( last_syllable ) else : penultimate_syllable = OldNor...
def console_size ( fd = 1 ) : """Return console size as a ( LINES , COLUMNS ) tuple"""
try : import fcntl import termios import struct except ImportError : size = os . getenv ( 'LINES' , 25 ) , os . getenv ( 'COLUMNS' , 80 ) else : size = struct . unpack ( 'hh' , fcntl . ioctl ( fd , termios . TIOCGWINSZ , b'1234' ) ) return size
def _conv_name ( x ) : '''If this XML tree has an xmlns attribute , then etree will add it to the beginning of the tag , like : " { http : / / path } tag " .'''
if '}' in x : comps = x . split ( '}' ) name = comps [ 1 ] return name return x
def read ( cls , filename , offset = 0 ) : """Read an ID3v2 tag from a file ."""
i = 0 with fileutil . opened ( filename , "rb" ) as file : file . seek ( offset ) tag = cls ( ) tag . _read_header ( file ) for ( frameid , bflags , data ) in tag . _read_frames ( file ) : if len ( data ) == 0 : warn ( "{0}: Ignoring empty frame" . format ( frameid ) , EmptyFrameWarn...
def _minute_exclusion_tree ( self ) : """Build an interval tree keyed by the start and end of each range of positions should be dropped from windows . ( These are the minutes between an early close and the minute which would be the close based on the regular period if there were no early close . ) The value...
itree = IntervalTree ( ) for market_open , early_close in self . _minutes_to_exclude ( ) : start_pos = self . _find_position_of_minute ( early_close ) + 1 end_pos = ( self . _find_position_of_minute ( market_open ) + self . _minutes_per_day - 1 ) data = ( start_pos , end_pos ) itree [ start_pos : end_po...
def value_to_db ( self , value ) : """Returns field ' s single value prepared for saving into a database ."""
assert isinstance ( value , six . integer_types ) return str ( value ) . encode ( "utf_8" )
def use_isolated_book_view ( self ) : """Pass through to provider CommentLookupSession . use _ isolated _ book _ view"""
self . _book_view = ISOLATED # self . _ get _ provider _ session ( ' comment _ lookup _ session ' ) # To make sure the session is tracked for session in self . _get_provider_sessions ( ) : try : session . use_isolated_book_view ( ) except AttributeError : pass
def _simple_lock ( f ) : """Simple file lock , times out after 20 second assuming lock is stale"""
lock_file = f + ".lock" timeout = 20 curtime = 0 interval = 2 while os . path . exists ( lock_file ) : time . sleep ( interval ) curtime += interval if curtime > timeout : os . remove ( lock_file ) with open ( lock_file , "w" ) as out_handle : out_handle . write ( "locked" ) yield if os . path ....
def save_workflow_graph_for ( self , spec_name , fname , full = False , style = 'flat' , ** kwargs ) : """Saves a graph of the workflow to generate the requested spec _ name Parameters spec _ name : str Name of the spec to generate the graph for fname : str The filename for the saved graph style : str ...
pipeline = self . spec ( spec_name ) . pipeline if full : workflow = pe . Workflow ( name = '{}_gen' . format ( spec_name ) , base_dir = self . processor . work_dir ) self . processor . _connect_pipeline ( pipeline , workflow , ** kwargs ) else : workflow = pipeline . _workflow fname = op . expanduser ( fna...
def register_event ( self , name , callback , validator ) : """Register a callback to receive events . Every event with the matching name will have its payload validated using validator and then will be passed to callback if validation succeeds . Callback must be a normal callback function , coroutines are ...
async def _validate_and_call ( message ) : payload = message . get ( 'payload' ) try : payload = validator . verify ( payload ) except ValidationError : self . _logger . warning ( "Dropping invalid payload for event %s, payload=%s" , name , payload ) return try : result =...
def _get_authz_session ( self ) : """Gets the AuthorizationSession for the default ( bootstrap ) typed Vault Assumes only one vault of this Type , but it can have children depending on underlying impl ."""
from . . utilities import BOOTSTRAP_VAULT_TYPE try : vaults = self . _get_vault_lookup_session ( ) . get_vaults_by_genus_type ( BOOTSTRAP_VAULT_TYPE ) except Unimplemented : return self . _get_authz_manager ( ) . get_authorization_session ( ) if vaults . available ( ) : vault = vaults . next ( ) return ...
def dispose ( self ) : """Disposes of this events writer manager , making it no longer usable . Call this method when this object is done being used in order to clean up resources and handlers . This method should ever only be called once ."""
self . _lock . acquire ( ) self . _events_writer . Close ( ) self . _events_writer = None self . _lock . release ( )
def import_path ( path ) : """Imports any valid python module or attribute path as though it were a module : Example : > > > from yamlconf import import _ path > > > from my _ package . my _ module . my _ submodule import attribute > > > attribute . sub _ attribute = = . . . import _ path ( " y _ package ...
# noqa sys . path . insert ( 0 , "." ) parts = path . split ( "." ) module = None # Import the module as deeply as possible . Prioritize an attribute chain # over a module chain for i in range ( 1 , len ( parts ) + 1 ) : if module is not None and hasattr ( module , parts [ i - 1 ] ) : try : retu...
def _write_session ( self ) : """Write SDK session file Args : version ( str ) : the version of the server"""
base_name = "%ssession" % self . _product_accronym . lower ( ) filename = "%s%s.py" % ( self . _class_prefix . lower ( ) , base_name ) override_content = self . _extract_override_content ( base_name ) self . write ( destination = self . output_directory , filename = filename , template_name = "session.py.tpl" , version...
def read ( self , count = None , block = None , last_id = None ) : """Monitor stream for new data . : param int count : limit number of messages returned : param int block : milliseconds to block , 0 for indefinitely : param last _ id : Last id read ( an exclusive lower - bound ) . If the ' $ ' value is giv...
if last_id is None : last_id = '0-0' resp = self . database . xread ( { self . key : _decode ( last_id ) } , count , block ) # resp is a 2 - tuple of stream name - > message list . return resp [ 0 ] [ 1 ] if resp else [ ]
def set_col_first ( df , col_names ) : """set selected columns first in a pandas . DataFrame . This function sets cols with names given in col _ names ( a list ) first in the DataFrame . The last col in col _ name will come first ( processed last )"""
column_headings = df . columns column_headings = column_headings . tolist ( ) try : for col_name in col_names : i = column_headings . index ( col_name ) column_headings . pop ( column_headings . index ( col_name ) ) column_headings . insert ( 0 , col_name ) finally : df = df . reindex ( ...