signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get ( self , key , value ) : """Retrieve single group record by id or name Supports resource cache Keyword Args : id ( str ) : Full Group ID name ( str ) : Group name Raises : TypeError : Unexpected or more than one keyword argument provided ValueError : No matching group found based on provided i...
if key == 'id' : response = self . _swimlane . request ( 'get' , 'groups/{}' . format ( value ) ) return Group ( self . _swimlane , response . json ( ) ) else : response = self . _swimlane . request ( 'get' , 'groups/lookup?name={}' . format ( value ) ) matched_groups = response . json ( ) for group...
def submit ( args = None ) : """Performs the submit according to arguments and returns an object describing the result ."""
streamsx . _streams . _version . _mismatch_check ( 'streamsx.topology.context' ) cmd_args = _parse_args ( args ) if cmd_args . topology is not None : app = _get_topology_app ( cmd_args ) elif cmd_args . main_composite is not None : app = _get_spl_app ( cmd_args ) elif cmd_args . bundle is not None : app = _...
def generate_intersect_subparser ( subparsers ) : """Adds a sub - command parser to ` subparsers ` to make an intersection query ."""
parser = subparsers . add_parser ( 'intersect' , description = constants . INTERSECT_DESCRIPTION , epilog = constants . INTERSECT_EPILOG , formatter_class = ParagraphFormatter , help = constants . INTERSECT_HELP ) parser . set_defaults ( func = ngram_intersection ) utils . add_common_arguments ( parser ) utils . add_db...
def poll_parser ( poll ) : """Parses a poll object"""
if __is_deleted ( poll ) : return deleted_parser ( poll ) if poll [ 'type' ] not in poll_types : raise Exception ( 'Not a poll type' ) return Poll ( poll [ 'id' ] , poll [ 'by' ] , __check_key ( 'kids' , poll ) , # poll and pollopt differ this property __check_key ( 'parts' , poll ) , # poll and pollopt differ ...
def get_biome_color_based_on_elevation ( world , elev , x , y , rng ) : '''This is the " business logic " for determining the base biome color in satellite view . This includes generating some " noise " at each spot in a pixel ' s rgb value , potentially modifying the noise based on elevation , and finally inco...
v = world . biome_at ( ( x , y ) ) . name ( ) biome_color = _biome_satellite_colors [ v ] # Default is no noise - will be overwritten if this tile is land noise = ( 0 , 0 , 0 ) if world . is_land ( ( x , y ) ) : # # Generate some random noise to apply to this pixel # There is noise for each element of the rgb value # T...
def load_builtin_plugins ( ) -> int : """Load built - in plugins distributed along with " nonebot " package ."""
plugin_dir = os . path . join ( os . path . dirname ( __file__ ) , 'plugins' ) return load_plugins ( plugin_dir , 'nonebot.plugins' )
def settings ( ** kwargs ) : """apply given PyEMMA config values temporarily within the given context ."""
from pyemma import config old_settings = { } try : # remember old setting , set new one . May raise ValueError , if invalid setting is given . for k , v in kwargs . items ( ) : old_settings [ k ] = getattr ( config , k ) setattr ( config , k , v ) yield finally : # restore old settings for k...
def update ( self , id , name = None , parent_id = None , order = None ) : """更新部门 https : / / work . weixin . qq . com / api / doc # 90000/90135/90206 : param id : 部门 id : param name : 部门名称 。 长度限制为1 ~ 32个字符 , 字符不能包括 \\ : ? ” < > | : param parent _ id : 父亲部门id : param order : 在父部门中的次序值 。 order值大的排序靠前 。 有效...
data = optionaldict ( id = id , name = name , parentid = parent_id , order = order ) return self . _post ( 'department/update' , data = data )
def _merge_wf_inputs ( new , out , wf_outputs , to_ignore , parallel , nested_inputs ) : """Merge inputs for a sub - workflow , adding any not present inputs in out . Skips inputs that are internally generated or generated and ignored , keeping only as inputs those that we do not generate internally ."""
internal_generated_ids = [ ] for vignore in to_ignore : vignore_id = _get_string_vid ( vignore ) # ignore anything we generate internally , but not those we need to pull in # from the external process if vignore_id not in [ v [ "id" ] for v in wf_outputs ] : internal_generated_ids . append ( vig...
def dfs_grid ( grid , i , j , mark = 'X' , free = '.' ) : """DFS on a grid , mark connected component , iterative version : param grid : matrix , 4 - neighborhood : param i , j : cell in this matrix , start of DFS exploration : param free : symbol for walkable cells : param mark : symbol to overwrite visite...
height = len ( grid ) width = len ( grid [ 0 ] ) to_visit = [ ( i , j ) ] grid [ i ] [ j ] = mark while to_visit : i1 , j1 = to_visit . pop ( ) for i2 , j2 in [ ( i1 + 1 , j1 ) , ( i1 , j1 + 1 ) , ( i1 - 1 , j1 ) , ( i1 , j1 - 1 ) ] : if ( 0 <= i2 < height and 0 <= j2 < width and grid [ i2 ] [ j2 ] == f...
def _local_browser_class ( browser_name ) : """Returns class , kwargs , and args needed to instantiate the local browser ."""
# Log name of local browser LOGGER . info ( u"Using local browser: %s [Default is firefox]" , browser_name ) # Get class of local browser based on name browser_class = BROWSERS . get ( browser_name ) headless = os . environ . get ( 'BOKCHOY_HEADLESS' , 'false' ) . lower ( ) == 'true' if browser_class is None : rais...
def bss_eval_sources ( reference_sources , estimated_sources , compute_permutation = True ) : """Ordering and measurement of the separation quality for estimated source signals in terms of filtered true source , interference and artifacts . The decomposition allows a time - invariant filter distortion of length...
# make sure the input is of shape ( nsrc , nsampl ) if estimated_sources . ndim == 1 : estimated_sources = estimated_sources [ np . newaxis , : ] if reference_sources . ndim == 1 : reference_sources = reference_sources [ np . newaxis , : ] validate ( reference_sources , estimated_sources ) # If empty matrices w...
def get_ZXY_data_IFFT ( Data , zf , xf , yf , zwidth = 10000 , xwidth = 5000 , ywidth = 5000 , timeStart = None , timeEnd = None , show_fig = True ) : """Given a Data object and the frequencies of the z , x and y peaks ( and some optional parameters for the created filters ) this function extracts the individua...
if timeStart == None : timeStart = Data . timeStart if timeEnd == None : timeEnd = Data . timeEnd time = Data . time . get_array ( ) StartIndex = _np . where ( time == take_closest ( time , timeStart ) ) [ 0 ] [ 0 ] EndIndex = _np . where ( time == take_closest ( time , timeEnd ) ) [ 0 ] [ 0 ] SAMPLEFREQ = Data...
def sync ( self , api_token , sync_token , resource_types = '["all"]' , ** kwargs ) : """Update and retrieve Todoist data . : param api _ token : The user ' s login api _ token . : type api _ token : str : param seq _ no : The request sequence number . On initial request pass ` ` 0 ` ` . On all others pass ...
params = { 'token' : api_token , 'sync_token' : sync_token , } req_func = self . _post if 'commands' not in kwargs : # GET if we ' re not changing data . req_func = self . _get params [ 'resource_types' ] = resource_types return req_func ( 'sync' , params , ** kwargs )
def create_directory ( directory ) : """Create directory but first delete it if it exists"""
if os . path . exists ( directory ) : rmtree ( directory ) os . makedirs ( directory ) return directory
def get_user_client ( self , user , password , populate = True ) : """Returns a new client for the given user . This is a lightweight client that only uses different credentials and shares the transport with the underlying client"""
return XCLIClientForUser ( weakproxy ( self ) , user , password , populate = populate )
def default_inasafe_html_resources ( feature , parent ) : """Retrieve default InaSAFE HTML resources ( style and script ) ."""
_ = feature , parent # NOQA project_context_scope = QgsExpressionContextUtils . projectScope ( ) key = provenance_layer_analysis_impacted [ 'provenance_key' ] if not project_context_scope . hasVariable ( key ) : return None analysis_dir = dirname ( project_context_scope . variable ( key ) ) complete_html_report = g...
def inc ( self , exception = None ) : # type : ( Optional [ ParseError . _ _ class _ _ ] ) - > bool """Increments the parser if the end of the input has not been reached . Returns whether or not it was able to advance ."""
try : self . _idx , self . _current = next ( self . _chars ) return True except StopIteration : self . _idx = len ( self ) self . _current = self . EOF if exception : raise self . parse_error ( exception ) return False
def getClassAllSubs ( self , aURI ) : """note : requires SPARQL 1.1 2015-06-04 : currenlty not used , inferred from above"""
aURI = aURI try : qres = self . rdfgraph . query ( """SELECT DISTINCT ?x WHERE { { ?x rdfs:subClassOf+ <%s> } FILTER (!isBlank(?x)) } """ % ( aURI ) ) except : printDebug ( "... warning: the 'getClas...
def _load_instance ( self , instance_id ) : """Return instance with the given id . For performance reasons , the instance ID is first searched for in the collection of VM instances started by ElastiCluster ( ` self . _ instances ` ) , then in the list of all instances known to the cloud provider at the time...
# if instance is known , return it if instance_id in self . _instances : return self . _instances [ instance_id ] # else , check ( cached ) list from provider if instance_id not in self . _cached_instances : self . _cached_instances = self . _build_cached_instances ( ) if instance_id in self . _cached_instances...
def VerifyStructure ( self , parser_mediator , line ) : """Verify that this file is a Mac Wifi log file . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . line ( str ) : line from a text file . Returns : bool : True if...
self . _last_month = 0 self . _year_use = parser_mediator . GetEstimatedYear ( ) key = 'header' try : structure = self . _MAC_WIFI_HEADER . parseString ( line ) except pyparsing . ParseException : structure = None if not structure : key = 'turned_over_header' try : structure = self . _MAC_WIFI_T...
def from_jd ( jd ) : '''Calculate Indian Civil date from Julian day Offset in years from Saka era to Gregorian epoch'''
start = 80 # Day offset between Saka and Gregorian jd = trunc ( jd ) + 0.5 greg = gregorian . from_jd ( jd ) # Gregorian date for Julian day leap = isleap ( greg [ 0 ] ) # Is this a leap year ? # Tentative year in Saka era year = greg [ 0 ] - SAKA_EPOCH # JD at start of Gregorian year greg0 = gregorian . to_jd ( greg [...
def cmp_pkgrevno ( package , revno , pkgcache = None ) : """Compare supplied revno with the revno of the installed package . * 1 = > Installed revno is greater than supplied arg * 0 = > Installed revno is the same as supplied arg * - 1 = > Installed revno is less than supplied arg This function imports YumB...
if not pkgcache : y = yum . YumBase ( ) packages = y . doPackageLists ( ) pkgcache = { i . Name : i . version for i in packages [ 'installed' ] } pkg = pkgcache [ package ] if pkg > revno : return 1 if pkg < revno : return - 1 return 0
def checked ( response ) : """Check a response status before returning it . : param response : a response from a XMLRPC call to OpenSubtitles . : return : the response . : raise : : class : ` OpenSubtitlesError `"""
status_code = int ( response [ 'status' ] [ : 3 ] ) if status_code == 401 : raise Unauthorized if status_code == 406 : raise NoSession if status_code == 407 : raise DownloadLimitReached if status_code == 413 : raise InvalidImdbid if status_code == 414 : raise UnknownUserAgent if status_code == 415 :...
def _strip_comments ( line ) : """Processes line stripping any comments from it : param line : line to be processed : type line : str : return : line with removed comments : rtype : str"""
if line == '' : return line r = re . search ( '(?P<line>[^#]*)(#(?P<comment>.*))?' , line ) if r : line = r . group ( 'line' ) if not line . endswith ( '\n' ) : line += '\n' return line return '\n'
def metta_config ( quarter , num_dimensions ) : """Returns metta metadata for a quarter ' s SOC code classifier matrix Args : quarter ( str ) quarter , in format ' 2015Q1' num _ dimensions ( int ) Number of features in matrix Returns : ( dict ) metadata suitable for metta . archive _ train _ test"""
first_day , last_day = quarter_boundaries ( quarter ) return { 'start_time' : first_day , 'end_time' : last_day , 'prediction_window' : 3 , 'label_name' : 'onet_soc_code' , 'label_type' : 'categorical' , 'matrix_id' : 'job_postings_{}' . format ( quarter ) , 'feature_names' : [ 'doc2vec_{}' . format ( i ) for i in rang...
def doCommit ( self , p : Prepare ) : """Create a commit message from the given Prepare message and trigger the commit phase : param p : the prepare message"""
key_3pc = ( p . viewNo , p . ppSeqNo ) self . logger . debug ( "{} Sending COMMIT{} at {}" . format ( self , key_3pc , self . get_current_time ( ) ) ) params = [ self . instId , p . viewNo , p . ppSeqNo ] pre_prepare = self . getPrePrepare ( * key_3pc ) # BLS multi - sig : if p . stateRootHash is not None : pre_pre...
def reset_password ( app , appbuilder , username , password ) : """Resets a user ' s password"""
_appbuilder = import_application ( app , appbuilder ) user = _appbuilder . sm . find_user ( username = username ) if not user : click . echo ( "User {0} not found." . format ( username ) ) else : _appbuilder . sm . reset_password ( user . id , password ) click . echo ( click . style ( "User {0} reseted." . ...
def name ( self ) : """Get the module name : return : Module name : rtype : str | unicode"""
res = type ( self ) . __name__ if self . _id : res += ".{}" . format ( self . _id ) return res
def build_ap_info_pkt ( self , layer_cls , dest ) : """Build a packet with info describing the current AP For beacon / proberesp use"""
return RadioTap ( ) / Dot11 ( addr1 = dest , addr2 = self . mac , addr3 = self . mac ) / layer_cls ( timestamp = 0 , beacon_interval = 100 , cap = 'ESS+privacy' ) / Dot11Elt ( ID = "SSID" , info = self . ssid ) / Dot11EltRates ( rates = [ 130 , 132 , 139 , 150 , 12 , 18 , 24 , 36 ] ) / Dot11Elt ( ID = "DSset" , info = ...
def add_row ( self , label , row_data , columns = "" ) : """Add a row with data . If any new keys are present in row _ data dictionary , that column will be added to the dataframe . This is done inplace"""
# use provided column order , making sure you don ' t lose any values # from self . df . columns if len ( columns ) : if sorted ( self . df . columns ) == sorted ( columns ) : self . df . columns = columns else : new_columns = [ ] new_columns . extend ( columns ) for col in self ...
def call_and_catch_errors ( self , f , * args , ** kwargs ) : """Call the given function with the given arguments . If it succeeds , return its return value . If it raises a : class : ` scss . errors . SassError ` and ` live _ errors ` is turned on , return CSS containing a traceback and error message ."""
try : return f ( * args , ** kwargs ) except SassError as e : if self . live_errors : # TODO should this setting also capture and display warnings ? return e . to_css ( ) else : raise
def batch_norm_relu ( inputs , is_training , relu = True ) : """Block of batch norm and relu ."""
inputs = mtf . layers . batch_norm ( inputs , is_training , BATCH_NORM_DECAY , epsilon = BATCH_NORM_EPSILON , init_zero = ( not relu ) ) if relu : inputs = mtf . relu ( inputs ) return inputs
def open_gif ( self , filename ) : """Open a gif file . Parameters filename : str Filename of the gif to open . Filename must end in gif ."""
if filename [ - 3 : ] != 'gif' : raise Exception ( 'Unsupported filetype. Must end in .gif' ) if isinstance ( vtki . FIGURE_PATH , str ) and not os . path . isabs ( filename ) : filename = os . path . join ( vtki . FIGURE_PATH , filename ) self . _gif_filename = os . path . abspath ( filename ) self . mwriter ...
def find_tags ( self ) : """Find information about the tags in the repository . . . note : : The ` ` bzr tags ` ` command reports tags pointing to non - existing revisions as ` ` ? ` ` but doesn ' t provide revision ids . We can get the revision ids using the ` ` bzr tags - - show - ids ` ` command but this...
valid_tags = [ ] listing = self . context . capture ( 'bzr' , 'tags' ) for line in listing . splitlines ( ) : tokens = line . split ( ) if len ( tokens ) == 2 and tokens [ 1 ] != '?' : valid_tags . append ( tokens [ 0 ] ) listing = self . context . capture ( 'bzr' , 'tags' , '--show-ids' ) for line in l...
def experiments_fmri_create ( self , experiment_id , filename ) : """Create functional data object from given file and associate the object with the specified experiment . Parameters experiment _ id : string Unique experiment identifier filename : File - type object Functional data file Returns FMRI...
# Get the experiment to ensure that it exist before we even create the # functional data object experiment = self . experiments_get ( experiment_id ) if experiment is None : return None # Create functional data object from given file fmri = self . funcdata . create_object ( filename ) # Update experiment to associa...
def import_keybase ( useropt ) : """Imports a public GPG key from Keybase"""
public_key = None u_bits = useropt . split ( ':' ) username = u_bits [ 0 ] if len ( u_bits ) == 1 : public_key = cryptorito . key_from_keybase ( username ) else : fingerprint = u_bits [ 1 ] public_key = cryptorito . key_from_keybase ( username , fingerprint ) if cryptorito . has_gpg_key ( public_key [ 'fing...
def flipVertical ( self ) : """flips an image object vertically"""
self . flipV = not self . flipV self . _transmogrophy ( self . angle , self . percent , self . scaleFromCenter , self . flipH , self . flipV )
def pressure_integral ( T1 , P1 , dH ) : r'''Method to compute an integral of the pressure differential of an elevation difference with a base elevation defined by temperature ` T1 ` and pressure ` P1 ` . This is similar to subtracting the pressures at two different elevations , except it allows for local c...
# Compute the elevation to obtain the pressure specified def to_solve ( H ) : return ATMOSPHERE_1976 ( H ) . P - P1 H_ref = brenth ( to_solve , - 610.0 , 86000 ) # Compute the temperature delta dT = T1 - ATMOSPHERE_1976 ( H_ref ) . T def to_int ( Z ) : atm = ATMOSPHERE_1976 ( Z , dT = dT ) return atm . g * ...
def histogram_bin_edges_mincount ( data , min_count , bins ) : r'''Merge bins with right - neighbour until each bin has a minimum number of data - points . : arguments : * * data * * ( ` ` < array _ like > ` ` ) Input data . The histogram is computed over the flattened array . * * bins * * ( ` ` < array _ l...
# escape if min_count is None : return bins if min_count is False : return bins # check if type ( min_count ) != int : raise IOError ( '"min_count" must be an integer number' ) # keep removing where needed while True : P , _ = np . histogram ( data , bins = bins , density = False ) idx = np . where ...
def add_location_timezone_to_device ( self , device_obj , location , timezone ) : """Returns ' device object ' with updated location http : / / docs . exosite . com / portals / # update - device http : / / docs . exosite . com / portals / # device - object"""
dictify_device_meta ( device_obj ) device_obj [ 'info' ] [ 'description' ] [ 'meta' ] [ 'location' ] = location device_obj [ 'info' ] [ 'description' ] [ 'meta' ] [ 'Location' ] = location device_obj [ 'info' ] [ 'description' ] [ 'meta' ] [ 'timezone' ] = timezone device_obj [ 'info' ] [ 'description' ] [ 'meta' ] [ '...
def Pop ( self ) : """Remove the tag from the front of the list and return it ."""
if self . tagList : tag = self . tagList [ 0 ] del self . tagList [ 0 ] else : tag = None return tag
def _authenticate_client ( self , client , secret ) : """Returns response of authenticating with the given client and secret ."""
client_s = str . join ( ':' , [ client , secret ] ) credentials = base64 . b64encode ( client_s . encode ( 'utf-8' ) ) . decode ( 'utf-8' ) headers = { 'Content-Type' : 'application/x-www-form-urlencoded' , 'Cache-Control' : 'no-cache' , 'Authorization' : 'Basic ' + credentials } params = { 'client_id' : client , 'gran...
def vrrp_priority ( self , ** kwargs ) : """Set VRRP priority . Args : int _ type ( str ) : Type of interface . ( gigabitethernet , tengigabitethernet , etc ) . name ( str ) : Name of interface . ( 1/0/5 , 1/0/10 , etc ) . vrid ( str ) : VRRPv3 ID . priority ( str ) : VRRP Priority . ip _ version ( st...
int_type = kwargs . pop ( 'int_type' ) . lower ( ) name = kwargs . pop ( 'name' ) vrid = kwargs . pop ( 'vrid' ) priority = kwargs . pop ( 'priority' ) ip_version = int ( kwargs . pop ( 'ip_version' ) ) rbridge_id = kwargs . pop ( 'rbridge_id' , '1' ) callback = kwargs . pop ( 'callback' , self . _callback ) valid_int_...
def cast_scalar ( method ) : """Cast scalars to constant interpolating objects"""
@ wraps ( method ) def new_method ( self , other ) : if np . isscalar ( other ) : other = type ( self ) ( [ other ] , self . domain ( ) ) return method ( self , other ) return new_method
def single_run_max_confidence_recipe ( sess , model , x , y , nb_classes , eps , clip_min , clip_max , eps_iter , nb_iter , report_path , batch_size = BATCH_SIZE , eps_iter_small = None ) : """A reasonable attack bundling recipe for a max norm threat model and a defender that uses confidence thresholding . This r...
noise_attack = Noise ( model , sess ) pgd_attack = ProjectedGradientDescent ( model , sess ) threat_params = { "eps" : eps , "clip_min" : clip_min , "clip_max" : clip_max } noise_attack_config = AttackConfig ( noise_attack , threat_params , "noise" ) attack_configs = [ noise_attack_config ] pgd_attack_configs = [ ] pgd...
def onChangeSelectedBlocksIndent ( self , increase , withSpace = False ) : """Tab or Space pressed and few blocks are selected , or Shift + Tab pressed Insert or remove text from the beginning of blocks"""
def blockIndentation ( block ) : text = block . text ( ) return text [ : len ( text ) - len ( text . lstrip ( ) ) ] def cursorAtSpaceEnd ( block ) : cursor = QTextCursor ( block ) cursor . setPosition ( block . position ( ) + len ( blockIndentation ( block ) ) ) return cursor def indentBlock ( block...
def fix ( self , * args , ** kwargs ) : """Turns parameters to constants . As arguments , parameters must be strings . As keyword arguments , they can be set at the same time . Note this will NOT work when specifying a non - string fit function , because there is no flexibility in the number of arguments . To...
# first set all the keyword argument values self . set ( ** kwargs ) # get everything into one big list pnames = list ( args ) + list ( kwargs . keys ( ) ) # move each pname to the constants for pname in pnames : if not pname in self . _pnames : self . _error ( "Naughty. '" + pname + "' is not a valid fit p...
def is_mod_function ( mod , fun ) : """Checks if a function in a module was declared in that module . http : / / stackoverflow . com / a / 1107150/3004221 Args : mod : the module fun : the function"""
return inspect . isfunction ( fun ) and inspect . getmodule ( fun ) == mod
def get ( self , thread_uuid , uuid ) : """Get one thread member ."""
members = ( v for v in self . list ( thread_uuid ) if v . get ( 'userUuid' ) == uuid ) for i in members : self . log . debug ( i ) return i return None
def ziptake ( items_list , indexes_list ) : """SeeAlso : vt . ziptake"""
return [ take ( list_ , index_list ) for list_ , index_list in zip ( items_list , indexes_list ) ]
def create_resource ( self , resource_form ) : """Creates a new ` ` Resource ` ` . arg : resource _ form ( osid . resource . ResourceForm ) : the form for this ` ` Resource ` ` return : ( osid . resource . Resource ) - the new ` ` Resource ` ` raise : IllegalState - ` ` resource _ form ` ` already used in a...
# Implemented from template for # osid . resource . ResourceAdminSession . create _ resource _ template collection = JSONClientValidated ( 'resource' , collection = 'Resource' , runtime = self . _runtime ) if not isinstance ( resource_form , ABCResourceForm ) : raise errors . InvalidArgument ( 'argument type is not...
def _inner_convert_old_schema ( self , node , depth ) : """Internal recursion helper for L { _ convert _ old _ schema } . @ param node : A node in the associative list tree as described in _ convert _ old _ schema . A two tuple of ( name , parameter ) . @ param depth : The depth that the node is at . This is ...
name , parameter_description = node if not isinstance ( parameter_description , list ) : # This is a leaf , i . e . , an actual L { Parameter } instance . return parameter_description if depth % 2 == 0 : # we ' re processing a structure . fields = { } for node in parameter_description : fields [ nod...
def apply_operator_overloading ( ) : """Function to apply operator overloading to Publisher class"""
# operator overloading is ( unfortunately ) not working for the following # cases : # int , float , str - should return appropriate type instead of a Publisher # len - should return an integer # " x in y " - is using _ _ bool _ _ which is not working with Publisher for method in ( '__lt__' , '__le__' , '__eq__' , '__ne...
def _rmsprop ( self , grads , cache = None , decay_rate = 0.95 ) : """Uses RMSProp to compute step from gradients . Args : grads : numpy array of gradients . cache : numpy array of same shape as ` grads ` as RMSProp cache decay _ rate : How fast to decay cache Returns : A tuple of step : numpy array o...
if cache is None : cache = np . zeros_like ( grads ) cache = decay_rate * cache + ( 1 - decay_rate ) * grads ** 2 step = - grads / np . sqrt ( cache + K . epsilon ( ) ) return step , cache
def lookup ( self , nick ) : """Looks for the most recent paste by a given nick . Returns the uid or None"""
query = dict ( nick = nick ) order = [ ( 'time' , pymongo . DESCENDING ) ] recs = self . db . pastes . find ( query ) . sort ( order ) . limit ( 1 ) try : return next ( recs ) [ 'uid' ] except StopIteration : pass
def require_sequence ( self ) -> None : """Require the node to be a sequence ."""
if not isinstance ( self . yaml_node , yaml . SequenceNode ) : raise RecognitionError ( ( '{}{}A sequence is required here' ) . format ( self . yaml_node . start_mark , os . linesep ) )
def _add_modifiers ( self , sql , blueprint , column ) : """Add the column modifiers to the deifinition"""
for modifier in self . _modifiers : method = '_modify_%s' % modifier if hasattr ( self , method ) : sql += getattr ( self , method ) ( blueprint , column ) return sql
def Tethering_bind ( self , port ) : """Function path : Tethering . bind Domain : Tethering Method name : bind Parameters : Required arguments : ' port ' ( type : integer ) - > Port number to bind . No return value . Description : Request browser port binding ."""
assert isinstance ( port , ( int , ) ) , "Argument 'port' must be of type '['int']'. Received type: '%s'" % type ( port ) subdom_funcs = self . synchronous_command ( 'Tethering.bind' , port = port ) return subdom_funcs
def make_token_post ( server , data ) : """Try getting an access token from the server . If successful , returns the JSON response . If unsuccessful , raises an OAuthException ."""
try : response = requests . post ( server + TOKEN_ENDPOINT , data = data , timeout = TIMEOUT ) body = response . json ( ) except Exception as e : log . warning ( 'Other error when exchanging code' , exc_info = True ) raise OAuthException ( error = 'Authentication Failed' , error_description = str ( e ) ...
def describe_stream ( self , stream_arn , first_shard = None ) : """Wraps : func : ` boto3 . DynamoDBStreams . Client . describe _ stream ` , handling continuation tokens . : param str stream _ arn : Stream arn , usually from the model ' s ` ` Meta . stream [ " arn " ] ` ` . : param str first _ shard : * ( Opti...
description = { "Shards" : [ ] } request = { "StreamArn" : stream_arn , "ExclusiveStartShardId" : first_shard } # boto3 isn ' t down with literal Nones . if first_shard is None : request . pop ( "ExclusiveStartShardId" ) while request . get ( "ExclusiveStartShardId" ) is not missing : try : response = s...
def read_objfile ( fname ) : """Takes . obj filename and returns dict of object properties for each object in file ."""
verts = defaultdict ( list ) obj_props = [ ] with open ( fname ) as f : lines = f . read ( ) . splitlines ( ) for line in lines : if line : split_line = line . strip ( ) . split ( ' ' , 1 ) if len ( split_line ) < 2 : continue prefix , value = split_line [ 0 ] , split_line [ ...
def _get_bcpIn ( self ) : """Subclasses may override this method ."""
segment = self . _segment offCurves = segment . offCurve if offCurves : bcp = offCurves [ - 1 ] x , y = relativeBCPIn ( self . anchor , ( bcp . x , bcp . y ) ) else : x = y = 0 return ( x , y )
def sinatra_path_to_regex ( cls , path ) : """Converts a sinatra - style path to a regex with named parameters ."""
# Return the path if already a ( compiled ) regex if type ( path ) is cls . regex_type : return path # Build a regular expression string which is split on the ' / ' character regex = [ "(?P<{}>\w+)" . format ( segment [ 1 : ] ) if cls . sinatra_param_regex . match ( segment ) else segment for segment in path . spli...
def save_snapshot ( self , context , snapshot_name , save_memory = 'No' ) : """Saves virtual machine to a snapshot : param context : resource context of the vCenterShell : type context : models . QualiDriverModels . ResourceCommandContext : param snapshot _ name : snapshot name to save to : type snapshot _ ...
resource_details = self . _parse_remote_model ( context ) created_snapshot_path = self . command_wrapper . execute_command_with_connection ( context , self . snapshot_saver . save_snapshot , resource_details . vm_uuid , snapshot_name , save_memory ) return set_command_result ( created_snapshot_path )
def d_hkl ( self , miller_index : Vector3Like ) -> float : """Returns the distance between the hkl plane and the origin Args : miller _ index ( [ h , k , l ] ) : Miller index of plane Returns : d _ hkl ( float )"""
gstar = self . reciprocal_lattice_crystallographic . metric_tensor hkl = np . array ( miller_index ) return 1 / ( ( dot ( dot ( hkl , gstar ) , hkl . T ) ) ** ( 1 / 2 ) )
def _make_symlink ( self , link_name : str , link_target : str ) : '''Make a symlink on the system .'''
path = self . _file_writer_session . extra_resource_path ( 'dummy' ) if path : dir_path = os . path . dirname ( path ) symlink_path = os . path . join ( dir_path , link_name ) _logger . debug ( 'symlink {} -> {}' , symlink_path , link_target ) os . symlink ( link_target , symlink_path ) _logger . in...
def classify_intersection5 ( s , curve1 , curve2 ) : """Image for : func : ` . _ surface _ helpers . classify _ intersection ` docstring ."""
if NO_IMAGES : return surface1 = bezier . Surface . from_nodes ( np . asfortranarray ( [ [ 1.0 , 1.5 , 2.0 , 1.25 , 1.75 , 1.5 ] , [ 0.0 , 1.0 , 0.0 , 0.9375 , 0.9375 , 1.875 ] , ] ) ) surface2 = bezier . Surface . from_nodes ( np . asfortranarray ( [ [ 3.0 , 1.5 , 0.0 , 2.25 , 0.75 , 1.5 ] , [ 0.0 , 1.0 , 0.0 , - ...
def getAnalysisRequestTemplatesInfo ( self ) : """Returns a lost of dicts with the analysis request templates infomration [ { ' uid ' : ' xxxx ' , ' id ' : ' xxxx ' , ' title ' : ' xxx ' , ' url ' : ' xxx ' } , . . . ]"""
arts_list = [ ] for art in self . context . ar_templates : pc = getToolByName ( self . context , 'portal_catalog' ) contentFilter = { 'portal_type' : 'ARTemplate' , 'UID' : art } art_brain = pc ( contentFilter ) if len ( art_brain ) == 1 : art_obj = art_brain [ 0 ] . getObject ( ) arts_l...
def put ( self , value , priority = 100 ) : """Put a task into the queue . Args : value ( str ) : Task data . priority ( int ) : An optional priority as an integer with at most 3 digits . Lower values signify higher priority ."""
task_name = '{}{:03d}_{}' . format ( self . TASK_PREFIX , priority , self . _counter ) path = posixpath . join ( self . _queue_path , task_name ) self . _client . kv [ path ] = value
def delete_orderrun ( backend , orderrun_id ) : """Delete the orderrun specified by the argument ."""
click . secho ( '%s - Deleting orderrun %s' % ( get_datetime ( ) , orderrun_id ) , fg = 'green' ) check_and_print ( DKCloudCommandRunner . delete_orderrun ( backend . dki , orderrun_id . strip ( ) ) )
def setPgConfigOptions ( ** kwargs ) : """Sets the PyQtGraph config options and emits a log message"""
for key , value in kwargs . items ( ) : logger . debug ( "Setting PyQtGraph config option: {} = {}" . format ( key , value ) ) pg . setConfigOptions ( ** kwargs )
def finalize_content ( self ) : """Finalize the additons"""
self . write_closed = True body = self . raw_body . decode ( self . encoding ) self . _init_xml ( body ) self . _form_output ( )
def is_ancestor_of_book ( self , id_ , book_id ) : """Tests if an ` ` Id ` ` is an ancestor of a book . arg : id ( osid . id . Id ) : an ` ` Id ` ` arg : book _ id ( osid . id . Id ) : the ` ` Id ` ` of a book return : ( boolean ) - ` ` tru ` ` e if this ` ` id ` ` is an ancestor of ` ` book _ id , ` ` ` ` ...
# Implemented from template for # osid . resource . BinHierarchySession . is _ ancestor _ of _ bin if self . _catalog_session is not None : return self . _catalog_session . is_ancestor_of_catalog ( id_ = id_ , catalog_id = book_id ) return self . _hierarchy_session . is_ancestor ( id_ = id_ , ancestor_id = book_id ...
def OnGoToCell ( self , event ) : """Shift a given cell into view"""
row , col , tab = event . key try : self . grid . actions . cursor = row , col , tab except ValueError : msg = _ ( "Cell {key} outside grid shape {shape}" ) . format ( key = event . key , shape = self . grid . code_array . shape ) post_command_event ( self . grid . main_window , self . grid . StatusBarMsg ,...
def unmarshal ( self , value , custom_formatters = None , strict = True ) : """Unmarshal parameter from the value ."""
if self . deprecated : warnings . warn ( "The schema is deprecated" , DeprecationWarning ) casted = self . cast ( value , custom_formatters = custom_formatters , strict = strict ) if casted is None and not self . required : return None if self . enum and casted not in self . enum : raise InvalidSchemaValue ...
def get_documentation ( self , element , namespace = None , schema_str = None ) : """* * Helper method : * * should return an schema specific documentation given an element parsing or getting the ` Clark ' s Notation ` _ ` { url : schema } Element ` from the message error on validate method . : param str elem...
if namespace is None : namespace = { 'xs' : 'http://www.w3.org/2001/XMLSchema' } schema_root = etree . parse ( StringIO ( self . schema ) ) document = schema_root . xpath ( self . get_element_from_clark ( element ) , namespaces = namespace ) return document and document [ 0 ] . text or ''
def _format_str ( format_int ) : """Return the string representation of a given numeric format ."""
for dictionary in _formats , _subtypes , _endians : for k , v in dictionary . items ( ) : if v == format_int : return k else : return 'n/a'
def description ( self , request , tag ) : """Render the description of the wrapped L { Parameter } instance ."""
if self . parameter . description is not None : tag [ self . parameter . description ] return tag
def image_save_buffer_fix ( maxblock = 1048576 ) : """Contextmanager that change MAXBLOCK in ImageFile ."""
before = ImageFile . MAXBLOCK ImageFile . MAXBLOCK = maxblock try : yield finally : ImageFile . MAXBLOCK = before
def _user_to_rgba ( color , expand = True , clip = False ) : """Convert color ( s ) from any set of fmts ( str / hex / arr ) to RGB ( A ) array"""
if color is None : color = np . zeros ( 4 , np . float32 ) if isinstance ( color , string_types ) : color = _string_to_rgb ( color ) elif isinstance ( color , ColorArray ) : color = color . rgba # We have to treat this specially elif isinstance ( color , ( list , tuple ) ) : if any ( isinstance ( c , st...
def query_geonames_country ( self , placename , country ) : """Like query _ geonames , but this time limited to a specified country ."""
# first , try for an exact phrase match q = { "multi_match" : { "query" : placename , "fields" : [ 'name^5' , 'asciiname^5' , 'alternativenames' ] , "type" : "phrase" } } res = self . conn . filter ( "term" , country_code3 = country ) . query ( q ) [ 0 : 50 ] . execute ( ) # if no results , use some fuzziness , but sti...
def get_pvalue ( self ) : """Returns pval for 1st method , if it exists . Else returns uncorrected pval ."""
if self . method_flds : return getattr ( self , "p_{m}" . format ( m = self . get_method_name ( ) ) ) return getattr ( self , "p_uncorrected" )
def p_program_def ( t ) : """program _ def : PROGRAM ID LBRACE version _ def version _ def _ list RBRACE EQUALS constant SEMI"""
print ( "Ignoring program {0:s} = {1:s}" . format ( t [ 2 ] , t [ 8 ] ) ) global name_dict id = t [ 2 ] value = t [ 8 ] lineno = t . lineno ( 1 ) if id_unique ( id , 'program' , lineno ) : name_dict [ id ] = const_info ( id , value , lineno )
def format ( self , altitude = None , deg_char = '' , min_char = 'm' , sec_char = 's' ) : """Format decimal degrees ( DD ) to degrees minutes seconds ( DMS )"""
latitude = "%s %s" % ( format_degrees ( abs ( self . latitude ) , symbols = { 'deg' : deg_char , 'arcmin' : min_char , 'arcsec' : sec_char } ) , self . latitude >= 0 and 'N' or 'S' ) longitude = "%s %s" % ( format_degrees ( abs ( self . longitude ) , symbols = { 'deg' : deg_char , 'arcmin' : min_char , 'arcsec' : sec_c...
def calc_tkor_v1 ( self ) : """Adjust the given air temperature values . Required control parameters : | NHRU | | KT | Required input sequence : | TemL | Calculated flux sequence : | TKor | Basic equation : : math : ` TKor = KT + TemL ` Example : > > > from hydpy . models . lland import * > ...
con = self . parameters . control . fastaccess inp = self . sequences . inputs . fastaccess flu = self . sequences . fluxes . fastaccess for k in range ( con . nhru ) : flu . tkor [ k ] = con . kt [ k ] + inp . teml
def cudnnGetConvolution2dForwardOutputDim ( convDesc , inputTensorDesc , wDesc ) : """Return the dimensions of the output tensor given a convolution descriptor . This function returns the dimensions of the resulting 4D tensor of a 2D convolution , given the convolution descriptor , the input tensor descriptor a...
n = ctypes . c_int ( ) c = ctypes . c_int ( ) h = ctypes . c_int ( ) w = ctypes . c_int ( ) status = _libcudnn . cudnnGetConvolution2dForwardOutputDim ( convDesc , inputTensorDesc , wDesc , ctypes . byref ( n ) , ctypes . byref ( c ) , ctypes . byref ( h ) , ctypes . byref ( w ) ) cudnnCheckStatus ( status ) return n ....
def describe_features ( self , traj ) : """Return a list of dictionaries describing the atom pair features . Parameters traj : mdtraj . Trajectory The trajectory to describe Returns feature _ descs : list of dict Dictionary describing each feature with the following information about the atoms partici...
feature_descs = [ ] top = traj . topology residue_indices = [ [ top . atom ( i [ 0 ] ) . residue . index , top . atom ( i [ 1 ] ) . residue . index ] for i in self . atom_indices ] aind = [ ] resseqs = [ ] resnames = [ ] for ind , resid_ids in enumerate ( residue_indices ) : aind += [ [ i for i in self . atom_indic...
def samples_to_records ( samples , default_keys = None ) : """Convert samples into output CWL records ."""
from bcbio . pipeline import run_info RECORD_CONVERT_TO_LIST = set ( [ "config__algorithm__tools_on" , "config__algorithm__tools_off" , "reference__genome_context" ] ) all_keys = _get_all_cwlkeys ( samples , default_keys ) out = [ ] for data in samples : for raw_key in sorted ( list ( all_keys ) ) : key = r...
def build ( documentPath , outputUFOFormatVersion = 3 , roundGeometry = True , verbose = True , # not supported logPath = None , # not supported progressFunc = None , # not supported processRules = True , logger = None , useVarlib = False , ) : """Simple builder for UFO designspaces ."""
import os , glob if os . path . isdir ( documentPath ) : # process all * . designspace documents in this folder todo = glob . glob ( os . path . join ( documentPath , "*.designspace" ) ) else : # process the todo = [ documentPath ] results = [ ] for path in todo : document = DesignSpaceProcessor ( ufoVersio...
def read ( self , timeout = 20.0 ) : """read data on the IN endpoint associated to the HID interface"""
start = time ( ) while len ( self . rcv_data ) == 0 : sleep ( 0 ) if time ( ) - start > timeout : # Read operations should typically take ~ 1-2ms . # If this exception occurs , then it could indicate # a problem in one of the following areas : # 1 . Bad usb driver causing either a dropped read or wr...
def _utc_year ( self ) : """Return a fractional UTC year , for convenience when plotting . An experiment , probably superseded by the ` ` J ` ` attribute below ."""
d = self . _utc_float ( ) - 1721059.5 # d + = offset C = 365 * 100 + 24 d -= 365 d += d // C - d // ( 4 * C ) d += 365 # Y = d / C * 100 # print ( Y ) K = 365 * 3 + 366 d -= ( d + K * 7 // 8 ) // K # d - = d / / 1461.0 return d / 365.0
def migrate_database ( adapter ) : """Migrate an old loqusdb instance to 1.0 Args : adapter Returns : nr _ updated ( int ) : Number of variants that where updated"""
all_variants = adapter . get_variants ( ) nr_variants = all_variants . count ( ) nr_updated = 0 with progressbar ( all_variants , label = "Updating variants" , length = nr_variants ) as bar : for variant in bar : # Do not update if the variants have the correct format if 'chrom' in variant : con...
def _stripe_object_to_refunds ( cls , target_cls , data , charge ) : """Retrieves Refunds for a charge : param target _ cls : The target class to instantiate per invoice item . : type target _ cls : ` ` Refund ` ` : param data : The data dictionary received from the Stripe API . : type data : dict : param...
refunds = data . get ( "refunds" ) if not refunds : return [ ] refund_objs = [ ] for refund_data in refunds . get ( "data" , [ ] ) : item , _ = target_cls . _get_or_create_from_stripe_object ( refund_data , refetch = False ) refund_objs . append ( item ) return refund_objs
async def emit_event ( self , event ) : """Publish an event : param event : Event object"""
self . log . info ( "publishing event on %s" , self . publish_topic ) if self . config . extra [ 'config' ] [ 'pub_options' ] [ 'retain' ] : try : await persist_event ( self . publish_topic , event , self . pool ) except SystemError as error : self . log . error ( error ) return loop = a...
def from_line ( cls , line ) : """: return : New RefLogEntry instance from the given revlog line . : param line : line bytes without trailing newline : raise ValueError : If line could not be parsed"""
line = line . decode ( defenc ) fields = line . split ( '\t' , 1 ) if len ( fields ) == 1 : info , msg = fields [ 0 ] , None elif len ( fields ) == 2 : info , msg = fields else : raise ValueError ( "Line must have up to two TAB-separated fields." " Got %s" % repr ( line ) ) # END handle first split oldhexsh...
def custom_function ( func , input_files , output_file ) : """Calls a custom function which must create the output file . The custom function takes 3 parameters : ` ` input _ files ` ` , ` ` output _ file ` ` and a boolean ` ` release ` ` ."""
from . modules import utils return { 'dependencies_fn' : utils . no_dependencies , 'compiler_fn' : func , 'input' : input_files , 'output' : output_file , 'kwargs' : { } , }
def register ( self , entity ) : """Registers a new entity and returns the entity object with an ID"""
response = self . api . post_entity ( entity . serialize ) print ( response ) print ( ) if response [ 'status' ] [ 'code' ] == 200 : entity . id = response [ 'id' ] if response [ 'status' ] [ 'code' ] == 409 : # entity already exists entity . id = next ( i . id for i in self . api . agent_entities if i . name =...
def makeairplantloop ( data , commdct ) : """make the edges for the airloop and the plantloop"""
anode = "epnode" endnode = "EndNode" # in plantloop get : # demand inlet , outlet , branchlist # supply inlet , outlet , branchlist plantloops = loops . plantloopfields ( data , commdct ) # splitters # inlet # outlet1 # outlet2 splitters = loops . splitterfields ( data , commdct ) # mixer # outlet # inlet1 # inlet2 mix...
def _find_base_tds_url ( catalog_url ) : """Identify the base URL of the THREDDS server from the catalog URL . Will retain URL scheme , host , port and username / password when present ."""
url_components = urlparse ( catalog_url ) if url_components . path : return catalog_url . split ( url_components . path ) [ 0 ] else : return catalog_url