signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def results ( data ) :
"""Results""" | cdata = [ ]
for r in data :
cdata . append ( r . data )
return cdata |
def setup_lilypond_windows ( path = "default" ) :
'''Optional helper method which does the environment setup for lilypond in windows . If you ' ve ran this method , you do not need and should not provide
a lyscript when you instantiate this class . As this method is static , you can run this method before you set... | default = "C:/Program Files (x86)/LilyPond/usr/bin"
path_variable = os . environ [ 'PATH' ] . split ( ";" )
if path == "default" :
path_variable . append ( default )
else :
path_variable . append ( path )
os . environ [ 'PATH' ] = ";" . join ( path_variable ) |
def send_dir ( self , local_path , remote_path , user = 'root' ) :
"""Upload a directory on the remote host .""" | self . enable_user ( user )
return self . ssh_pool . send_dir ( user , local_path , remote_path ) |
def get_last_traded_dt ( self , asset , dt ) :
"""Get the latest day on or before ` ` dt ` ` in which ` ` asset ` ` traded .
If there are no trades on or before ` ` dt ` ` , returns ` ` pd . NaT ` ` .
Parameters
asset : zipline . asset . Asset
The asset for which to get the last traded day .
dt : pd . Tim... | country_code = self . _country_code_for_assets ( [ asset . sid ] )
return self . _readers [ country_code ] . get_last_traded_dt ( asset , dt ) |
def create_badge ( self , update = False ) :
"""Saves the badge in the database ( or updates it if ` ` update ` ` is ` ` True ` ` ) .
Returns a tuple : ` ` badge ` ` ( the badge object ) and ` ` created ` ` ( ` ` True ` ` , if
badge has been created ) .""" | badge , created = self . badge , False
if badge :
logger . debug ( '✓ Badge %s: already created' , badge . slug )
if update :
to_update = { }
for field in ( 'name' , 'slug' , 'description' , 'image' ) :
attr = getattr ( self , field )
badge_attr = getattr ( badge , field ... |
def set_data_length ( self , length ) : # type : ( int ) - > None
'''A method to set the length of data for this El Torito Entry .
Parameters :
length - The new length for the El Torito Entry .
Returns :
Nothing .''' | if not self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'El Torito Entry not initialized' )
self . sector_count = utils . ceiling_div ( length , 512 ) |
def transform ( self , ref , strict = False ) :
"""Transform a URI reference relative to ` self ` into a
: class : ` SplitResult ` representing its target URI .""" | scheme , authority , path , query , fragment = self . RE . match ( ref ) . groups ( )
# RFC 3986 5.2.2 . Transform References
if scheme is not None and ( strict or scheme != self . scheme ) :
path = self . __remove_dot_segments ( path )
elif authority is not None :
scheme = self . scheme
path = self . __rem... |
def filter_unique_peptides ( peptides , score , ns ) :
"""Filters unique peptides from multiple Percolator output XML files .
Takes a dir with a set of XMLs , a score to filter on and a namespace .
Outputs an ElementTree .""" | scores = { 'q' : 'q_value' , 'pep' : 'pep' , 'p' : 'p_value' , 'svm' : 'svm_score' }
highest = { }
for el in peptides :
featscore = float ( el . xpath ( 'xmlns:%s' % scores [ score ] , namespaces = ns ) [ 0 ] . text )
seq = reader . get_peptide_seq ( el , ns )
if seq not in highest :
highest [ seq ]... |
def _makeTags ( tagStr , xml ) :
"""Internal helper to construct opening and closing tag expressions , given a tag name""" | if isinstance ( tagStr , basestring ) :
resname = tagStr
tagStr = Keyword ( tagStr , caseless = not xml )
else :
resname = tagStr . name
tagAttrName = Word ( alphas , alphanums + "_-:" )
if ( xml ) :
tagAttrValue = dblQuotedString . copy ( ) . setParseAction ( removeQuotes )
openTag = Suppress ( "<"... |
def elem_add ( self , idx = None , name = None , ** kwargs ) :
"""Add an element of this model
: param idx : element idx
: param name : element name
: param kwargs : keyword arguments of the parameters
: return : allocated idx""" | idx = self . system . devman . register_element ( dev_name = self . _name , idx = idx )
self . system . __dict__ [ self . _group ] . register_element ( self . _name , idx )
self . uid [ idx ] = self . n
self . idx . append ( idx )
self . mdl_to . append ( list ( ) )
self . mdl_from . append ( list ( ) )
# self . n + = ... |
def kak_decomposition ( mat : np . ndarray , rtol : float = 1e-5 , atol : float = 1e-8 ) -> KakDecomposition :
"""Decomposes a 2 - qubit unitary into 1 - qubit ops and XX / YY / ZZ interactions .
Args :
mat : The 4x4 unitary matrix to decompose .
rtol : Per - matrix - entry relative tolerance on equality .
... | magic = np . array ( [ [ 1 , 0 , 0 , 1j ] , [ 0 , 1j , 1 , 0 ] , [ 0 , 1j , - 1 , 0 ] , [ 1 , 0 , 0 , - 1j ] ] ) * np . sqrt ( 0.5 )
gamma = np . array ( [ [ 1 , 1 , 1 , 1 ] , [ 1 , 1 , - 1 , - 1 ] , [ - 1 , 1 , - 1 , 1 ] , [ 1 , - 1 , - 1 , 1 ] ] ) * 0.25
# Diagonalize in magic basis .
left , d , right = diagonalize .... |
def load_reconstruction ( folder , slice_start = 0 , slice_end = - 1 ) :
"""Load a volume from folder , also returns the corresponding partition .
Parameters
folder : str
Path to the folder where the DICOM files are stored .
slice _ start : int
Index of the first slice to use . Used for subsampling .
sl... | file_names = sorted ( [ f for f in os . listdir ( folder ) if f . endswith ( ".IMA" ) ] )
if len ( file_names ) == 0 :
raise ValueError ( 'No DICOM files found in {}' . format ( folder ) )
volumes = [ ]
datasets = [ ]
file_names = file_names [ slice_start : slice_end ]
for file_name in tqdm . tqdm ( file_names , 'l... |
def range_pad ( lower , upper , padding = None , log = False ) :
"""Pads the range by a fraction of the interval""" | if padding is not None and not isinstance ( padding , tuple ) :
padding = ( padding , padding )
if is_number ( lower ) and is_number ( upper ) and padding is not None :
if not isinstance ( lower , datetime_types ) and log and lower > 0 and upper > 0 :
log_min = np . log ( lower ) / np . log ( 10 )
... |
def _ParseRedirected ( self , parser_mediator , msiecf_item , recovered = False ) :
"""Extract data from a MSIE Cache Files ( MSIECF ) redirected item .
Every item is stored as an event object , one for each timestamp .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and ... | date_time = dfdatetime_semantic_time . SemanticTime ( 'Not set' )
event_data = MSIECFRedirectedEventData ( )
event_data . offset = msiecf_item . offset
event_data . recovered = recovered
event_data . url = msiecf_item . location
event = time_events . DateTimeValuesEvent ( date_time , definitions . TIME_DESCRIPTION_NOT_... |
def find_classes ( self , name = ".*" , no_external = False ) :
"""Find classes by name , using regular expression
This method will return all ClassAnalysis Object that match the name of
the class .
: param name : regular expression for class name ( default " . * " )
: param no _ external : Remove external ... | for cname , c in self . classes . items ( ) :
if no_external and isinstance ( c . get_vm_class ( ) , ExternalClass ) :
continue
if re . match ( name , cname ) :
yield c |
def size_bundle_from_tubecount ( N , Do , pitch , Ntp = 1 , angle = 30 , Method = None , AvailableMethods = False ) :
r'''Calculates the outer diameter of a tube bundle containing a specified
number of tubes .
The tube count is effected by the pitch , number of tube passes , and angle .
The result is an exact... | def list_methods ( ) :
methods = [ 'Phadkeb' ]
if Ntp == 1 :
methods . append ( 'HEDH' )
if Ntp in [ 1 , 2 , 4 , 8 ] :
methods . append ( 'VDI' )
if Ntp in [ 1 , 2 , 4 , 6 ] : # Also restricted to 1.25 pitch ratio but not hard coded
methods . append ( 'Perry' )
return methods... |
def _setup_events ( plugin ) :
"""Handles setup or teardown of event hook registration for the provided
plugin .
` plugin `
` ` Plugin ` ` class .""" | events = plugin . events
if events and isinstance ( events , ( list , tuple ) ) :
for event in [ e for e in events if e in _EVENT_VALS ] :
register ( 'event' , event , plugin ) |
def track_pa11y_stats ( pa11y_results , spider ) :
"""Keep track of the number of pa11y errors , warnings , and notices that
we ' ve seen so far , using the Scrapy stats collector :
http : / / doc . scrapy . org / en / 1.1 / topics / stats . html""" | num_err , num_warn , num_notice = pa11y_counts ( pa11y_results )
stats = spider . crawler . stats
stats . inc_value ( "pa11y/error" , count = num_err , spider = spider )
stats . inc_value ( "pa11y/warning" , count = num_warn , spider = spider )
stats . inc_value ( "pa11y/notice" , count = num_notice , spider = spider ) |
def lock ( self , lock_name , timeout = 900 ) :
"""Attempt to use lock and unlock , which will work if the Cache is Redis ,
but fall back to a memcached - compliant add / delete approach .
If the Jobtastic Cache isn ' t Redis or Memcache , or another product
with a compatible lock or add / delete API , then a... | # Try Redis first
try :
try :
lock = self . cache . lock
except AttributeError :
try : # Possibly using old Django - Redis
lock = self . cache . client . lock
except AttributeError : # Possibly using Werkzeug + Redis
lock = self . cache . _client . lock
have_l... |
def _get ( self , obj ) :
'''Internal implementation of instance attribute access for the
` ` BasicPropertyDescriptor ` ` getter .
If the value has not been explicitly set by a user , return that
value . Otherwise , return the default .
Args :
obj ( HasProps ) : the instance to get a value of this propert... | if not hasattr ( obj , '_property_values' ) :
raise RuntimeError ( "Cannot get a property value '%s' from a %s instance before HasProps.__init__" % ( self . name , obj . __class__ . __name__ ) )
if self . name not in obj . _property_values :
return self . _get_default ( obj )
else :
return obj . _property_v... |
def _increment_index ( self , di = 1 ) :
"""Move the most recently displayed annotation to the next item in the
series , if possible . If ` ` di ` ` is - 1 , move it to the previous item .""" | if self . _last_event is None :
return
if not hasattr ( self . _last_event , 'ind' ) :
return
event = self . _last_event
xy = pick_info . get_xy ( event . artist )
if xy is not None :
x , y = xy
i = ( event . ind [ 0 ] + di ) % len ( x )
event . ind = [ i ]
event . mouseevent . xdata = x [ i ]
... |
def subtract ( dict_a , dict_b , strict = False ) :
"""a stricter form of subtract _ by _ key ( ) , this version will only remove an
entry from dict _ a if the key is in dict _ b * and * the value at that key
matches""" | if not strict :
return subtract_by_key ( dict_a , dict_b )
difference_dict = { }
for key in dict_a :
if key not in dict_b or dict_b [ key ] != dict_a [ key ] :
difference_dict [ key ] = dict_a [ key ]
return difference_dict |
def createValidationDataSampler ( dataset , ratio ) :
"""Create ` torch . utils . data . Sampler ` s used to split the dataset into 2 ramdom
sampled subsets . The first should used for training and the second for
validation .
: param dataset : A valid torch . utils . data . Dataset ( i . e . torchvision . dat... | indices = np . random . permutation ( len ( dataset ) )
training_count = int ( len ( indices ) * ratio )
train = torch . utils . data . SubsetRandomSampler ( indices = indices [ : training_count ] )
validate = torch . utils . data . SubsetRandomSampler ( indices = indices [ training_count : ] )
return ( train , validat... |
def inspect ( lines ) :
"""Inspect SDFile list of string
Returns :
tuple : ( data label list , number of records )""" | labels = set ( )
count = 0
exp = re . compile ( r">.*?<([\w ]+)>" )
# Space should be accepted
valid = False
for line in lines :
if line . startswith ( "M END\n" ) :
valid = True
elif line . startswith ( "$$$$" ) :
count += 1
valid = False
else :
result = exp . match ( line ... |
def standardize ( Y , in_place = False ) :
"""standardize Y in a way that is robust to missing values
in _ place : create a copy or carry out inplace opreations ?""" | if in_place :
YY = Y
else :
YY = Y . copy ( )
for i in range ( YY . shape [ 1 ] ) :
Iok = ~ SP . isnan ( YY [ : , i ] )
Ym = YY [ Iok , i ] . mean ( )
YY [ : , i ] -= Ym
Ys = YY [ Iok , i ] . std ( )
YY [ : , i ] /= Ys
return YY |
def _get_maxentscan ( data ) :
"""The plugin executes the logic from one of the scripts depending on which
splice region the variant overlaps :
score5 . pl : last 3 bases of exon - - > first 6 bases of intron
score3 . pl : last 20 bases of intron - - > first 3 bases of exon
The plugin reports the reference ... | maxentscan_dir = os . path . dirname ( os . path . realpath ( config_utils . get_program ( "maxentscan_score3.pl" , data [ "config" ] ) ) )
if maxentscan_dir and os . path . exists ( maxentscan_dir ) :
return [ "--plugin" , "MaxEntScan,%s" % ( maxentscan_dir ) ]
else :
return [ ] |
def revoke_user ( self , user_id ) :
"""Revoke a user from the tenant
This will remove pending or approved roles but
will not not delete the user from Keystone .""" | uri = 'openstack/users/%s' % user_id
try :
resp = self . delete ( uri )
except AttributeError : # note : this breaks . stacktask returns a string , not json .
return
self . expected_success ( 200 , resp . status )
return rest_client . ResponseBody ( resp , None ) |
def copy_analysis_files ( cls , orig_dir , dest_dir , copyfiles ) :
"""Copy a list of files from orig _ dir to dest _ dir""" | for pattern in copyfiles :
glob_path = os . path . join ( orig_dir , pattern )
files = glob . glob ( glob_path )
for ff in files :
f = os . path . basename ( ff )
orig_path = os . path . join ( orig_dir , f )
dest_path = os . path . join ( dest_dir , f )
try :
cop... |
def get_simulant_creator ( self ) -> Callable [ [ int , Union [ Mapping [ str , Any ] , None ] ] , pd . Index ] :
"""Grabs a reference to the function that creates new simulants ( adds rows to the state table ) .
Returns
Callable
The simulant creator function . The creator function takes the number of simulan... | return self . _population_manager . get_simulant_creator ( ) |
def set_file_params ( self , reopen_on_reload = None , trucate_on_statup = None , max_size = None , rotation_fname = None , touch_reopen = None , touch_rotate = None , owner = None , mode = None ) :
"""Set various parameters related to file logging .
: param bool reopen _ on _ reload : Reopen log after reload .
... | self . _set ( 'log-reopen' , reopen_on_reload , cast = bool )
self . _set ( 'log-truncate' , trucate_on_statup , cast = bool )
self . _set ( 'log-maxsize' , max_size )
self . _set ( 'log-backupname' , rotation_fname )
self . _set ( 'touch-logreopen' , touch_reopen , multi = True )
self . _set ( 'touch-logrotate' , touc... |
def main ( ) :
"""Entry point for console script jp2dump .""" | kwargs = { 'description' : 'Print JPEG2000 metadata.' , 'formatter_class' : argparse . ArgumentDefaultsHelpFormatter }
parser = argparse . ArgumentParser ( ** kwargs )
parser . add_argument ( '-x' , '--noxml' , help = 'suppress XML' , action = 'store_true' )
parser . add_argument ( '-s' , '--short' , help = 'only print... |
def delete_image_tar ( file_obj , tar ) :
'''delete image tar will close a file object ( if extracted into
memory ) or delete from the file system ( if saved to disk )''' | try :
file_obj . close ( )
except :
tar . close ( )
if os . path . exists ( file_obj ) :
os . remove ( file_obj )
deleted = True
bot . debug ( 'Deleted temporary tar.' )
return deleted |
def GetFileObjectReferenceCount ( self , path_spec ) :
"""Retrieves the reference count of a cached file - like object .
Args :
path _ spec ( PathSpec ) : path specification .
Returns :
int : reference count or None if there is no file - like object for
the corresponding path specification cached .""" | cache_value = self . _file_object_cache . GetCacheValue ( path_spec . comparable )
if not cache_value :
return None
return cache_value . reference_count |
def get_live_league_games ( self ) :
"""Returns a dictionary containing a list of ticked games in progress
: return : dictionary of live games , see : doc : ` responses < / responses > `""" | url = self . __build_url ( urls . GET_LIVE_LEAGUE_GAMES )
req = self . executor ( url )
if self . logger :
self . logger . info ( 'URL: {0}' . format ( url ) )
if not self . __check_http_err ( req . status_code ) :
return response . build ( req , url , self . raw_mode ) |
def configure_roles_on_host ( api , host ) :
"""Go through all the roles on this host , and configure them if they
match the role types that we care about .""" | for role_ref in host . roleRefs : # Mgmt service / role has no cluster name . Skip over those .
if role_ref . get ( 'clusterName' ) is None :
continue
# Get the role and inspect the role type
role = api . get_cluster ( role_ref [ 'clusterName' ] ) . get_service ( role_ref [ 'serviceName' ] ) . get_r... |
def get_searches ( self , quick = False , saved = True ) :
'''Get searches listing .
: param quick bool : Include quick searches ( default False )
: param quick saved : Include saved searches ( default True )
: returns : : py : class : ` planet . api . models . Searches `
: raises planet . api . exceptions ... | params = { }
if saved and not quick :
params [ 'search_type' ] = 'saved'
elif quick :
params [ 'search_type' ] = 'quick'
return self . _get ( self . _url ( 'data/v1/searches/' ) , body_type = models . Searches , params = params ) . get_body ( ) |
def identifier ( self , camelsplit = False , ascii = True ) :
"""return a python identifier from the string ( underscore separators )""" | return self . nameify ( camelsplit = camelsplit , ascii = ascii , sep = '_' ) |
def download ( self , data , block_num = - 1 ) :
"""Downloads a DB data into the AG .
A whole block ( including header and footer ) must be available into the
user buffer .
: param block _ num : New Block number ( or - 1)
: param data : the user buffer""" | type_ = c_byte
size = len ( data )
cdata = ( type_ * len ( data ) ) . from_buffer_copy ( data )
result = self . library . Cli_Download ( self . pointer , block_num , byref ( cdata ) , size )
return result |
def create_dynamic ( cls , name , interface_id , dynamic_index = 1 , reverse_connection = True , automatic_default_route = True , domain_server_address = None , loopback_ndi = '127.0.0.1' , location_ref = None , log_server_ref = None , zone_ref = None , enable_gti = False , enable_antivirus = False , sidewinder_proxy_e... | interfaces = kw . pop ( 'interfaces' , [ ] )
# Add the primary interface to the interface list
interface = { 'interface_id' : interface_id , 'interface' : 'single_node_interface' , 'zone_ref' : zone_ref , 'interfaces' : [ { 'nodes' : [ { 'dynamic' : True , 'dynamic_index' : dynamic_index , 'nodeid' : 1 , 'reverse_conne... |
def isscalar ( cls , dataset , dim ) :
"""Tests if dimension is scalar in each subpath .""" | if not dataset . data :
return True
ds = cls . _inner_dataset_template ( dataset )
isscalar = [ ]
for d in dataset . data :
ds . data = d
isscalar . append ( ds . interface . isscalar ( ds , dim ) )
return all ( isscalar ) |
def geojson_polygon_to_mask ( feature , shape , lat_idx , lon_idx ) :
"""Convert a GeoJSON polygon feature to a numpy array
Args :
feature ( pygeoj . Feature ) : polygon feature to draw
shape ( tuple ( int , int ) ) : shape of 2D target numpy array to draw polygon in
lat _ idx ( func ) : function converting... | import matplotlib
# specify ' agg ' renderer , Mac renderer does not support what we want to do below
matplotlib . use ( 'agg' )
import matplotlib . pyplot as plt
from matplotlib import patches
import numpy as np
# we can only do polygons right now
if feature . geometry . type not in ( 'Polygon' , 'MultiPolygon' ) :
... |
def readline ( self , size = - 1 ) :
"The size is ignored since a complete line must be read ." | line = self . fin . readline ( )
if not line :
return ''
return self . process_line ( line . rstrip ( '\n' ) ) |
def _finalize ( self ) :
"""Dump traces using cPickle .""" | container = { }
try :
for name in self . _traces :
container [ name ] = self . _traces [ name ] . _trace
container [ '_state_' ] = self . _state_
file = open ( self . filename , 'w+b' )
std_pickle . dump ( container , file )
file . close ( )
except AttributeError :
pass |
def create_role_config_group ( resource_root , service_name , name , display_name , role_type , cluster_name = "default" ) :
"""Create a role config group .
@ param resource _ root : The root Resource object .
@ param service _ name : Service name .
@ param name : The name of the new group .
@ param display... | apigroup = ApiRoleConfigGroup ( resource_root , name , display_name , role_type )
return create_role_config_groups ( resource_root , service_name , [ apigroup ] , cluster_name ) [ 0 ] |
def rpc_get_completions ( self , filename , source , offset ) :
"""Get a list of completion candidates for the symbol at offset .""" | results = self . _call_backend ( "rpc_get_completions" , [ ] , filename , get_source ( source ) , offset )
# Uniquify by name
results = list ( dict ( ( res [ 'name' ] , res ) for res in results ) . values ( ) )
results . sort ( key = lambda cand : _pysymbol_key ( cand [ "name" ] ) )
return results |
def summary ( * samples ) :
"""Run SignatureCompareRelatedSimple module from qsignature tool .
Creates a matrix of pairwise comparison among samples . The
function will not run if the output exists
: param samples : list with only one element containing all samples information
: returns : ( dict ) with the ... | warnings , similar = [ ] , [ ]
qsig = config_utils . get_program ( "qsignature" , samples [ 0 ] [ 0 ] [ "config" ] )
if not qsig :
return [ [ ] ]
res_qsig = config_utils . get_resources ( "qsignature" , samples [ 0 ] [ 0 ] [ "config" ] )
jvm_opts = " " . join ( res_qsig . get ( "jvm_opts" , [ "-Xms750m" , "-Xmx8g" ... |
def _get_mod_ns ( name , fullname , includeprivate ) :
"""Return the template context of module identified by ` fullname ` as a
dict""" | ns = { # template variables
'name' : name , 'fullname' : fullname , 'members' : [ ] , 'functions' : [ ] , 'classes' : [ ] , 'exceptions' : [ ] , 'subpackages' : [ ] , 'submodules' : [ ] , 'doc' : None }
p = 0
if includeprivate :
p = 1
mod = importlib . import_module ( fullname )
ns [ 'members' ] = _get_members ( mo... |
def set_selected_submission ( self , course , task , submissionid ) :
"""Set submission whose id is ` submissionid ` to selected grading submission for the given course / task .
Returns a boolean indicating whether the operation was successful or not .""" | submission = self . submission_manager . get_submission ( submissionid )
# Do not continue if submission does not exist or is not owned by current user
if not submission :
return False
# Check if the submission if from this task / course !
if submission [ "taskid" ] != task . get_id ( ) or submission [ "courseid" ]... |
def list_metadata ( self , resource ) :
"""List all keys associated with the given resource .
Args :
resource ( intern . resource . boss . BossResource )
Returns :
( list )
Raises :
requests . HTTPError on a failure .""" | self . metadata_service . set_auth ( self . _token_metadata )
return self . metadata_service . list ( resource ) |
def parse_JSON ( self , JSON_string ) :
"""Parses a * pyowm . stationsapi30 . measurement . AggregatedMeasurement *
instance out of raw JSON data .
: param JSON _ string : a raw JSON string
: type JSON _ string : str
: return : a * pyowm . stationsapi30 . measurement . AggregatedMeasurement *
instance or ... | if JSON_string is None :
raise parse_response_error . ParseResponseError ( 'JSON data is None' )
d = json . loads ( JSON_string )
station_id = d . get ( 'station_id' , None )
ts = d . get ( 'date' , None )
if ts is not None :
ts = int ( ts )
aggregated_on = d . get ( 'type' , None )
temp = d . get ( 'temp' , di... |
def get_disk_quota ( username , machine_name = None ) :
"""Returns disk quota for username in KB""" | try :
ua = Account . objects . get ( username = username , date_deleted__isnull = True )
except Account . DoesNotExist :
return 'Account not found'
result = ua . get_disk_quota ( )
if result is None :
return False
return result * 1048576 |
def _safe_db ( num , den ) :
"""Properly handle the potential + Inf db SIR instead of raising a
RuntimeWarning .""" | if den == 0 :
return np . inf
return 10 * np . log10 ( num / den ) |
def find_or_build ( cls , ** kwargs ) :
"""Checks if an instance already exists in db with these kwargs else
returns a new , saved instance of the service ' s model class .
Args :
* * kwargs : instance parameters""" | keys = kwargs . pop ( 'keys' ) if 'keys' in kwargs else [ ]
return cls . first ( ** subdict ( kwargs , keys ) ) or cls . build ( ** kwargs ) |
def list ( self , ** params ) :
"""Retrieve all deal unqualified reasons
Returns all deal unqualified reasons available to the user according to the parameters provided
: calls : ` ` get / deal _ unqualified _ reasons ` `
: param dict params : ( optional ) Search options .
: return : List of dictionaries th... | _ , _ , deal_unqualified_reasons = self . http_client . get ( "/deal_unqualified_reasons" , params = params )
return deal_unqualified_reasons |
def _get_msge_with_gradient ( data , delta , xvschema , skipstep , p ) :
"""Calculate mean squared generalization error and its gradient ,
automatically selecting the best function .""" | t , m , l = data . shape
n = ( l - p ) * t
underdetermined = n < m * p
if underdetermined :
return _msge_with_gradient_underdetermined ( data , delta , xvschema , skipstep , p )
else :
return _msge_with_gradient_overdetermined ( data , delta , xvschema , skipstep , p ) |
def _validate ( self ) :
"""Checks whether all the attributes of this object is valid .""" | if self . region_type not in regions_attributes :
raise ValueError ( "'{0}' is not a valid region type in this package" . format ( self . region_type ) )
if self . coordsys not in valid_coordsys [ 'DS9' ] + valid_coordsys [ 'CRTF' ] :
raise ValueError ( "'{0}' is not a valid coordinate reference frame " "in ast... |
def check_code ( self , card_id , codes ) :
"""核查code""" | card_data = { 'card_id' : card_id , 'code' : codes }
return self . _post ( 'card/code/checkcode' , data = card_data ) |
def merge ( self , other ) : # type : ( TentativeType ) - > None
"""Merge two TentativeType instances""" | for hashables in other . types_hashable :
self . add ( hashables )
for non_hashbles in other . types :
self . add ( non_hashbles ) |
def tone_marks ( ) :
"""Keep tone - modifying punctuation by matching following character .
Assumes the ` tone _ marks ` pre - processor was run for cases where there might
not be any space after a tone - modifying punctuation mark .""" | return RegexBuilder ( pattern_args = symbols . TONE_MARKS , pattern_func = lambda x : u"(?<={})." . format ( x ) ) . regex |
def hide_columns ( self , subset ) :
"""Hide columns from rendering .
. . versionadded : : 0.23.0
Parameters
subset : IndexSlice
An argument to ` ` DataFrame . loc ` ` that identifies which columns
are hidden .
Returns
self : Styler""" | subset = _non_reducing_slice ( subset )
hidden_df = self . data . loc [ subset ]
self . hidden_columns = self . columns . get_indexer_for ( hidden_df . columns )
return self |
def next ( self ) :
"""Return the next available message
Blocks indefinitely unless consumer _ timeout _ ms > 0
Returns :
a single KafkaMessage from the message iterator
Raises :
ConsumerTimeout after consumer _ timeout _ ms and no message
Note :
This is also the method called internally during iterat... | self . _set_consumer_timeout_start ( )
while True :
try :
return six . next ( self . _get_message_iterator ( ) )
# Handle batch completion
except StopIteration :
self . _reset_message_iterator ( )
self . _check_consumer_timeout ( ) |
def open_keyword_cache_path ( self ) :
"""Open File dialog to choose the keyword cache path .""" | # noinspection PyCallByClass , PyTypeChecker
file_name , __ = QFileDialog . getSaveFileName ( self , self . tr ( 'Set keyword cache file' ) , self . leKeywordCachePath . text ( ) , self . tr ( 'Sqlite DB File (*.db)' ) )
if file_name :
self . leKeywordCachePath . setText ( file_name ) |
def request ( self , method , url , params = None , data = None , headers = None , cookies = None , files = None , auth = None , timeout = None , allow_redirects = True , proxies = None , hooks = None , stream = None , verify = None , cert = None , json = None ) :
"""Constructs a : class : ` Request < Request > ` ,... | # Create the Request .
req = Request ( method = method . upper ( ) , url = url , headers = headers , files = files , data = data or { } , json = json , params = params or { } , auth = auth , cookies = cookies , hooks = hooks , )
prep = self . prepare_request ( req )
proxies = proxies or { }
settings = self . merge_envi... |
def cleanup ( ) :
"""deletes launch configs and auto scaling group""" | try :
cloud_config = CloudConfig ( )
cloud_controller = CloudController ( cloud_config )
cloud_controller . cleanup ( )
except CloudComposeException as ex :
print ( ex ) |
def upload_scripts ( client , script_dir , overwrite = True ) :
"""Uploads general - purpose scripts to a Google Storage bucket .
TODO : docstring""" | local_dir = os . path . join ( genometools . _root , 'data' , 'gcloud' , 'scripts' )
match = _BUCKET_PAT . match ( script_dir )
script_bucket = match . group ( 1 )
script_prefix = match . group ( 2 )
depth = len ( local_dir . split ( os . sep ) )
for root , dirs , files in os . walk ( local_dir ) :
rel_path = '/' .... |
def walk ( patterns , dirname ) :
"""Like # os . walk ( ) , but filters the files and directories that are excluded by
the specified * patterns * .
# Arguments
patterns ( IgnoreList , IgnoreListCollection ) : Can also be any object that
implements the # IgnoreList . match ( ) interface .
dirname ( str ) :... | join = os . path . join
for root , dirs , files in os . walk ( dirname , topdown = True ) :
dirs [ : ] = [ d for d in dirs if patterns . match ( join ( root , d ) , True ) != MATCH_IGNORE ]
files [ : ] = [ f for f in files if patterns . match ( join ( root , f ) , False ) != MATCH_IGNORE ]
yield root , dirs... |
def _load_service_containers ( self , service , configs , use_cache ) :
""": param service :
: return :""" | if not isinstance ( service , Service ) :
raise TypeError ( "service must of an instance of Service" )
if not service . containers :
container_name = self . _container_registration ( service . alias )
if service . dependencies :
self . _load_dependency_containers ( service )
if not service . car... |
def get_elms ( self , id_ = None , class_name = None , name = None , tag_name = None , text = None , xpath = None , parent_id = None , parent_class_name = None , parent_name = None , parent_tag_name = None , css_selector = None ) :
"""Shortcut for : py : meth : ` find _ element * < selenium . webdriver . remote . w... | if parent_id or parent_class_name or parent_name or parent_tag_name :
parent = self . get_elm ( parent_id , parent_class_name , parent_name , parent_tag_name )
else :
parent = self
if len ( [ x for x in ( id_ , class_name , tag_name , text , xpath ) if x is not None ] ) > 1 :
raise Exception ( 'You can find... |
def render ( self ) :
"""Render html page and atom feed""" | context = GLOBAL_TEMPLATE_CONTEXT . copy ( )
context [ 'tag' ] = self
entries = list ( self . entries )
entries . sort ( key = operator . attrgetter ( 'date' ) , reverse = True )
context [ 'entries' ] = entries
# render html page
render_to = os . path . join ( CONFIG [ 'output_to' ] , 'tags' , self . slug )
if not os .... |
def description ( cls ) :
"""Return a field - > data type dictionary describing this model
as reported by the database .
: rtype : dict""" | description = { }
for column in cls . __table__ . columns : # pylint : disable = no - member
column_description = str ( column . type )
if not column . nullable :
column_description += ' (required)'
description [ column . name ] = column_description
return description |
def is_empty ( self ) :
"""Check whether this interval is empty .
: rtype : bool""" | if self . bounds [ 1 ] < self . bounds [ 0 ] :
return True
if self . bounds [ 1 ] == self . bounds [ 0 ] :
return not ( self . included [ 0 ] and self . included [ 1 ] ) |
def __instances ( self ) :
"""Cache instances , allowing generators to be used and reused .
This fills a cache as the generator gets emptied , eventually
reading exclusively from the cache .""" | for instance in self . __instances_cache :
yield instance
for instance in self . __instances_original :
self . __instances_cache . append ( instance )
yield instance |
def known_remotes ( self ) :
"""The names of the configured remote repositories ( a list of : class : ` . Remote ` objects ) .""" | objects = [ ]
output = self . context . capture ( 'bzr' , 'config' , 'parent_location' , check = False , silent = True , )
if output and not output . isspace ( ) :
location = output . strip ( )
# The ` bzr branch ' command has the unusual habit of converting
# absolute pathnames into relative pathnames . Al... |
def get_config ( ) :
"""Return configuration for current session .
When called for the first time , this will create a config object , using
whatever is the default load path to find the config yaml""" | if session . config is None :
path = session . default_config_path
if os . path . isfile ( path ) :
logging . info ( "LOADING FROM: {}" . format ( path ) )
session . config = load_config ( path )
else :
session . config = Config ( )
logging . info ( "using default session: {}... |
def list_edges ( self , * , axis : int ) -> List [ str ] :
"""* * DEPRECATED * * - Use ` ds . row _ graphs . keys ( ) ` or ` ds . col _ graphs . keys ( ) ` instead""" | deprecated ( "'list_edges' is deprecated. Use 'ds.row_graphs.keys()' or 'ds.col_graphs.keys()' instead" )
if axis == 0 :
return self . row_graphs . keys ( )
elif axis == 1 :
return self . col_graphs . keys ( )
else :
return [ ] |
def cnst_A1T ( self , Y1 ) :
r"""Compute : math : ` A _ 1 ^ T \ mathbf { y } _ 1 ` component of
: math : ` A ^ T \ mathbf { y } ` . In this case : math : ` A _ 1 ^ T \ mathbf { y } _ 1 =
( \ Gamma _ 0 ^ T \ ; \ ; \ Gamma _ 1 ^ T \ ; \ ; \ ldots ) \ mathbf { y } _ 1 ` .""" | Y1f = sl . rfftn ( Y1 , None , axes = self . cri . axisN )
return sl . irfftn ( np . conj ( self . GDf ) * Y1f , self . cri . Nv , self . cri . axisN ) |
def get_nodes_by_source ( self , graph , source_full_name ) :
"""yields nodes from graph are the specified source .""" | parts = source_full_name . split ( '.' )
if len ( parts ) == 1 :
target_source , target_table = parts [ 0 ] , None
elif len ( parts ) == 2 :
target_source , target_table = parts
else : # len ( parts ) > 2 or len ( parts ) = = 0
msg = ( 'Invalid source selector value "{}". Sources must be of the ' 'form `${{... |
def list2dict ( list_of_options ) :
"""Transforms a list of 2 element tuples to a dictionary""" | d = { }
for key , value in list_of_options :
d [ key ] = value
return d |
def accept ( self ) :
"""Launch the multi exposure analysis .""" | if not isinstance ( self . _multi_exposure_if , MultiExposureImpactFunction ) : # This should not happen as the " accept " button must be disabled if
# the impact function is not ready .
return ANALYSIS_FAILED_BAD_CODE , None
self . tab_widget . setCurrentIndex ( 2 )
self . set_enabled_buttons ( False )
enable_busy... |
def _tzstr ( self , sep = ":" ) :
"""Return formatted timezone offset ( + xx : xx ) or None .""" | off = self . utcoffset ( )
if off is not None :
if off . days < 0 :
sign = "-"
off = - off
else :
sign = "+"
hh , mm = divmod ( off , timedelta ( hours = 1 ) )
assert not mm % timedelta ( minutes = 1 ) , "whole minute"
mm //= timedelta ( minutes = 1 )
assert 0 <= hh < 24
... |
def send_cmd ( cmd , args , ret ) :
"""Collect and send analytics for CLI command .
Args :
args ( list ) : parsed args for the CLI command .
ret ( int ) : return value of the CLI command .""" | from dvc . daemon import daemon
if not Analytics . _is_enabled ( cmd ) :
return
analytics = Analytics ( )
analytics . collect_cmd ( args , ret )
daemon ( [ "analytics" , analytics . dump ( ) ] ) |
def bitpos ( self , key , bit , start = None , end = None ) :
"""Find first bit set or clear in a string .
: raises ValueError : if bit is not 0 or 1""" | if bit not in ( 1 , 0 ) :
raise ValueError ( "bit argument must be either 1 or 0" )
bytes_range = [ ]
if start is not None :
bytes_range . append ( start )
if end is not None :
if start is None :
bytes_range = [ 0 , end ]
else :
bytes_range . append ( end )
return self . execute ( b'BITP... |
def ascii2h5 ( bh_dir = None ) :
"""Convert the Burstein & Heiles ( 1982 ) dust map from ASCII to HDF5.""" | if bh_dir is None :
bh_dir = os . path . join ( data_dir_default , 'bh' )
fname = os . path . join ( bh_dir , '{}.ascii' )
f = h5py . File ( 'bh.h5' , 'w' )
for region in ( 'hinorth' , 'hisouth' ) :
data = np . loadtxt ( fname . format ( region ) , dtype = 'f4' )
# Reshape and clip
data . shape = ( 210 ... |
def equals ( df1 , df2 , ignore_order = set ( ) , ignore_indices = set ( ) , all_close = False , _return_reason = False ) :
'''Get whether 2 data frames are equal .
` ` NaN ` ` is considered equal to ` ` NaN ` ` and ` None ` .
Parameters
df1 : ~ pandas . DataFrame
Data frame to compare .
df2 : ~ pandas . ... | result = _equals ( df1 , df2 , ignore_order , ignore_indices , all_close )
if _return_reason :
return result
else :
return result [ 0 ] |
def get_cache_context ( self ) :
'''Retrieve a context cache from disk''' | with salt . utils . files . fopen ( self . cache_path , 'rb' ) as cache :
return salt . utils . data . decode ( self . serial . load ( cache ) ) |
def check_error ( res , error_enum ) :
"""Raise if the result has an error , otherwise return the result .""" | if res . HasField ( "error" ) :
enum_name = error_enum . DESCRIPTOR . full_name
error_name = error_enum . Name ( res . error )
details = getattr ( res , "error_details" , "<none>" )
raise RequestError ( "%s.%s: '%s'" % ( enum_name , error_name , details ) , res )
return res |
def get_changes ( self , factory_name , global_factory = False , resources = None , task_handle = taskhandle . NullTaskHandle ( ) ) :
"""Get the changes this refactoring makes
` factory _ name ` indicates the name of the factory function to
be added . If ` global _ factory ` is ` True ` the factory will be
gl... | if resources is None :
resources = self . project . get_python_files ( )
changes = ChangeSet ( 'Introduce factory method <%s>' % factory_name )
job_set = task_handle . create_jobset ( 'Collecting Changes' , len ( resources ) )
self . _change_module ( resources , changes , factory_name , global_factory , job_set )
r... |
def map_values2 ( self , func ) :
""": param func :
: type func : ( K , T ) - > U
: rtype : TDict [ U ]
Usage :
> > > TDict ( k1 = 1 , k2 = 2 , k3 = 3 ) . map _ values2 ( lambda k , v : f ' { k } - > { v * 2 } ' ) = = {
. . . " k1 " : " k1 - > 2 " ,
. . . " k2 " : " k2 - > 4 " ,
. . . " k3 " : " k3 - ... | return TDict ( { k : func ( k , v ) for k , v in self . items ( ) } ) |
def _parse_eval_args ( self , * args , ** kwargs ) :
"""NAME :
_ parse _ eval _ args
PURPOSE :
Internal function to parse the arguments given for an action / frequency / angle evaluation
INPUT :
OUTPUT :
HISTORY :
2010-07-11 - Written - Bovy ( NYU )""" | if len ( args ) == 3 : # R , vR . vT
R , vR , vT = args
self . _eval_R = R
self . _eval_vR = vR
self . _eval_vT = vT
self . _eval_z = 0.
self . _eval_vz = 0.
elif len ( args ) == 5 : # R , vR . vT , z , vz
R , vR , vT , z , vz = args
self . _eval_R = R
self . _eval_vR = vR
self .... |
def print ( self , tag = None , name = None ) :
"""Prints each tuple to stdout flushing after each tuple .
If ` tag ` is not ` None ` then each tuple has " tag : " prepended
to it before printing .
Args :
tag : A tag to prepend to each tuple .
name ( str ) : Name of the resulting stream .
When ` None ` ... | _name = name
if _name is None :
_name = 'print'
fn = streamsx . topology . functions . print_flush
if tag is not None :
tag = str ( tag ) + ': '
fn = lambda v : streamsx . topology . functions . print_flush ( tag + str ( v ) )
sp = self . for_each ( fn , name = _name )
sp . _op ( ) . sl = _SourceLocation ( ... |
def allocate ( self ) :
"""Returns an efficient portfolio allocation for the given risk index .""" | df = self . manager . get_historic_data ( ) [ self . SUPPORTED_COINS ]
# = = = = Calculate the daily changes = = = = #
change_columns = [ ]
for column in df :
if column in self . SUPPORTED_COINS :
change_column = '{}_change' . format ( column )
values = pd . Series ( ( df [ column ] . shift ( - 1 ) ... |
def attributes ( self , * args , ** kwargs ) :
"""Add one or more attributes to the : class : ` xml4h . nodes . Element ` node
represented by this Builder .
: return : the current Builder .
Delegates to : meth : ` xml4h . nodes . Element . set _ attributes ` .""" | self . _element . set_attributes ( * args , ** kwargs )
return self |
def get_named_type ( type_ ) : # noqa : F811
"""Unwrap possible wrapping type""" | if type_ :
unwrapped_type = type_
while is_wrapping_type ( unwrapped_type ) :
unwrapped_type = cast ( GraphQLWrappingType , unwrapped_type )
unwrapped_type = unwrapped_type . of_type
return cast ( GraphQLNamedType , unwrapped_type )
return None |
def get_links ( self , request = None ) :
"""Return a dictionary containing all the links that should be
included in the API schema .""" | links = LinkNode ( )
# Generate ( path , method , view ) given ( path , method , callback ) .
paths = [ ]
view_endpoints = [ ]
for path , method , callback in self . endpoints :
view = self . create_view ( callback , method , request )
if getattr ( view , 'exclude_from_schema' , False ) :
continue
p... |
def _request_raw_content ( self , url , timeout ) :
"""Send the request to get raw content .""" | request = Request ( url )
if self . referer is not None :
request . add_header ( 'Referer' , self . referer )
raw_xml = self . _call_geocoder ( request , timeout = timeout , deserializer = None )
return raw_xml |
def findall ( self , title = None ) :
"""Return a list of worksheets with the given title .
Args :
title ( str ) : title / name of the worksheets to return , or ` ` None ` ` for all
Returns :
list : list of contained worksheet instances ( possibly empty )""" | if title is None :
return list ( self . _sheets )
if title not in self . _titles :
return [ ]
return list ( self . _titles [ title ] ) |
def active_brokers ( self ) :
"""Return set of brokers that are not inactive or decommissioned .""" | return { broker for broker in self . _brokers if not broker . inactive and not broker . decommissioned } |
def _convert_snapshots ( topo_dir ) :
"""Convert 1 . x snapshot to the new format""" | old_snapshots_dir = os . path . join ( topo_dir , "project-files" , "snapshots" )
if os . path . exists ( old_snapshots_dir ) :
new_snapshots_dir = os . path . join ( topo_dir , "snapshots" )
os . makedirs ( new_snapshots_dir )
for snapshot in os . listdir ( old_snapshots_dir ) :
snapshot_dir = os .... |
def check_tx_ok ( result ) :
"""Checks if function : meth : ` UcanServer . write _ can _ msg ` successfully wrote CAN message ( s ) .
While using : meth : ` UcanServer . write _ can _ msg _ ex ` the number of sent CAN messages can be less than
the number of CAN messages which should be sent .
: param ReturnCo... | return ( result . value == ReturnCode . SUCCESSFUL ) or ( result . value > ReturnCode . WARNING ) |
def _load_dataset ( self , images , labels , emotion_index_map ) :
"""Loads Dataset object with images , labels , and other data .
: param images : numpy array of image data
: param labels : numpy array of one - hot vector labels
: param emotion _ index _ map : map linking string / integer emotion class to in... | train_images , test_images , train_labels , test_labels = train_test_split ( images , labels , test_size = self . validation_split , random_state = 42 , stratify = labels )
dataset = Dataset ( train_images , test_images , train_labels , test_labels , emotion_index_map , self . time_delay )
return dataset |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.