signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def prt_goids ( self , goids = None , prtfmt = None , sortby = True , prt = sys . stdout ) :
"""Given GO IDs , print decriptive info about each GO Term .""" | if goids is None :
goids = self . go_sources
nts = self . get_nts ( goids , sortby )
if prtfmt is None :
prtfmt = self . prt_attr [ 'fmta' ]
for ntgo in nts :
key2val = ntgo . _asdict ( )
prt . write ( "{GO}\n" . format ( GO = prtfmt . format ( ** key2val ) ) )
return nts |
async def proposal ( self ) :
"""Get the proposal in question .
Actually just the first proposal with the same name , but the
chance of a collision is tiny .
Returns
awaitable of : class : ` aionationstates . Proposal `
The proposal submitted .
Raises
aionationstates . NotFound
If the proposal has s... | proposals = await aionationstates . wa . proposals ( )
for proposal in proposals :
if ( proposal . name == self . proposal_name ) :
return proposal
raise aionationstates . NotFound |
def load_dictionary ( self , filename , encoding = "utf-8" ) :
"""Load in a pre - built word frequency list
Args :
filename ( str ) : The filepath to the json ( optionally gzipped ) file to be loaded
encoding ( str ) : The encoding of the dictionary""" | with load_file ( filename , encoding ) as data :
self . _dictionary . update ( json . loads ( data . lower ( ) , encoding = encoding ) )
self . _update_dictionary ( ) |
def srandmember ( self , name , number = None ) :
"""Emulate srandmember .""" | redis_set = self . _get_set ( name , 'SRANDMEMBER' )
if not redis_set :
return None if number is None else [ ]
if number is None :
return choice ( list ( redis_set ) )
elif number > 0 :
return sample ( list ( redis_set ) , min ( number , len ( redis_set ) ) )
else :
return [ choice ( list ( redis_set ) ... |
def get_config_node ( self ) :
'''get _ config _ node
High - level api : get _ config _ node returns an Element node in the config
tree , which is corresponding to the URL in the Restconf GET reply .
Returns
Element
A config node .''' | default_ns = ''
config_node = etree . Element ( config_tag , nsmap = { 'nc' : nc_url } )
for index , url_piece in enumerate ( self . _url_pieces ) :
if index == len ( self . _url_pieces ) - 1 :
config_node_parent = self . copy ( config_node )
node_name , values = self . parse_url_piece ( url_piece )
... |
def _validate_path ( validation_context , path , end_entity_name_override = None ) :
"""Internal copy of validate _ path ( ) that allows overriding the name of the
end - entity certificate as used in exception messages . This functionality is
used during chain validation when dealing with indirect CRLs issuer o... | if not isinstance ( path , ValidationPath ) :
raise TypeError ( pretty_message ( '''
path must be an instance of certvalidator.path.ValidationPath,
not %s
''' , type_name ( path ) ) )
if not isinstance ( validation_context , ValidationContext ) :
raise TypeError ( pretty_mess... |
def ordinal ( value ) :
'''Converts a number to its ordinal representation .
: param value : number
> > > print ( ordinal ( 1 ) )
1st
> > > print ( ordinal ( 11 ) )
11th
> > > print ( ordinal ( 101 ) )
101st
> > > print ( ordinal ( 104 ) )
104th
> > > print ( ordinal ( 113 ) )
113th
> > > pr... | try :
value = int ( value )
except ( TypeError , ValueError ) :
raise ValueError
if value % 100 in ( 11 , 12 , 13 ) :
return '%d%s' % ( value , ORDINAL_SUFFIX [ 0 ] )
else :
return '%d%s' % ( value , ORDINAL_SUFFIX [ value % 10 ] ) |
def convert_reshape ( net , node , module , builder ) :
"""Converts a reshape layer from mxnet to coreml .
This doesn ' t currently handle the deprecated parameters for the reshape layer .
Parameters
network : net
An mxnet network object .
layer : node
Node to convert .
module : module
A module for ... | input_name , output_name = _get_input_output_name ( net , node )
name = node [ 'name' ]
target_shape = node [ 'shape' ]
if any ( item <= 0 for item in target_shape ) :
raise NotImplementedError ( 'Special dimensional values less than or equal to 0 are not supported yet.' 'Feel free to file an issue here: https://gi... |
def index_queryset ( self , using = None ) :
"""Used when the entire index for model is updated .""" | kwargs = { "active" : True }
# if permissions are enabled then we want only public pages
# https : / / github . com / leonardo - modules / leonardo - module - pagepermissions
if hasattr ( Page ( ) , 'permissions' ) :
kwargs [ 'permissions__isnull' ] = True
# https : / / github . com / leonardo - modules / leonardo ... |
def hybrid_forward ( self , F , inputs ) : # pylint : disable = arguments - differ
"""Compute context insensitive token embeddings for ELMo representations .
Parameters
inputs : NDArray
Shape ( batch _ size , sequence _ length , max _ character _ per _ token )
of character ids representing the current batch... | # the character id embedding
# ( batch _ size * sequence _ length , max _ chars _ per _ token , embed _ dim )
character_embedding = self . _char_embedding ( inputs . reshape ( ( - 1 , self . _max_chars_per_token ) ) )
character_embedding = F . transpose ( character_embedding , axes = ( 1 , 0 , 2 ) )
token_embedding = s... |
def cmd_arp_sniff ( iface ) :
"""Listen for ARP packets and show information for each device .
Columns : Seconds from last packet | IP | MAC | Vendor
Example :
1 192.168.0.1 a4:08 : f5:19:17 : a4 Sagemcom Broadband SAS
7 192.168.0.2 64 : bc : 0c : 33 : e5:57 LG Electronics ( Mobile Communications )
2 192.... | conf . verb = False
if iface :
conf . iface = iface
print ( "Waiting for ARP packets..." , file = sys . stderr )
sniff ( filter = "arp" , store = False , prn = procpkt ) |
def _argsort_and_resolve_ties ( time , random_state ) :
"""Like numpy . argsort , but resolves ties uniformly at random""" | n_samples = len ( time )
order = numpy . argsort ( time , kind = "mergesort" )
i = 0
while i < n_samples - 1 :
inext = i + 1
while inext < n_samples and time [ order [ i ] ] == time [ order [ inext ] ] :
inext += 1
if i + 1 != inext : # resolve ties randomly
random_state . shuffle ( order [ ... |
def get_image ( self , digest , blob , mime_type , index , size = 500 ) :
"""Return an image for the given content , only if it already exists in
the image cache .""" | # Special case , for now ( XXX ) .
if mime_type . startswith ( "image/" ) :
return ""
cache_key = f"img:{index}:{size}:{digest}"
return self . cache . get ( cache_key ) |
def file_selection ( multiple = False , directory = False , save = False , confirm_overwrite = False , filename = None , title = "" , width = DEFAULT_WIDTH , height = DEFAULT_HEIGHT , timeout = None ) :
"""Open a file selection window
: param multiple : allow multiple file selection
: type multiple : bool
: p... | dialog = ZFileSelection ( multiple , directory , save , confirm_overwrite , filename , title , width , height , timeout )
dialog . run ( )
return dialog . response |
def _mute ( self ) :
"""mute vlc""" | if self . muted :
self . _sendCommand ( "volume {}\n" . format ( self . actual_volume ) )
if logger . isEnabledFor ( logging . DEBUG ) :
logger . debug ( 'VLC unmuted: {0} ({1}%)' . format ( self . actual_volume , int ( 100 * self . actual_volume / self . max_volume ) ) )
else :
if self . actual_vol... |
def remove_member_from ( self , leaderboard_name , member ) :
'''Remove the optional member data for a given member in the named leaderboard .
@ param leaderboard _ name [ String ] Name of the leaderboard .
@ param member [ String ] Member name .''' | pipeline = self . redis_connection . pipeline ( )
pipeline . zrem ( leaderboard_name , member )
pipeline . hdel ( self . _member_data_key ( leaderboard_name ) , member )
pipeline . execute ( ) |
def _get_efron_values_batch ( self , X , T , E , weights , beta ) : # pylint : disable = too - many - locals
"""Assumes sorted on ascending on T
Calculates the first and second order vector differentials , with respect to beta .
A good explanation for how Efron handles ties . Consider three of five subjects who... | n , d = X . shape
hessian = np . zeros ( ( d , d ) )
gradient = np . zeros ( ( d , ) )
log_lik = 0
# weights = weights [ : , None ]
# Init risk and tie sums to zero
risk_phi , tie_phi = 0 , 0
risk_phi_x , tie_phi_x = np . zeros ( ( d , ) ) , np . zeros ( ( d , ) )
risk_phi_x_x , tie_phi_x_x = np . zeros ( ( d , d ) ) ,... |
def is_homozygous ( self ) :
'''Returns true iff this variant has a GT field and is homozygous , which here
means that the genotype is n / n ( where n can be any number ) .''' | if self . FORMAT is None :
return False
else :
genotypes = set ( self . FORMAT . get ( 'GT' , '0/1' ) . split ( '/' ) )
return '.' not in genotypes and len ( genotypes ) == 1 |
def is_unused ( input , model_file = None , model_proto = None , name = None ) :
"""Returns true if input id is unused piece .
Args :
input : An arbitrary tensor of int32.
model _ file : The sentencepiece model file path .
model _ proto : The sentencepiece model serialized proto .
Either ` model _ file ` ... | return _gen_sentencepiece_processor_op . sentencepiece_get_piece_type ( input , model_file = model_file , model_proto = model_proto , name = name , piece_type = 2 ) |
def edges ( self , tail_head_iter ) :
"""Create a bunch of edges .
Args :
tail _ head _ iter : Iterable of ` ` ( tail _ name , head _ name ) ` ` pairs .""" | edge = self . _edge_plain
quote = self . _quote_edge
lines = ( edge % ( quote ( t ) , quote ( h ) ) for t , h in tail_head_iter )
self . body . extend ( lines ) |
def define_hardware_breakpoint ( self , dwThreadId , address , triggerFlag = BP_BREAK_ON_ACCESS , sizeFlag = BP_WATCH_DWORD , condition = True , action = None ) :
"""Creates a disabled hardware breakpoint at the given address .
@ see :
L { has _ hardware _ breakpoint } ,
L { get _ hardware _ breakpoint } ,
... | thread = self . system . get_thread ( dwThreadId )
bp = HardwareBreakpoint ( address , triggerFlag , sizeFlag , condition , action )
begin = bp . get_address ( )
end = begin + bp . get_size ( )
if dwThreadId in self . __hardwareBP :
bpSet = self . __hardwareBP [ dwThreadId ]
for oldbp in bpSet :
old_beg... |
def load_configuration ( conf_path ) :
"""Load and validate test configuration .
: param conf _ path : path to YAML configuration file .
: return : configuration as dict .""" | with open ( conf_path ) as f :
conf_dict = yaml . load ( f )
validate_config ( conf_dict )
return conf_dict |
def google_get_token ( self , config , prefix ) :
"""Make request to Google API to get token .""" | params = { 'code' : self . request_args_get ( 'code' , default = '' ) , 'client_id' : self . google_api_client_id , 'client_secret' : self . google_api_client_secret , 'redirect_uri' : self . scheme_host_port_prefix ( 'http' , config . host , config . port , prefix ) + '/home' , 'grant_type' : 'authorization_code' , }
... |
def expandEntitiesFromEmail ( e ) :
"""Method that receives an email an creates linked entities
Args :
e : Email to verify .
Returns :
Three different values : email , alias and domain in a list .""" | # Grabbing the email
email = { }
email [ "type" ] = "i3visio.email"
email [ "value" ] = e
email [ "attributes" ] = [ ]
# Grabbing the alias
alias = { }
alias [ "type" ] = "i3visio.alias"
alias [ "value" ] = e . split ( "@" ) [ 0 ]
alias [ "attributes" ] = [ ]
# Grabbing the domain
domain = { }
domain [ "type" ] = "i3vi... |
def press ( self ) :
'''press key via name or key code . Supported key name includes :
home , back , left , right , up , down , center , menu , search , enter ,
delete ( or del ) , recent ( recent apps ) , volume _ up , volume _ down ,
volume _ mute , camera , power .
Usage :
d . press . back ( ) # press ... | @ param_to_property ( key = [ "home" , "back" , "left" , "right" , "up" , "down" , "center" , "menu" , "search" , "enter" , "delete" , "del" , "recent" , "volume_up" , "volume_down" , "volume_mute" , "camera" , "power" ] )
def _press ( key , meta = None ) :
if isinstance ( key , int ) :
return self . server... |
def _handle_subscribed ( self , * args , chanId = None , channel = None , ** kwargs ) :
"""Handles responses to subscribe ( ) commands - registers a channel id with
the client and assigns a data handler to it .
: param chanId : int , represent channel id as assigned by server
: param channel : str , represent... | log . debug ( "_handle_subscribed: %s - %s - %s" , chanId , channel , kwargs )
if chanId in self . channels :
raise AlreadyRegisteredError ( )
self . _heartbeats [ chanId ] = time . time ( )
try :
channel_key = ( 'raw_' + channel if kwargs [ 'prec' ] . startswith ( 'R' ) and channel == 'book' else channel )
exc... |
def _parse_metadata ( self , meta ) :
"""Return the dict containing document metadata""" | formatted_fields = self . settings [ 'FORMATTED_FIELDS' ]
output = collections . OrderedDict ( )
for name , value in meta . items ( ) :
name = name . lower ( )
if name in formatted_fields :
rendered = self . _render ( value ) . strip ( )
output [ name ] = self . process_metadata ( name , rendere... |
def rect_to_cyl_vec ( vx , vy , vz , X , Y , Z , cyl = False ) :
"""NAME :
rect _ to _ cyl _ vec
PURPOSE :
transform vectors from rectangular to cylindrical coordinates vectors
INPUT :
vx -
vy -
vz -
X - X
Y - Y
Z - Z
cyl - if True , X , Y , Z are already cylindrical
OUTPUT :
vR , vT , vz ... | if not cyl :
R , phi , Z = rect_to_cyl ( X , Y , Z )
else :
phi = Y
vr = + vx * sc . cos ( phi ) + vy * sc . sin ( phi )
vt = - vx * sc . sin ( phi ) + vy * sc . cos ( phi )
return ( vr , vt , vz ) |
def RemoveProcessedTaskStorage ( self , task ) :
"""Removes a processed task storage .
Args :
task ( Task ) : task .
Raises :
IOError : if the task storage does not exist .
OSError : if the task storage does not exist .""" | if task . identifier not in self . _task_storage_writers :
raise IOError ( 'Storage writer for task: {0:s} does not exist.' . format ( task . identifier ) )
del self . _task_storage_writers [ task . identifier ] |
def to_ipv6 ( key ) :
"""Get IPv6 address from a public key .""" | if key [ - 2 : ] != '.k' :
raise ValueError ( 'Key does not end with .k' )
key_bytes = base32 . decode ( key [ : - 2 ] )
hash_one = sha512 ( key_bytes ) . digest ( )
hash_two = sha512 ( hash_one ) . hexdigest ( )
return ':' . join ( [ hash_two [ i : i + 4 ] for i in range ( 0 , 32 , 4 ) ] ) |
def eta_hms ( seconds , always_show_hours = False , always_show_minutes = False , hours_leading_zero = False ) :
"""Converts seconds remaining into a human readable timestamp ( e . g . hh : mm : ss , h : mm : ss , mm : ss , or ss ) .
Positional arguments :
seconds - - integer / float indicating seconds remainin... | # Convert seconds to other units .
final_hours , final_minutes , final_seconds = 0 , 0 , seconds
if final_seconds >= 3600 :
final_hours = int ( final_seconds / 3600.0 )
final_seconds -= final_hours * 3600
if final_seconds >= 60 :
final_minutes = int ( final_seconds / 60.0 )
final_seconds -= final_minute... |
def _get_location_descriptor ( self , location ) :
"""Get corresponding : class : ` LocationDescriptor ` object from a string or a : class : ` LocationDescriptor ` itself .
Args :
location : a string or a : class : ` LocationDescriptor ` .
Returns :
A corresponding : class : ` LocationDescriptor ` object . ... | loc_descriptor = None
if isinstance ( location , basestring ) :
loc_descriptor = LocationDescriptor ( location )
elif isinstance ( location , LocationDescriptor ) :
loc_descriptor = location
else :
raise RuntimeError ( "Argument is neither a string nor a self._nbr_of_nodes" )
return loc_descriptor |
def growth ( interval , pricecol , eqdata ) :
"""Retrieve growth labels .
Parameters
interval : int
Number of sessions over which growth is measured . For example , if
the value of 32 is passed for ` interval ` , the data returned will
show the growth 32 sessions ahead for each data point .
eqdata : Dat... | size = len ( eqdata . index )
labeldata = eqdata . loc [ : , pricecol ] . values [ interval : ] / eqdata . loc [ : , pricecol ] . values [ : ( size - interval ) ]
df = pd . DataFrame ( data = labeldata , index = eqdata . index [ : ( size - interval ) ] , columns = [ 'Growth' ] , dtype = 'float64' )
return df |
def add_reserved_switch_binding ( switch_ip , state ) :
"""Add a reserved switch binding .""" | # overload port _ id to contain switch state
add_nexusport_binding ( state , const . NO_VLAN_OR_VNI_ID , const . NO_VLAN_OR_VNI_ID , switch_ip , const . RESERVED_NEXUS_SWITCH_DEVICE_ID_R1 ) |
def prj_create_user ( self , * args , ** kwargs ) :
"""Create a new project
: returns : None
: rtype : None
: raises : None""" | if not self . cur_prj :
return
user = self . create_user ( projects = [ self . cur_prj ] )
if user :
userdata = djitemdata . UserItemData ( user )
treemodel . TreeItem ( userdata , self . prj_user_model . root ) |
def chmod_plus_x ( path ) :
"""Equivalent of unix ` chmod a + x path `""" | path_mode = os . stat ( path ) . st_mode
path_mode &= int ( '777' , 8 )
if path_mode & stat . S_IRUSR :
path_mode |= stat . S_IXUSR
if path_mode & stat . S_IRGRP :
path_mode |= stat . S_IXGRP
if path_mode & stat . S_IROTH :
path_mode |= stat . S_IXOTH
os . chmod ( path , path_mode ) |
def to_dict ( self ) :
"""Returns a dict representation of this instance suitable for
conversion to YAML .""" | return { 'model_type' : 'segmented_discretechoice' , 'name' : self . name , 'segmentation_col' : self . segmentation_col , 'sample_size' : self . sample_size , 'probability_mode' : self . probability_mode , 'choice_mode' : self . choice_mode , 'choosers_fit_filters' : self . choosers_fit_filters , 'choosers_predict_fil... |
def get_halfs_double ( self , vertex_a1 , vertex_b1 , vertex_a2 , vertex_b2 ) :
"""Compute the two parts separated by ` ` ( vertex _ a1 , vertex _ b1 ) ` ` and ` ` ( vertex _ a2 , vertex _ b2 ) ` `
Raise a GraphError when ` ` ( vertex _ a1 , vertex _ b1 ) ` ` and
` ` ( vertex _ a2 , vertex _ b2 ) ` ` do not sep... | if vertex_a1 not in self . neighbors [ vertex_b1 ] :
raise GraphError ( "vertex_a1 must be a neighbor of vertex_b1." )
if vertex_a2 not in self . neighbors [ vertex_b2 ] :
raise GraphError ( "vertex_a2 must be a neighbor of vertex_b2." )
# find vertex _ a _ part ( and possibly switch vertex _ a2 , vertex _ b2)
... |
def random_dimer ( molecule0 , molecule1 , thresholds , shoot_max ) :
"""Create a random dimer .
molecule0 and molecule1 are placed in one reference frame at random
relative positions . Interatomic distances are above the thresholds .
Initially a dimer is created where one interatomic distance approximates
... | # apply a random rotation to molecule1
center = np . zeros ( 3 , float )
angle = np . random . uniform ( 0 , 2 * np . pi )
axis = random_unit ( )
rotation = Complete . about_axis ( center , angle , axis )
cor1 = np . dot ( molecule1 . coordinates , rotation . r )
# select a random atom in each molecule
atom0 = np . ran... |
def split_term ( cls , term ) :
"""Split a term in to parent and record term components
: param term : combined term text
: return : Tuple of parent and record term""" | if '.' in term :
parent_term , record_term = term . split ( '.' )
parent_term , record_term = parent_term . strip ( ) , record_term . strip ( )
if parent_term == '' :
parent_term = ELIDED_TERM
else :
parent_term , record_term = ROOT_TERM , term . strip ( )
return parent_term , record_term |
def query ( botcust2 , message ) :
"""Sends a message to Mitsuku and retrieves the reply
Args :
botcust2 ( str ) : The botcust2 identifier
message ( str ) : The message to send to Mitsuku
Returns :
reply ( str ) : The message Mitsuku sent back""" | logger . debug ( "Getting Mitsuku reply" )
# Set up http request packages
params = { 'botid' : 'f6a012073e345a08' , 'amp;skin' : 'chat' }
headers = { 'Accept-Encoding' : 'gzip, deflate, br' , 'Accept-Language' : 'en-US,en;q=0.8' , 'Cache-Control' : 'max-age=0' , 'Connection' : 'keep-alive' , 'Content-Length' : str ( le... |
def format_stack_trace_json ( self ) :
"""Convert a StackTrace object to json format .""" | stack_trace_json = { }
if self . stack_frames :
stack_trace_json [ 'stack_frames' ] = { 'frame' : self . stack_frames , 'dropped_frames_count' : self . dropped_frames_count }
stack_trace_json [ 'stack_trace_hash_id' ] = self . stack_trace_hash_id
return stack_trace_json |
def copy_to_file ( self , name , fp_dest , callback = None ) :
"""Write cur _ dir / name to file - like ` fp _ dest ` .
Args :
name ( str ) : file name , located in self . curdir
fp _ dest ( file - like ) : must support write ( ) method
callback ( function , optional ) :
Called like ` func ( buf ) ` for e... | assert compat . is_native ( name )
def _write_to_file ( data ) : # print ( " _ write _ to _ file ( ) { } bytes . " . format ( len ( data ) ) )
fp_dest . write ( data )
if callback :
callback ( data )
self . ftp . retrbinary ( "RETR {}" . format ( name ) , _write_to_file , FtpTarget . DEFAULT_BLOCKSIZE ) |
def verification_events ( self ) :
"""Events related to command verification .
: type : List [ : class : ` . CommandHistoryEvent ` ]""" | queued = self . _assemble_event ( 'Verifier_Queued' )
started = self . _assemble_event ( 'Verifier_Started' )
return [ x for x in [ queued , started ] if x ] |
def merge ( self , graph , witness_sigil , witness_tokens , alignments = { } ) :
""": type graph : VariantGraph""" | # NOTE : token _ to _ vertex only contains newly generated vertices
token_to_vertex = { }
last = graph . start
for token in witness_tokens :
vertex = alignments . get ( token , None )
if not vertex :
vertex = graph . add_vertex ( token , witness_sigil )
token_to_vertex [ token ] = vertex
els... |
def log_pdf ( self , y , mu , weights = None ) :
"""computes the log of the pdf or pmf of the values under the current distribution
Parameters
y : array - like of length n
target values
mu : array - like of length n
expected values
weights : array - like shape ( n , ) or None , default : None
sample w... | if weights is None :
weights = np . ones_like ( mu )
scale = self . scale / weights
return sp . stats . norm . logpdf ( y , loc = mu , scale = scale ) |
def from_internal ( self , attribute_profile , internal_dict ) :
"""Converts the internal data to " type "
: type attribute _ profile : str
: type internal _ dict : dict [ str , str ]
: rtype : dict [ str , str ]
: param attribute _ profile : To which external type to convert ( ex : oidc , saml , . . . )
... | external_dict = { }
for internal_attribute_name in internal_dict :
try :
attribute_mapping = self . from_internal_attributes [ internal_attribute_name ]
except KeyError :
logger . debug ( "no attribute mapping found for the internal attribute '%s'" , internal_attribute_name )
continue
... |
def weekdays ( start , end ) :
"""Returns the number of weekdays between the inputted start and end dates .
This would be the equivalent of doing ( end - start ) to get the number of
calendar days between the two dates .
: param start | < datetime . date >
end | < datetime . date >
: return < int >""" | # don ' t bother calculating anything for the same inputted date
if start == end :
return int ( start . isoweekday ( ) not in ( 6 , 7 ) )
elif end < start :
return - weekdays ( end , start )
else :
strt_weekday = start . isoweekday ( )
end_weekday = end . isoweekday ( )
# calculate in the positive d... |
def getDescsV2 ( flags , fs_list = ( ) , hs_list = ( ) , ss_list = ( ) , os_list = ( ) ) :
"""Return a FunctionFS descriptor suitable for serialisation .
flags ( int )
Any combination of VIRTUAL _ ADDR , EVENTFD , ALL _ CTRL _ RECIP ,
CONFIG0 _ SETUP .
{ fs , hs , ss , os } _ list ( list of descriptors )
... | count_field_list = [ ]
descr_field_list = [ ]
kw = { }
for descriptor_list , flag , prefix , allowed_descriptor_klass in ( ( fs_list , HAS_FS_DESC , 'fs' , USBDescriptorHeader ) , ( hs_list , HAS_HS_DESC , 'hs' , USBDescriptorHeader ) , ( ss_list , HAS_SS_DESC , 'ss' , USBDescriptorHeader ) , ( os_list , HAS_MS_OS_DESC... |
def make_plot ( self ) :
"""This method creates the waterfall plot .""" | # sets levels of main contour plot
colors1 = [ 'None' , 'darkblue' , 'blue' , 'deepskyblue' , 'aqua' , 'greenyellow' , 'orange' , 'red' , 'darkred' ]
if len ( self . contour_vals ) > len ( colors1 ) + 1 :
raise AttributeError ( "Reduce number of contours." )
# produce filled contour of SNR
sc = self . axis . contou... |
def from_vega ( cls , ** kwargs ) :
"""Load : ref : ` Vega spectrum < synphot - vega - spec > ` .
Parameters
kwargs : dict
Keywords acceptable by : func : ` ~ synphot . specio . read _ remote _ spec ` .
Returns
vegaspec : ` SourceSpectrum `
Empirical Vega spectrum .""" | filename = conf . vega_file
header , wavelengths , fluxes = specio . read_remote_spec ( filename , ** kwargs )
header [ 'filename' ] = filename
meta = { 'header' : header , 'expr' : 'Vega from {0}' . format ( os . path . basename ( filename ) ) }
return cls ( Empirical1D , points = wavelengths , lookup_table = fluxes ,... |
def display_reports ( self , layout ) :
"""Issues the final PyLint score as a TeamCity build statistic value""" | try :
score = self . linter . stats [ 'global_note' ]
except ( AttributeError , KeyError ) :
pass
else :
self . tc . message ( 'buildStatisticValue' , key = 'PyLintScore' , value = str ( score ) ) |
def passthrough_device ( self , name , controller_port , device , passthrough ) :
"""Sets the passthrough mode of an existing DVD device . Changing the
setting while the VM is running is forbidden . The setting is only used
if at VM start the device is configured as a host DVD drive , in all
other cases it is... | if not isinstance ( name , basestring ) :
raise TypeError ( "name can only be an instance of type basestring" )
if not isinstance ( controller_port , baseinteger ) :
raise TypeError ( "controller_port can only be an instance of type baseinteger" )
if not isinstance ( device , baseinteger ) :
raise TypeError... |
def get_hierarchy_design_session ( self , proxy ) :
"""Gets the ` ` OsidSession ` ` associated with the hierarchy design service .
arg : proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . hierarchy . HierarchyDesignSession ) - a
` ` HierarchyDesignSession ` `
raise : NullArgument - ` ` proxy ` ` is ... | if not self . supports_hierarchy_design ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . HierarchyDesignSession ( proxy = proxy , runtime = self . _runtime ) |
def _resolve_to_func ( self , what ) :
"""This method resolves whatever is passed : a string , a
bound or unbound method , a function , to make it a
function . This makes internal handling of setter and getter
uniform and easier .""" | if isinstance ( what , str ) :
what = getattr ( Adapter . _get_property ( self ) , what )
# makes it an unbounded function if needed
if type ( what ) == types . MethodType :
what = what . __func__
if not type ( what ) == types . FunctionType :
raise TypeError ( "Expected a method name, a method or a functio... |
def make_button_widget ( cls , label , file_path = None , handler = None , style = None , layout = Layout ( width = 'auto' ) ) :
"Return a Button widget with specified ` handler ` ." | btn = widgets . Button ( description = label , layout = layout )
if handler is not None :
btn . on_click ( handler )
if style is not None :
btn . button_style = style
btn . file_path = file_path
btn . flagged_for_delete = False
return btn |
def _estimateCubicCurveLength ( pt0 , pt1 , pt2 , pt3 , precision = 10 ) :
"""Estimate the length of this curve by iterating
through it and averaging the length of the flat bits .""" | points = [ ]
length = 0
step = 1.0 / precision
factors = range ( 0 , precision + 1 )
for i in factors :
points . append ( _getCubicPoint ( i * step , pt0 , pt1 , pt2 , pt3 ) )
for i in range ( len ( points ) - 1 ) :
pta = points [ i ]
ptb = points [ i + 1 ]
length += _distance ( pta , ptb )
return lengt... |
def pool_process ( func , iterable , process_name = 'Pool processing' , cpus = cpu_count ( ) ) :
"""Apply a function to each element in an iterable and return a result list .
: param func : A function that returns a value
: param iterable : A list or set of elements to be passed to the func as the singular para... | with Timer ( '\t{0} ({1}) completed in' . format ( process_name , str ( func ) ) ) :
pool = Pool ( cpus )
vals = pool . map ( func , iterable )
pool . close ( )
return vals |
def verify_submit ( session , queue_url , log_url , job_ids , timeout = _DEFAULT_TIMEOUT , delay = _DEFAULT_DELAY , ** kwargs ) :
"""Verifies that the results were successfully submitted .""" | verification_queue = get_queue_obj ( session = session , queue_url = queue_url , log_url = log_url )
return verification_queue . verify_submit ( job_ids , timeout , delay , ** kwargs ) |
def make_heading_authors ( self , authors ) :
"""Constructs the Authors content for the Heading . This should display
directly after the Article Title .
Metadata element , content derived from FrontMatter""" | author_element = etree . Element ( 'h3' , { 'class' : 'authors' } )
# Construct content for the author element
first = True
for author in authors :
if first :
first = False
else :
append_new_text ( author_element , ',' , join_str = '' )
collab = author . find ( 'collab' )
anon = author .... |
def token ( self , adata , load ) :
'''Determine if token auth is valid and yield the adata''' | try :
token = self . loadauth . get_tok ( load [ 'token' ] )
except Exception as exc :
log . error ( 'Exception occurred when generating auth token: %s' , exc )
yield { }
if not token :
log . warning ( 'Authentication failure of type "token" occurred.' )
yield { }
for sub_auth in adata :
for sub... |
def add_layer2image ( grid2d , x_pos , y_pos , kernel , order = 1 ) :
"""adds a kernel on the grid2d image at position x _ pos , y _ pos with an interpolated subgrid pixel shift of order = order
: param grid2d : 2d pixel grid ( i . e . image )
: param x _ pos : x - position center ( pixel coordinate ) of the la... | x_int = int ( round ( x_pos ) )
y_int = int ( round ( y_pos ) )
shift_x = x_int - x_pos
shift_y = y_int - y_pos
kernel_shifted = interp . shift ( kernel , [ - shift_y , - shift_x ] , order = order )
return add_layer2image_int ( grid2d , x_int , y_int , kernel_shifted ) |
def _linalg_cho_factor ( A , rho , lower = False , check_finite = True ) :
"""Patched version of : func : ` sporco . linalg . cho _ factor ` .""" | N , M = A . shape
if N >= M :
c , lwr = _cho_factor ( A . T . dot ( A ) + rho * cp . identity ( M , dtype = A . dtype ) , lower = lower , check_finite = check_finite )
else :
c , lwr = _cho_factor ( A . dot ( A . T ) + rho * cp . identity ( N , dtype = A . dtype ) , lower = lower , check_finite = check_finite )... |
def create ( self ) :
"""Create the subqueue to change the default behavior of Lock to semaphore .""" | self . queue = self . scheduler . queue . addSubQueue ( self . priority , LockEvent . createMatcher ( self . context , self . key ) , maxdefault = self . size , defaultQueueClass = CBQueue . AutoClassQueue . initHelper ( 'locker' , subqueuelimit = 1 ) ) |
def connect ( self , servers = [ "nats://127.0.0.1:4222" ] , loop = None , # ' io _ loop ' and ' loop ' are the same , but we have
# both params to be consistent with asyncio client .
io_loop = None , # Event Callbacks
error_cb = None , disconnected_cb = None , reconnected_cb = None , closed_cb = None , # ' close _ cb ... | self . _setup_server_pool ( servers )
self . _loop = io_loop or loop or tornado . ioloop . IOLoop . current ( )
self . _error_cb = error_cb
self . _closed_cb = closed_cb or close_cb
self . _reconnected_cb = reconnected_cb
self . _disconnected_cb = disconnected_cb
self . _max_read_buffer_size = max_read_buffer_size
self... |
def add_log_entry ( self , entry ) :
""": db . model . job record holds event log , that can be accessed by MX
this method adds a record and removes oldest one if necessary""" | event_log = self . job_record . event_log
if len ( event_log ) > job . MAX_NUMBER_OF_EVENTS :
del event_log [ - 1 ]
event_log . insert ( 0 , entry ) |
def has_value_of_type ( self , var_type ) :
"""Does the variable both have the given type and
have a variable value we can use ?""" | if self . has_value ( ) and self . has_type ( var_type ) :
return True
return False |
def __set_clear_button_visibility ( self , text ) :
"""Sets the clear button visibility .
: param text : Current field text .
: type text : QString""" | if text :
self . __clear_button . show ( )
else :
self . __clear_button . hide ( ) |
def main ( argv = None ) :
"""Takes crash data via args and generates a Socorro signature""" | parser = argparse . ArgumentParser ( description = DESCRIPTION , epilog = EPILOG )
parser . add_argument ( '-v' , '--verbose' , help = 'increase output verbosity' , action = 'store_true' )
parser . add_argument ( '--format' , help = 'specify output format: csv, text (default)' )
parser . add_argument ( '--different-onl... |
def position_target_global_int_send ( self , time_boot_ms , coordinate_frame , type_mask , lat_int , lon_int , alt , vx , vy , vz , afx , afy , afz , yaw , yaw_rate , force_mavlink1 = False ) :
'''Reports the current commanded vehicle position , velocity , and
acceleration as specified by the autopilot . This
s... | return self . send ( self . position_target_global_int_encode ( time_boot_ms , coordinate_frame , type_mask , lat_int , lon_int , alt , vx , vy , vz , afx , afy , afz , yaw , yaw_rate ) , force_mavlink1 = force_mavlink1 ) |
def get_command_templates ( command_tokens , file_tokens = [ ] , path_tokens = [ ] , job_options = [ ] ) :
"""Given a list of tokens from the grammar , return a
list of commands .""" | files = get_files ( file_tokens )
paths = get_paths ( path_tokens )
job_options = get_options ( job_options )
templates = _get_command_templates ( command_tokens , files , paths , job_options )
for command_template in templates :
command_template . _dependencies = _get_prelim_dependencies ( command_template , templ... |
def select ( * cases ) :
"""Select the first case that becomes ready .
If a default case ( : class : ` goless . dcase ` ) is present ,
return that if no other cases are ready .
If there is no default case and no case is ready ,
block until one becomes ready .
See Go ' s ` ` reflect . Select ` ` method for... | if len ( cases ) == 0 :
return
# If the first argument is a list , it should be the only argument
if isinstance ( cases [ 0 ] , list ) :
if len ( cases ) != 1 :
raise TypeError ( 'Select can be called either with a list of cases ' 'or multiple case arguments, but not both.' )
cases = cases [ 0 ]
... |
def convert_svc_catalog_endpoint_data_to_v3 ( self , ep_data ) :
"""Convert v2 endpoint data into v3.
' service _ name1 ' : [
' adminURL ' : adminURL ,
' id ' : id ,
' region ' : region .
' publicURL ' : publicURL ,
' internalURL ' : internalURL
' service _ name2 ' : [
' adminURL ' : adminURL ,
' ... | self . log . warn ( "Endpoint ID and Region ID validation is limited to not " "null checks after v2 to v3 conversion" )
for svc in ep_data . keys ( ) :
assert len ( ep_data [ svc ] ) == 1 , "Unknown data format"
svc_ep_data = ep_data [ svc ] [ 0 ]
ep_data [ svc ] = [ { 'url' : svc_ep_data [ 'adminURL' ] , '... |
def is_valid_endpoint ( url ) :
"""Just ensures the url has a scheme ( http / https ) , and a net location ( IP or domain name ) .
Can make more advanced or do on - network tests if needed , but this is really just to catch obvious errors .
> > > is _ valid _ endpoint ( " https : / / 34.216.72.29:6206 " )
Tru... | try :
result = urlparse ( url )
if result . port :
_port = int ( result . port )
return ( all ( [ result . scheme , result . netloc ] ) and result . scheme in [ 'http' , 'https' ] )
except ValueError :
return False |
def localize_shapefile ( shp_href , dirs ) :
"""Given a shapefile href and a set of directories , modify the shapefile
name so it ' s correct with respect to the output and cache directories .""" | # support latest mapnik features of auto - detection
# of image sizes and jpeg reading support . . .
# http : / / trac . mapnik . org / ticket / 508
mapnik_requires_absolute_paths = ( MAPNIK_VERSION < 601 )
shp_href = urljoin ( dirs . source . rstrip ( '/' ) + '/' , shp_href )
scheme , host , path , p , q , f = urlpars... |
def similar_objects ( self , num = None , ** filters ) :
"""Find similar objects using related tags .""" | tags = self . tags
if not tags :
return [ ]
content_type = ContentType . objects . get_for_model ( self . __class__ )
filters [ 'content_type' ] = content_type
# can ' t filter , see
# - https : / / github . com / alex / django - taggit / issues / 32
# - https : / / django - taggit . readthedocs . io / en / latest ... |
def nowarnings ( func ) :
"""Create a function wrapped in a context that ignores warnings .""" | @ functools . wraps ( func )
def new_func ( * args , ** kwargs ) :
with warnings . catch_warnings ( ) :
warnings . simplefilter ( 'ignore' )
return func ( * args , ** kwargs )
return new_func |
def get_resource_url ( cls , resource , base_url ) :
"""Construct the URL for talking to this resource .
i . e . :
http : / / myapi . com / api / resource
Note that this is NOT the method for calling individual instances i . e .
http : / / myapi . com / api / resource / 1
Args :
resource : The resource ... | if resource . Meta . resource_name :
url = '{}/{}' . format ( base_url , resource . Meta . resource_name )
else :
p = inflect . engine ( )
plural_name = p . plural ( resource . Meta . name . lower ( ) )
url = '{}/{}' . format ( base_url , plural_name )
return cls . _parse_url_and_validate ( url ) |
def immerkaer_local ( input , size , output = None , mode = "reflect" , cval = 0.0 ) :
r"""Estimate the local noise .
The input image is assumed to have additive zero mean Gaussian noise . The Immerkaer
noise estimation is applied to the image locally over a N - dimensional cube of
side - length size . The si... | output = _ni_support . _get_output ( output , input )
footprint = numpy . asarray ( [ 1 ] * size )
# build nd - kernel to acquire square root of sum of squared elements
kernel = [ 1 , - 2 , 1 ]
for _ in range ( input . ndim - 1 ) :
kernel = numpy . tensordot ( kernel , [ 1 , - 2 , 1 ] , 0 )
divider = numpy . square... |
def compile_timeoper ( rule ) :
"""Compiler helper method : attempt to compile constant into object representing
datetime or timedelta object to enable relations and thus simple comparisons
using Python operators .""" | if isinstance ( rule . value , ( datetime . datetime , datetime . timedelta ) ) :
return rule
if isinstance ( rule , NumberRule ) :
return compile_timedelta ( rule )
if isinstance ( rule , ConstantRule ) :
try :
return compile_datetime ( rule )
except ValueError :
pass
try :
... |
def dispatch ( self , request , * args , ** kwargs ) :
"""Does request processing for return _ url query parameter and redirects with it ' s missing
We can ' t do that in the get method , as it does not exist in the View base class
and child mixins implementing get do not call super ( ) . get""" | self . return_url = request . GET . get ( 'return_url' , None )
referrer = request . META . get ( 'HTTP_REFERER' , None )
# leave alone POST and ajax requests and if return _ url is explicitly left empty
if ( request . method != "GET" or request . is_ajax ( ) or self . return_url or referrer is None or self . return_ur... |
def newer_pairwise_group ( sources_groups , targets ) :
"""Walk both arguments in parallel , testing if each source group is newer
than its corresponding target . Returns a pair of lists ( sources _ groups ,
targets ) where sources is newer than target , according to the semantics
of ' newer _ group ( ) ' .""... | if len ( sources_groups ) != len ( targets ) :
raise ValueError ( "'sources_group' and 'targets' must be the same length" )
# build a pair of lists ( sources _ groups , targets ) where source is newer
n_sources = [ ]
n_targets = [ ]
for i in range ( len ( sources_groups ) ) :
if newer_group ( sources_groups [ i... |
def purge ( self , strategy = "klogn" , keep = None , deleteNonSnapshots = False , ** kwargs ) :
"""Purge snapshot directory of snapshots according to some strategy ,
preserving however a given " keep " list or set of snapshot numbers .
Available strategies are :
" lastk " : Keep last k snapshots ( Default : ... | assert ( isinstance ( keep , ( list , set ) ) or keep is None )
keep = set ( keep or [ ] )
if self . haveSnapshots :
if strategy == "lastk" :
keep . update ( self . strategyLastK ( self . latestSnapshotNum , ** kwargs ) )
elif strategy == "klogn" :
keep . update ( self . strategyKLogN ( self . l... |
def on_mouse ( self , event ) :
'''implement dragging''' | # print ( ' on _ mouse ' )
if not event . Dragging ( ) :
self . _dragPos = None
return
# self . CaptureMouse ( )
if not self . _dragPos :
self . _dragPos = event . GetPosition ( )
else :
pos = event . GetPosition ( )
displacement = self . _dragPos - pos
self . SetPosition ( self . GetPosition ( ... |
def _endCodeIfNeeded ( line , inCodeBlock ) :
"""Simple routine to append end code marker if needed .""" | assert isinstance ( line , str )
if inCodeBlock :
line = '# @endcode{0}{1}' . format ( linesep , line . rstrip ( ) )
inCodeBlock = False
return line , inCodeBlock |
def writeObject ( self , obj , is_proxy = False ) :
"""Writes an object to the stream .""" | if self . use_proxies and not is_proxy :
self . writeProxy ( obj )
return
self . stream . write ( TYPE_OBJECT )
ref = self . context . getObjectReference ( obj )
if ref != - 1 :
self . _writeInteger ( ref << 1 )
return
self . context . addObject ( obj )
# object is not referenced , serialise it
kls = ob... |
def QA_fetch_user ( user_cookie , db = DATABASE ) :
"""get the user
Arguments :
user _ cookie : str the unique cookie _ id for a user
Keyword Arguments :
db : database for query
Returns :
list - - - [ ACCOUNT ]""" | collection = DATABASE . account
return [ res for res in collection . find ( { 'user_cookie' : user_cookie } , { "_id" : 0 } ) ] |
def remove_capability ( capability , image = None , restart = False ) :
'''Uninstall a capability
Args :
capability ( str ) : The capability to be removed
image ( Optional [ str ] ) : The path to the root directory of an offline
Windows image . If ` None ` is passed , the running operating system is
targe... | if salt . utils . versions . version_cmp ( __grains__ [ 'osversion' ] , '10' ) == - 1 :
raise NotImplementedError ( '`uninstall_capability` is not available on this version of ' 'Windows: {0}' . format ( __grains__ [ 'osversion' ] ) )
cmd = [ 'DISM' , '/Quiet' , '/Image:{0}' . format ( image ) if image else '/Onlin... |
def read ( path ) :
"""Read the contents of a LockFile .
Arguments :
path ( str ) : Path to lockfile .
Returns :
Tuple ( int , datetime ) : The integer PID of the lock owner , and the
date the lock was required . If the lock is not claimed , both
values are None .""" | if fs . exists ( path ) :
with open ( path ) as infile :
components = infile . read ( ) . split ( )
pid = int ( components [ 0 ] )
date = datetime . date . fromtimestamp ( float ( components [ 1 ] ) )
return pid , date
else :
return None , None |
def expand_dir ( _dir , cwd = os . getcwd ( ) ) :
"""Return path with environmental variables and tilde ~ expanded .
: param _ dir :
: type _ dir : str
: param cwd : current working dir ( for deciphering relative _ dir paths )
: type cwd : str
: rtype ; str""" | _dir = os . path . expanduser ( os . path . expandvars ( _dir ) )
if not os . path . isabs ( _dir ) :
_dir = os . path . normpath ( os . path . join ( cwd , _dir ) )
return _dir |
def wait_until_complete ( job_list ) :
"""Args : Accepts a list of GPJob objects
This method will not return until all GPJob objects in the list have
finished running . That us , they are either complete and have resulted in
an error state .
This method will occasionally query each job to see if it is finis... | complete = [ False ] * len ( job_list )
wait = 1
while not all ( complete ) :
time . sleep ( wait )
for i , job in enumerate ( job_list ) :
if not complete [ i ] :
complete [ i ] = job . is_finished ( )
if not complete [ i ] :
break
wait = min ( wait * 2 , 10 ... |
def set_model ( model , tablename = None , created = None , appname = None , model_path = None ) :
"""Register an model and tablename to a global variable .
model could be a string format , i . e . , ' uliweb . contrib . auth . models . User '
: param appname : if no appname , then archive according to model
... | if isinstance ( model , type ) and issubclass ( model , Model ) : # use alias first
tablename = model . _alias or model . tablename
tablename = tablename . lower ( )
# set global _ _ models _ _
d = __models__ . setdefault ( tablename , { } )
engines = d . get ( 'config' , { } ) . pop ( 'engines' , [ 'default' ] )
i... |
def update ( self ) :
"""Update | KI1 | based on | EQI1 | and | TInd | .
> > > from hydpy . models . lland import *
> > > parameterstep ( ' 1d ' )
> > > eqi1(5.0)
> > > tind . value = 10.0
> > > derived . ki1 . update ( )
> > > derived . ki1
ki1(50.0)""" | con = self . subpars . pars . control
self ( con . eqi1 * con . tind ) |
def width_aware_slice ( self , index ) :
"""Slice based on the number of columns it would take to display the substring .""" | if wcswidth ( self . s ) == - 1 :
raise ValueError ( 'bad values for width aware slicing' )
index = normalize_slice ( self . width , index )
counter = 0
parts = [ ]
for chunk in self . chunks :
if index . start < counter + chunk . width and index . stop > counter :
start = max ( 0 , index . start - coun... |
def add_bundle ( self , prov_bundle , identifier ) :
"""Verbose method of adding a bundle .
Can also be done as :
> > > api = Api ( )
> > > document = api . document . get ( 148)
> > > document . bundles [ ' identifier ' ] = prov _ bundle
: param prov _ bundle : The bundle to be added
: param str identi... | if self . abstract :
raise AbstractDocumentException ( )
self . _api . add_bundle ( self . id , prov_bundle . serialize ( ) , identifier ) |
def seq_2_StdDoubleVector ( seq , vec = None ) :
"""Converts a python sequence < float > object to a : class : ` tango . StdDoubleVector `
: param seq : the sequence of floats
: type seq : sequence < : py : obj : ` float ` >
: param vec : ( optional , default is None ) an : class : ` tango . StdDoubleVector `... | if vec is None :
if isinstance ( seq , StdDoubleVector ) :
return seq
vec = StdDoubleVector ( )
if not isinstance ( vec , StdDoubleVector ) :
raise TypeError ( 'vec must be a tango.StdDoubleVector' )
for e in seq :
vec . append ( str ( e ) )
return vec |
def time_coef ( tc , nc , tb , nb ) :
"""Return time coefficient relative to base numbers .
@ param tc : current test time
@ param nc : current test data size
@ param tb : base test time
@ param nb : base test data size
@ return : time coef .""" | tc = float ( tc )
nc = float ( nc )
tb = float ( tb )
nb = float ( nb )
q = ( tc * nb ) / ( tb * nc )
return q |
def install_virtualbox ( distribution , force_setup = False ) :
"""install virtualbox""" | if 'ubuntu' in distribution :
with hide ( 'running' , 'stdout' ) :
sudo ( 'DEBIAN_FRONTEND=noninteractive apt-get update' )
sudo ( "sudo DEBIAN_FRONTEND=noninteractive apt-get -y -o " "Dpkg::Options::='--force-confdef' " "-o Dpkg::Options::='--force-confold' upgrade --force-yes" )
install_ub... |
def pad_sequences ( self , sequences , fixed_sentences_seq_length = None , fixed_token_seq_length = None , padding = 'pre' , truncating = 'post' , padding_token = "<PAD>" ) :
"""Pads each sequence to the same fixed length ( length of the longest sequence or provided override ) .
Args :
sequences : list of list ... | value = self . special_token . index ( padding_token )
if value < 0 :
raise ValueError ( 'The padding token "' + padding_token + " is not in the special tokens of the tokenizer." )
# Determine if input is ( samples , max _ sentences , max _ tokens ) or not .
if isinstance ( sequences [ 0 ] [ 0 ] , list ) :
x = ... |
def run_bots ( bots ) :
"""Run many bots in parallel .
: param bots : IRC bots to run .
: type bots : list""" | greenlets = [ spawn ( bot . run ) for bot in bots ]
try :
joinall ( greenlets )
except KeyboardInterrupt :
for bot in bots :
bot . disconnect ( )
finally :
killall ( greenlets ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.