signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def from_dynacRepr ( cls , pynacRepr ) :
"""Construct a ` ` CavityAnalytic ` ` instance from the Pynac lattice element""" | cavID = int ( pynacRepr [ 1 ] [ 0 ] [ 0 ] )
xesln = float ( pynacRepr [ 1 ] [ 1 ] [ 0 ] )
phase = float ( pynacRepr [ 1 ] [ 1 ] [ 1 ] )
fieldReduction = float ( pynacRepr [ 1 ] [ 1 ] [ 2 ] )
isec = int ( pynacRepr [ 1 ] [ 1 ] [ 3 ] )
return cls ( phase , fieldReduction , cavID , xesln , isec ) |
def length ( self , rows = None ) :
"""Tensor holding the current length of episodes .
Args :
rows : Episodes to select length from , defaults to all .
Returns :
Batch tensor of sequence lengths .""" | rows = tf . range ( self . _capacity ) if rows is None else rows
return tf . gather ( self . _length , rows ) |
def create_partition ( self , partition_spec , if_not_exists = False , async_ = False , ** kw ) :
"""Create a partition within the table .
: param partition _ spec : specification of the partition .
: param if _ not _ exists :
: param async _ :
: return : partition object
: rtype : odps . models . partiti... | async_ = kw . get ( 'async' , async_ )
return self . partitions . create ( partition_spec , if_not_exists = if_not_exists , async_ = async_ ) |
def reset ( db , aid , episode ) :
"""Reset episode count for anime .""" | params = { 'aid' : aid , 'type' : get_eptype ( db , 'regular' ) . id , 'watched' : 1 , 'number' : episode , }
with db :
cur = db . cursor ( )
cur . execute ( """UPDATE episode SET user_watched=:watched
WHERE aid=:aid AND type=:type AND number<=:number""" , params )
params [ 'watched' ] = 0
c... |
def edge_by_target ( self ) :
"""Returns a reference to the dict of target node id to ( edge _ id , edge )""" | if self . _edge_by_target is None :
self . _edge_by_target = reverse_edge_by_source_dict ( self . _edge_by_source_id , self . _nexson_tree [ '^ot:rootNodeId' ] )
return self . _edge_by_target |
def arrays ( self ) :
"""Return an iterator over ( name , value ) pairs for arrays only .
Examples
> > > import zarr
> > > g1 = zarr . group ( )
> > > g2 = g1 . create _ group ( ' foo ' )
> > > g3 = g1 . create _ group ( ' bar ' )
> > > d1 = g1 . create _ dataset ( ' baz ' , shape = 100 , chunks = 10)
... | for key in sorted ( listdir ( self . _store , self . _path ) ) :
path = self . _key_prefix + key
if contains_array ( self . _store , path ) :
yield key , Array ( self . _store , path = path , read_only = self . _read_only , chunk_store = self . _chunk_store , cache_attrs = self . attrs . cache , synchro... |
def value_parameters ( self ) :
"""Parameters of policy""" | return it . chain ( self . value_backbone . parameters ( ) , self . critic_head . parameters ( ) ) |
def parseData ( self , data , host , port , options ) :
'''This function will parse the raw syslog data , dynamically create the
topic according to the topic specified by the user ( if specified ) and
decide whether to send the syslog data as an event on the master bus ,
based on the constraints given by the ... | data = self . obj . parse ( data )
data [ 'hostip' ] = host
log . debug ( 'Junos Syslog - received %s from %s, sent from port %s' , data , host , port )
send_this_event = True
for key in options :
if key in data :
if isinstance ( options [ key ] , ( six . string_types , int ) ) :
if six . text_t... |
def bdplotter ( task , ** kwargs ) :
'''bdplotter is based on the fact that phonon DOS / bands and
electron DOS / bands are the objects of the same kind .
1 ) DOS is formatted precomputed / smeared according to a normal distribution
2 ) bands are formatted precomputed / interpolated through natural cubic spli... | if task == 'bands' : # CRYSTAL , " VASP " , EXCITING
results = [ ]
if 'precomputed' in kwargs :
for n in range ( len ( kwargs [ 'precomputed' ] [ 'ticks' ] ) ) :
if kwargs [ 'precomputed' ] [ 'ticks' ] [ n ] [ 1 ] == 'GAMMA' :
kwargs [ 'precomputed' ] [ 'ticks' ] [ n ] [ 1 ] ... |
def render_to_string ( self , * args , ** kwargs ) :
"""Load and render a template into a unicode string .""" | try :
template_name , args = args [ 0 ] , args [ 1 : ]
except IndexError :
raise TypeError ( 'name of template required' )
return self . get_template ( template_name ) . render ( * args , ** kwargs ) |
def exportTree ( self , tree , filename ) :
"""Exports the inputed tree object to the given excel file .
: param tree | < QTreeWidget >
filename | < str >
: return < bool >""" | book = xlwt . Workbook ( )
# determine the title for the sheet to export
title = nativestring ( tree . windowTitle ( ) )
if not title :
title = nativestring ( tree . objectName ( ) )
if not title :
title = 'Sheet 1'
sheet = book . add_sheet ( title )
# determine visible columns to export
cols = [ c for c in ran... |
def new_message_from_header ( header ) :
"""Given an OF Header , return an empty message of header ' s message _ type .
Args :
header ( ~ pyof . v0x01 . common . header . Header ) : Unpacked OpenFlow Header .
Returns :
Empty OpenFlow message of the same type of message _ type attribute from
the given head... | message_type = header . message_type
if not isinstance ( message_type , Type ) :
try :
if isinstance ( message_type , str ) :
message_type = Type [ message_type ]
elif isinstance ( message_type , int ) :
message_type = Type ( message_type )
except ValueError :
rai... |
def containsParamSubset ( self , params ) :
"""Test whether this element contains at least all ` params ` , or more .
Args :
params ( dict / SpecialDict ) : Subset of parameters .
Returns :
bool : True if all ` params ` are contained in this element .""" | for key in params . keys ( ) :
if key not in self . params :
return False
if params [ key ] != self . params [ key ] :
return False
return True |
def _create_rubber_bands_action ( self ) :
"""Create action for toggling rubber bands .""" | icon = resources_path ( 'img' , 'icons' , 'toggle-rubber-bands.svg' )
self . action_toggle_rubberbands = QAction ( QIcon ( icon ) , self . tr ( 'Toggle Scenario Outlines' ) , self . iface . mainWindow ( ) )
message = self . tr ( 'Toggle rubber bands showing scenario extents.' )
self . action_toggle_rubberbands . setSta... |
def RootGroup ( self ) :
"""Returns group object for datacenter root group .
> > > clc . v2 . Datacenter ( ) . RootGroup ( )
< clc . APIv2 . group . Group object at 0x105feacd0 >
> > > print _
WA1 Hardware""" | return ( clc . v2 . Group ( id = self . root_group_id , alias = self . alias , session = self . session ) ) |
def trigger ( self , event_name , * args , ** kwargs ) :
"""Trigger an event on this context .
Params :
event _ name ( string ) :
Event name to trigger
Args and kwargs are passed to each handler - see the bubbler . Event class
for more information .
Returns :
bubbler . Event :
Event instance after e... | ev = Event ( event_name , self )
ev . trigger ( * args , ** kwargs )
return ev |
def profile_list ( list_names = False , remote_addr = None , cert = None , key = None , verify_cert = True ) :
'''Lists all profiles from the LXD .
list _ names :
Return a list of names instead of full blown dicts .
remote _ addr :
An URL to a remote Server , you also have to give cert and key if
you prov... | client = pylxd_client_get ( remote_addr , cert , key , verify_cert )
profiles = client . profiles . all ( )
if list_names :
return [ p . name for p in profiles ]
return map ( _pylxd_model_to_dict , profiles ) |
def get_block_info ( self ) :
"""Get the retrieved block information .
Return [ ( height , [ txs ] ) ] on success , ordered on height
Raise if not finished downloading""" | if not self . finished :
raise Exception ( "Not finished downloading" )
ret = [ ]
for ( block_hash , block_data ) in self . block_info . items ( ) :
ret . append ( ( block_data [ 'height' ] , block_data [ 'txns' ] ) )
return ret |
def get_parser ( ) :
"""Return a parser for the command - line arguments .""" | parser = argparse . ArgumentParser ( add_help = False , description = 'Analysis of your architecture strength based on DSM data' )
parser . add_argument ( '-c' , '--config' , action = 'store' , type = valid_file , dest = 'config_file' , metavar = 'FILE' , help = 'Configuration file to use.' )
parser . add_argument ( '-... |
def _constraint_names ( self , model , column_names = None , unique = None , primary_key = None , index = None , foreign_key = None , check = None ) :
"""Returns all constraint names matching the columns and conditions""" | column_names = list ( column_names ) if column_names else None
with self . connection . cursor ( ) as cursor :
constraints = get_constraints ( cursor , model . _meta . db_table )
result = [ ]
for name , infodict in constraints . items ( ) :
if column_names is None or column_names == infodict [ 'columns' ] :
... |
def parse ( self , resource ) :
"""Parse a list of directories and reads it into a collection
: param resource : List of folders
: return : An inventory resource and a list of CtsTextMetadata metadata - objects""" | textgroups = [ ]
texts = [ ]
invalids = [ ]
for folder in resource :
cts_files = glob ( "{base_folder}/data/*/__cts__.xml" . format ( base_folder = folder ) )
for cts_file in cts_files :
textgroup , cts_file = self . _parse_textgroup ( cts_file )
textgroups . append ( ( textgroup , cts_file ) )
... |
def stackscript_create ( self , label , script , images , desc = None , public = False , ** kwargs ) :
"""Creates a new : any : ` StackScript ` on your account .
: param label : The label for this StackScript .
: type label : str
: param script : The script to run when an : any : ` Instance ` is deployed with... | image_list = None
if type ( images ) is list or type ( images ) is PaginatedList :
image_list = [ d . id if issubclass ( type ( d ) , Base ) else d for d in images ]
elif type ( images ) is Image :
image_list = [ images . id ]
elif type ( images ) is str :
image_list = [ images ]
else :
raise ValueError... |
def _executemany ( self , cursor , query , parameters ) :
"""The function is mostly useful for commands that update the database :
any result set returned by the query is discarded .""" | try :
self . _log ( query )
cursor . executemany ( query , parameters )
except OperationalError as e : # pragma : no cover
logging . error ( 'Error connecting to PostgreSQL on %s, e' , self . host , e )
self . close ( )
raise |
def auth_list ( ** kwargs ) :
"""Shows available authorization groups .""" | ctx = Context ( ** kwargs )
ctx . execute_action ( 'auth:group:list' , ** { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , } ) |
def multi_ops ( data_stream , * funcs ) :
"""fork a generator with multiple operations / functions
data _ stream - an iterable data structure ( ie : list / generator / tuple )
funcs - every function that will be applied to the data _ stream""" | assert all ( callable ( func ) for func in funcs ) , 'multi_ops can only apply functions to the first argument'
assert len ( funcs ) , 'multi_ops needs at least one function to apply to data_stream'
for i in data_stream :
if len ( funcs ) > 1 :
yield tuple ( func ( i ) for func in funcs )
elif len ( fun... |
def add_validator ( validator , base_tag , tag = None ) :
"""Add a validator for the given tag , which defines a subset of base _ tag .
If tag is None , it is automatically constructed as
u ' ! ~ ' + validator . _ _ name _ _
Validator is a function that accepts a document node ( in the form of a
Python obje... | if not tag :
tag = u'!~' + validator . __name__
for xid , opts in _VALIDATOR_MODES . iteritems ( ) :
mtag = "%s%s" % ( tag , xid )
yaml . add_constructor ( mtag , ContructorValidatorNode ( mtag , base_tag , validator , opts [ 'name' ] , opts [ 'min' ] , opts [ 'max' ] ) ) |
def now ( cls , tzinfo = None ) :
"""[ tz ] - > new datetime with tz ' s local day and time .""" | obj = cls . utcnow ( )
if tzinfo is None :
tzinfo = localtz ( )
return obj . astimezone ( tzinfo ) |
def make_app ( config = None ) :
"""Factory function that creates a new ` CoolmagicApplication `
object . Optional WSGI middlewares should be applied here .""" | config = config or { }
app = CoolMagicApplication ( config )
# static stuff
app = SharedDataMiddleware ( app , { "/public" : path . join ( path . dirname ( __file__ ) , "public" ) } )
# clean up locals
app = local_manager . make_middleware ( app )
return app |
def _get_ontology ( ontology ) :
"""Return the ( name , path , url ) to the short ontology name .
: param ontology : path to the file or url .""" | onto_name = onto_path = onto_url = None
# first assume we got the path to the file
if os . path . exists ( ontology ) :
onto_name = os . path . split ( os . path . abspath ( ontology ) ) [ 1 ]
onto_path = os . path . abspath ( ontology )
onto_url = ""
else : # if not , try to find it in a known locations
... |
def within_ipv4_network ( self , field , values ) :
"""This filter adds specified networks to a filter to check
for inclusion .
: param str field : name of field to filter on . Taken from ' Show Filter
Expression ' within SMC .
: param list values : network definitions , in cidr format , i . e : 1.1.1.0/24.... | v = [ 'ipv4_net("%s")' % net for net in values ]
self . update_filter ( '{} IN union({})' . format ( field , ',' . join ( v ) ) ) |
def usearch61_chimera_check_denovo ( abundance_fp , uchime_denovo_fp , minlen = 64 , output_dir = "." , remove_usearch_logs = False , uchime_denovo_log_fp = "uchime_denovo.log" , usearch61_minh = 0.28 , usearch61_xn = 8.0 , usearch61_dn = 1.4 , usearch61_mindiffs = 3 , usearch61_mindiv = 0.8 , usearch61_abundance_skew ... | params = { '--minseqlength' : minlen , '--uchime_denovo' : abundance_fp , '--uchimeout' : uchime_denovo_fp , '--minh' : usearch61_minh , '--xn' : usearch61_xn , '--dn' : usearch61_dn , '--mindiffs' : usearch61_mindiffs , '--mindiv' : usearch61_mindiv , '--abskew' : usearch61_abundance_skew }
if not remove_usearch_logs ... |
def remove ( path , chmod = False ) :
"""Remove a file or directory located on the filesystem at path .
If chmod is True , chmod - R 755 is executed on the path
before rm - rf path is called .
Parameters
path : str
file system path to an existing file or directory
chmod : bool
If True , chmod - R 755 ... | if not os . path . exists ( path ) :
return
if chmod :
cmd = "chmod -R 755 %s" % path
subproc . call ( cmd )
cmd = 'rm -rf "{p}"' . format ( p = path )
subproc . call ( cmd ) |
def clear ( self , asset_manager_id ) :
"""This method deletes all the data for an asset _ manager _ id .
It should be used with extreme caution . In production it
is almost always better to Inactivate rather than delete .""" | self . logger . info ( 'Clear Assets - Asset Manager: %s' , asset_manager_id )
url = '%s/clear/%s' % ( self . endpoint , asset_manager_id )
response = self . session . delete ( url )
if response . ok :
count = response . json ( ) . get ( 'count' , 'Unknown' )
self . logger . info ( 'Deleted %s Assets.' , count ... |
def _get_popularity_baseline ( self ) :
"""Returns a new popularity model matching the data set this model was
trained with . Can be used for comparison purposes .""" | response = self . __proxy__ . get_popularity_baseline ( )
from . popularity_recommender import PopularityRecommender
return PopularityRecommender ( response ) |
def set_progress ( self , scan_id , progress ) :
"""Sets scan _ id scan ' s progress .""" | if progress > 0 and progress <= 100 :
self . scans_table [ scan_id ] [ 'progress' ] = progress
if progress == 100 :
self . scans_table [ scan_id ] [ 'end_time' ] = int ( time . time ( ) ) |
def build_result_metadata ( self , data = None , args = None ) :
"""collect metadata into this object
: param data : dict
: param args : build from args instead of data""" | data = data if data else self . _build_result_metainfo ( args )
if data . get ( "build_branch" ) :
self . build_branch = data . get ( "build_branch" )
if data . get ( "buildcommit" ) :
self . buildcommit = data . get ( "buildcommit" )
if data . get ( "build_git_url" ) :
self . build_git_url = data . get ( "... |
def parse_layout ( elems , font_stat , combine = False ) :
"""Parses pdf texts into a hypergraph grouped into rows
and columns and then output""" | boxes_segments = elems . segments
boxes_curves = elems . curves
boxes_figures = elems . figures
page_width = elems . layout . width
# page _ height = elems . layout . height
boxes = elems . mentions
avg_font_pts = get_most_common_font_pts ( elems . mentions , font_stat )
width = get_page_width ( boxes + boxes_segments ... |
def _suffix ( self ) :
"""Return appropriate suffix for alignment file""" | _output_formats = { 'GCG' : '.msf' , 'GDE' : '.gde' , 'PHYLIP' : '.phy' , 'PIR' : '.pir' , 'NEXUS' : '.nxs' }
if self . Parameters [ '-output' ] . isOn ( ) :
return _output_formats [ self . Parameters [ '-output' ] . Value ]
else :
return '.aln' |
def _process_response_xml ( self , response_xml ) :
'''Processa o xml de resposta e caso não existam erros retorna um
dicionario com o codigo e data .
: return : dictionary''' | result = { }
xml = ElementTree . fromstring ( response_xml )
if xml . tag == 'errors' :
logger . error ( u'Erro no pedido de pagamento ao PagSeguro.' + ' O xml de resposta foi: %s' % response_xml )
errors_message = u'Ocorreu algum problema com os dados do pagamento: '
for error in xml . findall ( 'error' ) ... |
def find_rings ( self , including = None ) :
"""Find ring structures in the MoleculeGraph .
: param including : list of site indices . If
including is not None , then find _ rings will
only return those rings including the specified
sites . By default , this parameter is None , and
all rings will be retur... | # Copies self . graph such that all edges ( u , v ) matched by edges ( v , u )
undirected = self . graph . to_undirected ( )
directed = undirected . to_directed ( )
cycles_nodes = [ ]
cycles_edges = [ ]
# Remove all two - edge cycles
all_cycles = [ c for c in nx . simple_cycles ( directed ) if len ( c ) > 2 ]
# Using t... |
def ping ( self ) :
"""Ping Redis Server and return Round - Trip - Time in seconds .
@ return : Round - trip - time in seconds as float .""" | start = time . time ( )
self . _conn . ping ( )
return ( time . time ( ) - start ) |
def put ( self , key , value ) :
"""Puts a new value into map element specified by its key .
The key can be defined using dot notation
and allows to recursively access elements of elements .
: param key : a key of the element to put .
: param value : a new value for map element .""" | if key == None or key == '' :
return None
elif key . find ( '.' ) > 0 :
RecursiveObjectWriter . set_property ( self , key , value )
return value
else :
self [ key ] = value
return value |
def unpack_grad_tuple ( gv , gpt ) :
"""Unpack a previously packed collection of gradient tensors .
Args :
gv : A ( grad , var ) pair to be unpacked .
gpt : A GradPackTuple describing the packing operation that produced gv .
Returns :
A list of ( grad , var ) pairs corresponding to the values that were
... | elt_widths = [ x . num_elements ( ) for x in gpt . shapes ]
with tf . device ( gv [ 0 ] [ 0 ] . device ) :
with tf . name_scope ( "unpack" ) :
splits = tf . split ( gv [ 0 ] , elt_widths )
unpacked_gv = [ ]
for idx , s in enumerate ( splits ) :
unpacked_gv . append ( ( tf . resha... |
def underline ( self , msg ) :
"""Underline the input""" | return click . style ( msg , underline = True ) if self . colorize else msg |
def sparql_post ( self , owner , id , query , ** kwargs ) :
"""SPARQL query
This endpoint executes SPARQL queries against a dataset or data project . SPARQL results are available in a variety of formats . By default , ` application / sparql - results + json ` will be returned . Set the ` Accept ` header to one of... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . sparql_post_with_http_info ( owner , id , query , ** kwargs )
else :
( data ) = self . sparql_post_with_http_info ( owner , id , query , ** kwargs )
return data |
def bench_dot ( lhs_row_dim , lhs_col_dim , rhs_col_dim , density , rhs_density , dot_func , trans_lhs , lhs_stype , rhs_stype , only_storage , distribution = "uniform" ) :
"""Benchmarking both storage and dot""" | lhs_nd = rand_ndarray ( ( lhs_row_dim , lhs_col_dim ) , lhs_stype , density , distribution = distribution )
if not only_storage :
rhs_nd = rand_ndarray ( ( lhs_col_dim , rhs_col_dim ) , rhs_stype , density = rhs_density , distribution = distribution )
out = dot_func ( lhs_nd , rhs_nd , trans_lhs )
mx . nd . wai... |
def restart ( name ) :
'''Restart the named service
CLI Example :
. . code - block : : bash
salt ' * ' service . restart < service name >''' | cmd = '/usr/sbin/svcadm restart {0}' . format ( name )
if not __salt__ [ 'cmd.retcode' ] ( cmd , python_shell = False ) : # calling restart doesn ' t clear maintenance
# or tell us that the service is in the ' online ' state
return start ( name )
return False |
def create ( self , repo_name , scm = 'git' , private = True , ** kwargs ) :
"""Creates a new repository on own Bitbucket account and return it .""" | url = self . bitbucket . url ( 'CREATE_REPO' )
return self . bitbucket . dispatch ( 'POST' , url , auth = self . bitbucket . auth , name = repo_name , scm = scm , is_private = private , ** kwargs ) |
def run ( self , context ) :
"""We have to overwrite this method because we don ' t want an implicit context""" | args = [ ]
kwargs = { }
for arg in self . explicit_arguments :
if arg . name is not None :
kwargs [ arg . name ] = arg . value
else :
args . append ( arg . value )
for arg in self . implicit_arguments :
if arg . name is not None :
annotation = self . signature . parameters [ arg . na... |
def _pad_string ( self , str , colwidth ) :
"""Center - pads a string to the given column width using spaces .""" | width = self . _disp_width ( str )
prefix = ( colwidth - 1 - width ) // 2
suffix = colwidth - prefix - width
return ' ' * prefix + str + ' ' * suffix |
def load ( self , username ) :
""": param username :
: type username :
: return :
: rtype :""" | config_dir = StorageTools . getStorageForPhone ( username )
logger . debug ( "Detecting config for username=%s, dir=%s" % ( username , config_dir ) )
exhausted = [ ]
for ftype in self . MAP_EXT :
if len ( ftype ) :
fname = ( self . NAME_FILE_CONFIG + "." + ftype )
else :
fname = self . NAME_FILE... |
def _bss_image_crit ( s_true , e_spat , e_interf , e_artif ) :
"""Measurement of the separation quality for a given image in terms of
filtered true source , spatial error , interference and artifacts .""" | # energy ratios
sdr = _safe_db ( np . sum ( s_true ** 2 ) , np . sum ( ( e_spat + e_interf + e_artif ) ** 2 ) )
isr = _safe_db ( np . sum ( s_true ** 2 ) , np . sum ( e_spat ** 2 ) )
sir = _safe_db ( np . sum ( ( s_true + e_spat ) ** 2 ) , np . sum ( e_interf ** 2 ) )
sar = _safe_db ( np . sum ( ( s_true + e_spat + e_i... |
def _get_unscheduled_routers ( self , plugin , context ) :
"""Get routers with no agent binding .""" | if NEUTRON_VERSION . version [ 0 ] <= NEUTRON_NEWTON_VERSION . version [ 0 ] :
context , plugin = plugin , context
# TODO ( gongysh ) consider the disabled agent ' s router
no_agent_binding = ~ sql . exists ( ) . where ( bc . Router . id == bc . rb_model . RouterL3AgentBinding . router_id )
# Modified to only inclu... |
def _add_monitor ( monitors , handle , callback , devices , events ) :
"""Add the given monitor to the listed devices and events .""" | for conn_string in devices :
data = monitors . get ( conn_string )
if data is None :
data = dict ( )
monitors [ conn_string ] = data
for event in events :
event_dict = data . get ( event )
if event_dict is None :
event_dict = dict ( )
data [ event ] = ... |
def _repopulate_pool ( self ) :
"""Bring the number of pool processes up to the specified number ,
for use after reaping workers which have exited .""" | for i in range ( self . _processes - len ( self . _pool ) ) :
w = self . Process ( target = self . _worker_f , args = ( self . _inqueue , self . _outqueue , self . _initializer , self . _initargs , self . _maxtasksperchild ) )
self . _pool . append ( w )
w . name = w . name . replace ( 'Process' , 'PoolWork... |
def file_md5 ( self , resource ) :
"""Deprecated alias for * resource _ md5 * .""" | warnings . warn ( "file_md5 is deprecated; use resource_md5 instead" , DeprecationWarning , stacklevel = 2 )
return self . resource_md5 ( resource ) |
def read_csv ( filename : Union [ PathLike , Iterator [ str ] ] , delimiter : Optional [ str ] = ',' , first_column_names : Optional [ bool ] = None , dtype : str = 'float32' , ) -> AnnData :
"""Read ` ` . csv ` ` file .
Same as : func : ` ~ anndata . read _ text ` but with default delimiter ` ` ' , ' ` ` .
Par... | return read_text ( filename , delimiter , first_column_names , dtype ) |
def get_d1_env_by_base_url ( cn_base_url ) :
"""Given the BaseURL for a CN , return the DataONE environment dict for the CN ' s
environemnt .""" | for k , v in D1_ENV_DICT :
if v [ 'base_url' ] . startswith ( cn_base_url ) :
return D1_ENV_DICT [ k ] |
def return_socket ( self , sock_info ) :
"""Return the socket to the pool , or if it ' s closed discard it .""" | if self . pid != os . getpid ( ) :
self . reset ( )
else :
if sock_info . pool_id != self . pool_id :
sock_info . close ( )
elif not sock_info . closed :
sock_info . update_last_checkin_time ( )
with self . lock :
self . sockets . appendleft ( sock_info )
self . _socket_s... |
def build_path ( self , source , path_patterns = None , strict = False , domains = None ) :
'''Constructs a target filename for a file or dictionary of entities .
Args :
source ( str , File , dict ) : The source data to use to construct the
new file path . Must be one of :
- A File object
- A string givin... | if isinstance ( source , six . string_types ) :
if source not in self . files :
source = join ( self . root , source )
source = self . get_file ( source )
if isinstance ( source , File ) :
source = source . entities
if path_patterns is None :
if domains is None :
domains = list ( self . ... |
def element_type ( self ) :
"""Retrieve the Type of elements within this Type .
If accessed on a type that is not an array , complex , or vector type , an
exception will be raised .""" | result = conf . lib . clang_getElementType ( self )
if result . kind == TypeKind . INVALID :
raise Exception ( 'Element type not available on this type.' )
return result |
def add_regional_client ( self , region_name ) :
"""Adds a regional client for the specified region if it does not already exist .
: param str region _ name : AWS Region ID ( ex : us - east - 1)""" | if region_name not in self . _regional_clients :
session = boto3 . session . Session ( region_name = region_name , botocore_session = self . config . botocore_session )
client = session . client ( "kms" , config = self . _user_agent_adding_config )
self . _register_client ( client , region_name )
self .... |
def guess_sequence ( redeem_script ) :
'''str - > int
If OP _ CSV is used , guess an appropriate sequence
Otherwise , disable RBF , but leave lock _ time on .
Fails if there ' s not a constant before OP _ CSV''' | try :
script_array = redeem_script . split ( )
loc = script_array . index ( 'OP_CHECKSEQUENCEVERIFY' )
return int ( script_array [ loc - 1 ] , 16 )
except ValueError :
return 0xFFFFFFFE |
def print_fold ( column_to_fold , total_columns , skips ) :
"""Print a row that removes the given column and shifts all the following
columns .""" | format_str = '{:<2}' * ( total_columns - 1 )
cols = [ ]
for i in range ( column_to_fold ) : # print ( i )
if i in skips :
cols . append ( " " )
else :
cols . append ( "| " )
for i in range ( column_to_fold + 1 , total_columns ) : # print ( i )
if i in skips :
cols . append ( " " )
... |
def consume_vertices ( self ) :
"""Consumes all consecutive vertices .
NOTE : There is no guarantee this will consume all vertices since other
statements can also occur in the vertex list""" | while True : # Vertex color
if len ( self . values ) == 7 :
yield ( float ( self . values [ 1 ] ) , float ( self . values [ 2 ] ) , float ( self . values [ 3 ] ) , float ( self . values [ 4 ] ) , float ( self . values [ 5 ] ) , float ( self . values [ 6 ] ) , )
# Positions only
else :
yield ... |
def call ( fun , ** kwargs ) :
'''Directly call a function inside a loader directory''' | args = kwargs . get ( 'args' , [ ] )
dirs = kwargs . get ( 'dirs' , [ ] )
funcs = LazyLoader ( [ os . path . join ( SALT_BASE_PATH , 'modules' ) ] + dirs , None , tag = 'modules' , virtual_enable = False , )
return funcs [ fun ] ( * args ) |
def build_parser ( ) :
"Build an argparse argument parser to parse the command line ." | parser = argparse . ArgumentParser ( description = """Coursera OAuth2 client CLI. This tool
helps users of the Coursera App Platform to programmatically access
Coursera APIs.""" , epilog = """Please file bugs on github at:
https://github.com/coursera/courseraoauth2client/issues. If you
w... |
def log_url ( self , url_data ) :
"""Write url checking info .""" | self . writeln ( )
if self . has_part ( 'url' ) :
self . write_url ( url_data )
if url_data . name and self . has_part ( 'name' ) :
self . write_name ( url_data )
if url_data . parent_url and self . has_part ( 'parenturl' ) :
self . write_parent ( url_data )
if url_data . base_ref and self . has_part ( 'bas... |
def get_set_voltage ( self , channel ) :
"""channel : 1 = OP1 , 2 = OP2 , AUX is not supported""" | ret = self . ask ( "V%d?" % channel )
if ret [ : 3 ] != "V%d " % channel :
print ( "ttiQl355tp.get_voltage() format error" , ret )
return None
return float ( ret [ 3 : ] ) |
def refactor_tree ( self , tree , name ) :
"""Refactors a parse tree ( modifying the tree in place ) .
For compatible patterns the bottom matcher module is
used . Otherwise the tree is traversed node - to - node for
matches .
Args :
tree : a pytree . Node instance representing the root of the tree
to be... | for fixer in chain ( self . pre_order , self . post_order ) :
fixer . start_tree ( tree , name )
# use traditional matching for the incompatible fixers
self . traverse_by ( self . bmi_pre_order_heads , tree . pre_order ( ) )
self . traverse_by ( self . bmi_post_order_heads , tree . post_order ( ) )
# obtain a set o... |
def cancel ( self , function ) :
"""Cancel the scheduled ` function ` calls .""" | if function in self . _callback . keys ( ) :
callback_id = self . _callback [ function ] [ 0 ]
self . tk . after_cancel ( callback_id )
self . _callback . pop ( function )
else :
utils . error_format ( "Could not cancel function - it doesnt exist, it may have already run" ) |
def cart_to_zmat ( self , coordinates ) :
"""Convert cartesian coordinates to ZMatrix format
Argument :
coordinates - - Cartesian coordinates ( numpy array Nx3)
The coordinates must match with the graph that was used to initialize
the ZMatrixGenerator object .""" | N = len ( self . graph . numbers )
if coordinates . shape != ( N , 3 ) :
raise ValueError ( "The shape of the coordinates must be (%i, 3)" % N )
result = np . zeros ( N , dtype = self . dtype )
for i in range ( N ) :
ref0 = self . old_index [ i ]
rel1 = - 1
rel2 = - 1
rel3 = - 1
distance = 0
... |
def parse_import_names ( sourcecode , top_level = True , fpath = None , branch = False ) :
"""Finds all function names in a file without importing it
Args :
sourcecode ( str ) :
Returns :
list : func _ names
CommandLine :
python - m utool . util _ inspect parse _ import _ names
References :
https : ... | import ast
import_names = [ ]
if six . PY2 :
import utool as ut
sourcecode = ut . ensure_unicode ( sourcecode )
encoded = sourcecode . encode ( 'utf8' )
pt = ast . parse ( encoded )
else :
pt = ast . parse ( sourcecode )
modules = [ ]
class ImportVisitor ( ast . NodeVisitor ) :
def _parse_alias_... |
def sigmoidal ( arr , contrast , bias ) :
r"""Sigmoidal contrast is type of contrast control that
adjusts the contrast without saturating highlights or shadows .
It allows control over two factors :
the contrast range from light to dark , and where the middle value
of the mid - tones falls . The result is a... | if ( arr . max ( ) > 1.0 + epsilon ) or ( arr . min ( ) < 0 - epsilon ) :
raise ValueError ( "Input array must have float values between 0 and 1" )
if ( bias > 1.0 + epsilon ) or ( bias < 0 - epsilon ) :
raise ValueError ( "bias must be a scalar float between 0 and 1" )
alpha , beta = bias , contrast
# We use t... |
def isEmpty ( self ) :
"""Check if rectangle area is empty .""" | return self . x0 == self . x1 or self . y0 == self . y1 |
def get_nullable_type ( type_ ) : # noqa : F811
"""Unwrap possible non - null type""" | if is_non_null_type ( type_ ) :
type_ = cast ( GraphQLNonNull , type_ )
type_ = type_ . of_type
return cast ( Optional [ GraphQLNullableType ] , type_ ) |
def configure ( self , address ) :
"""Configure socket ' s addresses with nanoconfig""" | global nanoconfig_started
if len ( self . _endpoints ) :
raise ValueError ( "Nanoconfig address must be sole endpoint" )
endpoint_id = _nn_check_positive_rtn ( wrapper . nc_configure ( self . fd , address ) )
if not nanoconfig_started :
nanoconfig_started = True
ep = Socket . NanoconfigEndpoint ( self , endpoin... |
def _set_mep ( self , v , load = False ) :
"""Setter method for mep , mapped from YANG variable / protocol / cfm / domain _ name / ma _ name / cfm _ ma _ sub _ commands / mep ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ mep is considered as a private
metho... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "mep_id" , mep . mep , yang_name = "mep" , rest_name = "mep" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'mep-id' , extensions = { u'tailf-co... |
def do_title ( s ) :
"""Return a titlecased version of the value . I . e . words will start with
uppercase letters , all remaining characters are lowercase .""" | return '' . join ( [ item [ 0 ] . upper ( ) + item [ 1 : ] . lower ( ) for item in _word_beginning_split_re . split ( soft_unicode ( s ) ) if item ] ) |
def _resolve_nodes_to_phenotypes ( id_list : List [ str ] ) -> List [ str ] :
"""Given a list of ids of unknown type , determine which ids
are phenotypes , if the id is not a phenotype , check to
see if it is associated with one or more phenotypes via
the ' has _ phenotype ' relation
: param id _ list : lis... | pheno_list = [ ]
node_types = get_id_type_map ( id_list )
for node in id_list :
if 'phenotype' in node_types [ node ] :
pheno_list . append ( node )
else :
phenotypes = get_objects_for_subject ( subject = node , object_category = 'phenotype' , relation = 'RO:0002200' )
pheno_list = pheno... |
def export ( self , output_folder ) :
"""Export matrices as ` ` * . npy ` ` files to an output folder .""" | if not os . path . exists ( output_folder ) :
os . makedirs ( output_folder )
self . _interact_with_folder ( output_folder , 'w' ) |
def p_expr_GE_expr ( p ) :
"""expr : expr GE expr""" | p [ 0 ] = make_binary ( p . lineno ( 2 ) , 'GE' , p [ 1 ] , p [ 3 ] , lambda x , y : x >= y ) |
def all_current_versions ( self ) : # type : ( ) - > Dict [ str , str ]
"""Track down all the versions & compile into one dictionary
: return :""" | if self . PROJECT is None :
raise TypeError ( "self.PROJECT missing, can't continue" )
versions = { }
# type : Dict [ str , str ]
files_to_check = [ x for x in self . file_inventory . source_files ]
files_to_check . append ( self . PROJECT + ".py" )
# is this the ' central ' module ?
for file in self . file_invento... |
def CreateCustomizerFeedItems ( client , adgroup_ids , ad_customizer_feed ) :
"""Creates FeedItems for the specified AdGroups .
These FeedItems contain values to use in ad customizations for the AdGroups .
Args :
client : an AdWordsClient instance .
adgroup _ ids : a list containing two AdGroup Ids .
ad _... | # Get the FeedItemService
feed_item_service = client . GetService ( 'FeedItemService' , 'v201809' )
now = datetime . now ( )
mars_date = datetime ( now . year , now . month , 1 , 0 , 0 )
venus_date = datetime ( now . year , now . month , 15 , 0 , 0 )
time_format = '%Y%m%d %H%M%S'
feed_item_operations = [ CreateFeedItem... |
def add ( self , opener ) :
"""Adds an opener to the registry
: param opener : Opener object
: type opener : Opener inherited object""" | index = len ( self . openers )
self . openers [ index ] = opener
for name in opener . names :
self . registry [ name ] = index |
def add_event ( cls , event , event_name = None ) :
"""Add events""" | # setattr ( cls , event _ name , event )
event_name = event_name or event . __name__
setattr ( cls , event_name , types . MethodType ( event , cls ) ) |
def _set_static_mac ( self , v , load = False ) :
"""Setter method for static _ mac , mapped from YANG variable / mac _ address _ table / static / static _ mac ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ static _ mac is considered as a private
method . Ba... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "mac_address forward interface_type interface_name vlan vlanid" , static_mac . static_mac , yang_name = "static-mac" , rest_name = "static-mac" , parent = self , is_container = 'list' , user_ordered = False , p... |
def dir ( self , methods = True , showall = True ) :
"""Show this object ' s attributes and methods .""" | import inspect
# print " [ attributes ] "
for k , v in sorted ( self . __dict__ . items ( ) ) :
if k . startswith ( "_" ) :
continue
print makeminlength ( "." + k , being . linelen ) , "\t" , v
if not methods :
return
entmethods = dir ( entity )
print
# print " [ methods ] "
for x in [ x for x in di... |
def make_folium_polyline ( edge , edge_color , edge_width , edge_opacity , popup_attribute = None ) :
"""Turn a row from the gdf _ edges GeoDataFrame into a folium PolyLine with
attributes .
Parameters
edge : GeoSeries
a row from the gdf _ edges GeoDataFrame
edge _ color : string
color of the edge lines... | # check if we were able to import folium successfully
if not folium :
raise ImportError ( 'The folium package must be installed to use this optional feature.' )
# locations is a list of points for the polyline
# folium takes coords in lat , lon but geopandas provides them in lon , lat
# so we have to flip them arou... |
def iter_all_children ( obj , skipContainers = False ) :
"""Returns an iterator over all childen and nested children using
obj ' s get _ children ( ) method
if skipContainers is true , only childless objects are returned .""" | if hasattr ( obj , 'get_children' ) and len ( obj . get_children ( ) ) > 0 :
for child in obj . get_children ( ) :
if not skipContainers :
yield child
# could use ` yield from ` in python 3 . . .
for grandchild in iter_all_children ( child , skipContainers ) :
yield g... |
def irr ( values , guess = None ) :
"""Function to calculate the internal rate of return ( IRR ) using payments and periodic dates . It resembles the
excel function IRR ( ) .
Excel reference : https : / / support . office . com / en - us / article / IRR - function - 64925eaa - 9988-495b - b290-3ad0c163c1bc
: ... | if isinstance ( values , Range ) :
values = values . values
if guess is not None and guess != 0 :
raise ValueError ( 'guess value for excellib.irr() is %s and not 0' % guess )
else :
try :
return np . irr ( values )
except Exception as e :
return ExcelError ( '#NUM!' , e ) |
def set_energy_range ( self , logemin , logemax ) :
"""Set the energy bounds of the analysis . This restricts the
evaluation of the likelihood to the data that falls in this
range . Input values will be rounded to the closest bin edge
value . If either argument is None then the lower or upper
bound of the a... | if logemin is None :
logemin = self . log_energies [ 0 ]
else :
imin = int ( utils . val_to_edge ( self . log_energies , logemin ) [ 0 ] )
logemin = self . log_energies [ imin ]
if logemax is None :
logemax = self . log_energies [ - 1 ]
else :
imax = int ( utils . val_to_edge ( self . log_energies ,... |
def parse ( self , xsl = 'text' ) :
"""TODO : add double - quoted string literals that allows for escaped double quotes
https : / / gist . github . com / prathe / 2439752 or
http : / / www . metaltoad . com / blog / regex - quoted - string - escapable - quotes""" | try :
cmd_text , option_text = xsl . split ( None , 1 )
except ValueError :
cmd_text = xsl
option_text = ''
try :
context , cmd = cmd_text . strip ( ) . lower ( ) . split ( ':' , 1 )
except ValueError :
cmd = cmd_text . lower ( )
context = None
if not cmd in DEFAULT_CMD_TO_CONTEXT_MAPPING :
... |
def validate ( self ) :
"""Cleans and validates the field values""" | for name , col in self . _columns . items ( ) :
v = getattr ( self , name )
if v is None and not self . _values [ name ] . explicit and col . has_default :
v = col . get_default ( )
val = col . validate ( v )
self . _set_column_value ( name , val ) |
def get_cutoff_energy ( self ) :
'''Determine the cutoff energy from the output''' | return Value ( scalars = [ Scalar ( value = self . settings [ "kinetic-energy cutoff" ] ) ] , units = self . settings [ 'kinetic-energy cutoff units' ] ) |
def sendintr ( self ) :
'''This sends a SIGINT to the child . It does not require
the SIGINT to be the first character on a line .''' | n , byte = self . ptyproc . sendintr ( )
self . _log_control ( byte ) |
def list_datasources ( self , source_id ) :
"""Filterable list of Datasources for a Source .""" | target_url = self . client . get_url ( 'DATASOURCE' , 'GET' , 'multi' , { 'source_id' : source_id } )
return base . Query ( self . client . get_manager ( Datasource ) , target_url ) |
def getCaCerts ( self ) :
'''Return a list of CA certs from the CertDir .
Returns :
[ OpenSSL . crypto . X509 ] : List of CA certificates .''' | retn = [ ]
path = s_common . genpath ( self . certdir , 'cas' )
for name in os . listdir ( path ) :
if not name . endswith ( '.crt' ) :
continue
full = s_common . genpath ( self . certdir , 'cas' , name )
retn . append ( self . _loadCertPath ( full ) )
return retn |
def pdf_link ( self , inv_link_f , y , Y_metadata = None ) :
"""Likelihood function given link ( f )
. . math : :
p ( y _ { i } | \\ lambda ( f _ { i } ) ) = \\ frac { \\ Gamma \\ left ( \\ frac { v + 1 } { 2} \\ right ) } { \\ Gamma \\ left ( \\ frac { v } { 2} \\ right ) \\ sqrt { v \\ pi \\ sigma ^ { 2 } } }... | assert np . atleast_1d ( inv_link_f ) . shape == np . atleast_1d ( y ) . shape
e = y - inv_link_f
# Careful gamma ( big _ number ) is infinity !
objective = ( ( np . exp ( gammaln ( ( self . v + 1 ) * 0.5 ) - gammaln ( self . v * 0.5 ) ) / ( np . sqrt ( self . v * np . pi * self . sigma2 ) ) ) * ( ( 1 + ( 1. / float ( ... |
def retrieve_pool_stats ( self , pool , ** _params ) :
"""Retrieves stats for a certain load balancer pool .""" | return self . get ( self . pool_path_stats % ( pool ) , params = _params ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.