signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def infos ( self , type = None , failed = False ) :
"""Get infos that originate from this node .
Type must be a subclass of : class : ` ~ dallinger . models . Info ` , the default is
` ` Info ` ` . Failed can be True , False or " all " .""" | if type is None :
type = Info
if not issubclass ( type , Info ) :
raise TypeError ( "Cannot get infos of type {} " "as it is not a valid type." . format ( type ) )
if failed not in [ "all" , False , True ] :
raise ValueError ( "{} is not a valid vector failed" . format ( failed ) )
if failed == "all" :
... |
def _get_all_cwlkeys ( items , default_keys = None ) :
"""Retrieve cwlkeys from inputs , handling defaults which can be null .
When inputs are null in some and present in others , this creates unequal
keys in each sample , confusing decision making about which are primary and extras .""" | if default_keys :
default_keys = set ( default_keys )
else :
default_keys = set ( [ "metadata__batch" , "config__algorithm__validate" , "config__algorithm__validate_regions" , "config__algorithm__validate_regions_merged" , "config__algorithm__variant_regions" , "validate__summary" , "validate__tp" , "validate__... |
def load_mldataset ( filename ) :
"""Not particularly fast code to parse the text file and load it into three NDArray ' s
and product an NDArrayIter""" | user = [ ]
item = [ ]
score = [ ]
with open ( filename ) as f :
for line in f :
tks = line . strip ( ) . split ( '\t' )
if len ( tks ) != 4 :
continue
user . append ( int ( tks [ 0 ] ) )
item . append ( int ( tks [ 1 ] ) )
score . append ( float ( tks [ 2 ] ) )
us... |
def compute_Pi_V_given_J ( self , CDR3_seq , V_usage_mask , J_usage_mask ) :
"""Compute Pi _ V conditioned on J .
This function returns the Pi array from the model factors of the V genomic
contributions , P ( V , J ) * P ( delV | V ) . This corresponds to V ( J ) _ { x _ 1 } .
For clarity in parsing the algor... | # Note , the cutV _ genomic _ CDR3 _ segs INCLUDE the palindromic insertions and thus are max _ palindrome nts longer than the template .
# furthermore , the genomic sequence should be pruned to start at the conserved C
Pi_V_given_J = [ np . zeros ( ( 4 , len ( CDR3_seq ) * 3 ) ) for i in J_usage_mask ]
# Holds the agg... |
def write ( self , fileobj = sys . stdout , indent = u"" ) :
"""Recursively write an element and it ' s children to a file .""" | fileobj . write ( self . start_tag ( indent ) )
fileobj . write ( u"\n" ) |
def disable ( cls , args ) :
"""Disable subcommand .""" | mgr = NAppsManager ( )
if args [ 'all' ] :
napps = mgr . get_enabled ( )
else :
napps = args [ '<napp>' ]
for napp in napps :
mgr . set_napp ( * napp )
LOG . info ( 'NApp %s:' , mgr . napp_id )
cls . disable_napp ( mgr ) |
def matchup ( self ) :
"""Return the game meta information displayed in report banners including team names ,
final score , game date , location , and attendance . Data format is
. . code : : python
' home ' : home ,
' away ' : away ,
' final ' : final ,
' attendance ' : att ,
' date ' : date ,
' lo... | if self . play_by_play . matchup :
return self . play_by_play . matchup
elif self . rosters . matchup :
return self . rosters . matchup
elif self . toi . matchup :
return self . toi . matchup
else :
self . face_off_comp . matchup |
def parse_kv_args ( self , args ) :
"""parse key - value style arguments""" | for arg in [ "start" , "end" , "count" , "stride" ] :
try :
arg_raw = args . pop ( arg , None )
if arg_raw is None :
continue
arg_cooked = int ( arg_raw , 0 )
setattr ( self , arg , arg_cooked )
except ValueError :
raise AnsibleError ( "can't parse arg %s=%r a... |
def get_desc2nts_fnc ( self , hdrgo_prt = True , section_prt = None , top_n = None , use_sections = True ) :
"""Return grouped , sorted namedtuples in either format : flat , sections .""" | # RETURN : flat list of namedtuples
nts_flat = self . get_nts_flat ( hdrgo_prt , use_sections )
if nts_flat :
flds = nts_flat [ 0 ] . _fields
if not use_sections :
return { 'sortobj' : self , 'flat' : nts_flat , 'hdrgo_prt' : hdrgo_prt , 'flds' : flds , 'num_items' : len ( nts_flat ) , 'num_sections' : ... |
def call_plugins ( self , step ) :
'''For each plugins , check if a " step " method exist on it , and call it
Args :
step ( str ) : The method to search and call on each plugin''' | for plugin in self . plugins :
try :
getattr ( plugin , step ) ( )
except AttributeError :
self . logger . debug ( "{} doesn't exist on plugin {}" . format ( step , plugin ) )
except TypeError :
self . logger . debug ( "{} on plugin {} is not callable" . format ( step , plugin ) ) |
def route_tables_list_all ( ** kwargs ) :
'''. . versionadded : : 2019.2.0
List all route tables within a subscription .
CLI Example :
. . code - block : : bash
salt - call azurearm _ network . route _ tables _ list _ all''' | result = { }
netconn = __utils__ [ 'azurearm.get_client' ] ( 'network' , ** kwargs )
try :
tables = __utils__ [ 'azurearm.paged_object_to_list' ] ( netconn . route_tables . list_all ( ) )
for table in tables :
result [ table [ 'name' ] ] = table
except CloudError as exc :
__utils__ [ 'azurearm.log_c... |
def IsRunning ( self ) :
"""Returns True if there ' s a currently running iteration of this job .""" | current_urn = self . Get ( self . Schema . CURRENT_FLOW_URN )
if not current_urn :
return False
try :
current_flow = aff4 . FACTORY . Open ( urn = current_urn , aff4_type = flow . GRRFlow , token = self . token , mode = "r" )
except aff4 . InstantiationError : # This isn ' t a flow , something went really wrong... |
def search_tags ( self , tag_name ) :
"""Searches for tags
: param tag _ name : Partial tag name to get autocomplete suggestions for""" | response = self . _req ( '/browse/tags/search' , { "tag_name" : tag_name } )
tags = list ( )
for item in response [ 'results' ] :
tags . append ( item [ 'tag_name' ] )
return tags |
def _get_rename_function ( mapper ) :
"""Returns a function that will map names / labels , dependent if mapper
is a dict , Series or just a function .""" | if isinstance ( mapper , ( abc . Mapping , ABCSeries ) ) :
def f ( x ) :
if x in mapper :
return mapper [ x ]
else :
return x
else :
f = mapper
return f |
def start ( self , program , start = None , stop = None , resolution = None , max_delay = None ) :
"""Start executing the given SignalFlow program without being attached
to the output of the computation .""" | params = self . _get_params ( start = start , stop = stop , resolution = resolution , maxDelay = max_delay )
self . _transport . start ( program , params ) |
def ascolumn ( x , dtype = None ) :
'''Convert ` ` x ` ` into a ` ` column ` ` - type ` ` numpy . ndarray ` ` .''' | x = asarray ( x , dtype )
return x if len ( x . shape ) >= 2 else x . reshape ( len ( x ) , 1 ) |
async def put ( self , tube , data , ttl = None , ttr = None , delay = None ) :
"""Enqueue a task .
Returns a ` Task ` object .""" | cmd = tube . cmd ( "put" )
args = ( data , )
params = dict ( )
if ttr is not None :
params [ "ttr" ] = ttr
if ttl is not None :
params [ "ttl" ] = ttl
if delay is not None :
params [ "delay" ] = delay
if params :
args += ( params , )
res = await self . tnt . call ( cmd , args )
return res |
def parseMemory ( memAttribute ) :
"""Returns EC2 ' memory ' string as a float .
Format should always be ' # ' GiB ( example : ' 244 GiB ' or ' 1,952 GiB ' ) .
Amazon loves to put commas in their numbers , so we have to accommodate that .
If the syntax ever changes , this will raise .
: param memAttribute :... | mem = memAttribute . replace ( ',' , '' ) . split ( )
if mem [ 1 ] == 'GiB' :
return float ( mem [ 0 ] )
else :
raise RuntimeError ( 'EC2 JSON format has likely changed. Error parsing memory.' ) |
def describe ( self , bucket , descriptor = None ) :
"""https : / / github . com / frictionlessdata / tableschema - bigquery - py # storage""" | # Set descriptor
if descriptor is not None :
self . __descriptors [ bucket ] = descriptor
# Get descriptor
else :
descriptor = self . __descriptors . get ( bucket )
if descriptor is None :
table_name = self . __mapper . convert_bucket ( bucket )
response = self . __service . tables ( ) . get... |
def _read_json_db ( self ) :
"""read metadata from a json string stored in a DB .
: return : the parsed json dict
: rtype : dict""" | try :
metadata_str = self . db_io . read_metadata_from_uri ( self . layer_uri , 'json' )
except HashNotFoundError :
return { }
try :
metadata = json . loads ( metadata_str )
return metadata
except ValueError :
message = tr ( 'the file DB entry for %s does not appear to be ' 'valid JSON' )
messag... |
def is_sms_service_for_region ( numobj , region_dialing_from ) :
"""Given a valid short number , determines whether it is an SMS service
( however , nothing is implied about its validity ) . An SMS service is where
the primary or only intended usage is to receive and / or send text messages
( SMSs ) . This in... | if not _region_dialing_from_matches_number ( numobj , region_dialing_from ) :
return False
metadata = PhoneMetadata . short_metadata_for_region ( region_dialing_from )
return ( metadata is not None and _matches_possible_number_and_national_number ( national_significant_number ( numobj ) , metadata . sms_services ) ... |
def hold_absent ( name , snapshot , recursive = False ) :
'''ensure hold is absent on the system
name : string
name of hold
snapshot : string
name of snapshot
recursive : boolean
recursively releases a hold with the given tag on the snapshots of all descendent file systems .''' | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
# # log configuration
log . debug ( 'zfs.hold_absent::%s::config::snapshot = %s' , name , snapshot )
log . debug ( 'zfs.hold_absent::%s::config::recursive = %s' , name , recursive )
# # check we have a snapshot / tag name
if not __utils__ [ 'z... |
def upload_to_s3 ( self , key , filename ) :
"""Set the content type and gzip headers if applicable
and upload the item to S3""" | extra_args = { 'ACL' : self . acl }
# determine the mimetype of the file
guess = mimetypes . guess_type ( filename )
content_type = guess [ 0 ]
encoding = guess [ 1 ]
if content_type :
extra_args [ 'ContentType' ] = content_type
# add the gzip headers , if necessary
if ( self . gzip and content_type in self . gzip_... |
def stop ( cls , name ) :
"""stops the timer with a given name .
: param name : the name of the timer
: type name : string""" | cls . timer_end [ name ] = time . time ( )
if cls . debug :
print ( "Timer" , name , "stopped ..." ) |
def run ( self , test = False ) :
'''The main entry point for a plugin .''' | self . _request = self . _parse_request ( )
log . debug ( 'Handling incoming request for %s' , self . request . path )
items = self . _dispatch ( self . request . path )
# Close any open storages which will persist them to disk
if hasattr ( self , '_unsynced_storages' ) :
for storage in self . _unsynced_storages . ... |
def write_idx ( self , idx , buf ) :
"""Inserts input record at given index .
Examples
> > > for i in range ( 5 ) :
. . . record . write _ idx ( i , ' record _ % d ' % i )
> > > record . close ( )
Parameters
idx : int
Index of a file .
buf :
Record to write .""" | key = self . key_type ( idx )
pos = self . tell ( )
self . write ( buf )
self . fidx . write ( '%s\t%d\n' % ( str ( key ) , pos ) )
self . idx [ key ] = pos
self . keys . append ( key ) |
def stream ( identifier = None , priority = LOG_INFO , level_prefix = False ) :
r"""Return a file object wrapping a stream to journal .
Log messages written to this file as simple newline sepearted text strings
are written to the journal .
The file will be line buffered , so messages are actually sent after a... | if identifier is None :
if not _sys . argv or not _sys . argv [ 0 ] or _sys . argv [ 0 ] == '-c' :
identifier = 'python'
else :
identifier = _sys . argv [ 0 ]
fd = stream_fd ( identifier , priority , level_prefix )
return _os . fdopen ( fd , 'w' , 1 ) |
def wait_until_element_is_visible ( self , locator , timeout = None , error = None ) :
"""Waits until element specified with ` locator ` is visible .
Fails if ` timeout ` expires before the element is visible . See
` introduction ` for more information about ` timeout ` and its
default value .
` error ` can... | def check_visibility ( ) :
visible = self . _is_visible ( locator )
if visible :
return
elif visible is None :
return error or "Element locator '%s' did not match any elements after %s" % ( locator , self . _format_timeout ( timeout ) )
else :
return error or "Element '%s' was no... |
def masked_pick_probability ( x , y , temp , cos_distance ) :
"""The pairwise sampling probabilities for the elements of x for neighbor
points which share labels .
: param x : a matrix
: param y : a list of labels for each element of x
: param temp : Temperature
: cos _ distance : Boolean for using cosine... | return SNNLCrossEntropy . pick_probability ( x , temp , cos_distance ) * SNNLCrossEntropy . same_label_mask ( y , y ) |
def __do_init ( self , dat_dict ) :
"""使用字典方式来更新到存储文件中
: param dat _ dict :
: type dat _ dict :
: return :
: rtype :""" | for k , v in dat_dict . items ( ) :
if isinstance ( v , dict ) :
self . cfg . init ( k , v [ 'val' ] , v [ 'proto' ] )
else :
self . cfg . init ( k , v )
self . cfg . sync ( ) |
def rows_sum_init ( hdf5_file , path , out_lock , * numpy_args ) :
"""Create global variables sharing the same object as the one pointed by
' hdf5 _ file ' , ' path ' and ' out _ lock ' .
Also Create a NumPy array copy of a multiprocessing . Array ctypes array
specified by ' * numpy _ args ' .""" | global g_hdf5_file , g_path , g_out , g_out_lock
g_hdf5_file , g_path , g_out_lock = hdf5_file , path , out_lock
g_out = to_numpy_array ( * numpy_args ) |
def find_by_name ( collection , name , exact = True ) :
"""Searches collection by resource name .
: param rightscale . ResourceCollection collection : The collection in which to
look for : attr : ` name ` .
: param str name : The name to look for in collection .
: param bool exact : A RightScale ` ` index `... | params = { 'filter[]' : [ 'name==%s' % name ] }
found = collection . index ( params = params )
if not exact and len ( found ) > 0 :
return found
for f in found :
if f . soul [ 'name' ] == name :
return f |
def _create_component ( tag_name , allow_children = True , callbacks = [ ] ) :
"""Create a component for an HTML Tag
Examples :
> > > marquee = _ create _ component ( ' marquee ' )
> > > marquee ( ' woohoo ' )
< marquee > woohoo < / marquee >""" | def _component ( * children , ** kwargs ) :
if 'children' in kwargs :
children = kwargs . pop ( 'children' )
else : # Flatten children under specific circumstances
# This supports the use case of div ( [ a , b , c ] )
# And allows users to skip the * operator
if len ( children ) == 1 and... |
def _execute_commands ( self , commands , fails = False ) :
"""Execute commands and get list of failed commands and count of successful commands""" | # Confirm that prepare _ statements flag is on
if self . _prep_statements :
prepared_commands = [ prepare_sql ( c ) for c in tqdm ( commands , total = len ( commands ) , desc = 'Prepping SQL Commands' ) ]
print ( '\tCommands prepared' , len ( prepared_commands ) )
else :
prepared_commands = commands
desc = ... |
def cost ( self ) :
"""Get the approximate cost of this filter .
Cost is the total cost of the exclusion rules in this filter . The cost
of family - specific filters is divided by 10.
Returns :
float : The approximate cost of the filter .""" | total = 0.0
for family , rules in self . _excludes . iteritems ( ) :
cost = sum ( x . cost ( ) for x in rules )
if family :
cost = cost / float ( 10 )
total += cost
return total |
def is_readable ( path ) :
"""Returns if given path is readable .
: param path : Path to check access .
: type path : unicode
: return : Is path writable .
: rtype : bool""" | if os . access ( path , os . R_OK ) :
LOGGER . debug ( "> '{0}' path is readable." . format ( path ) )
return True
else :
LOGGER . debug ( "> '{0}' path is not readable." . format ( path ) )
return False |
def get_attribute ( self , element , attribute , convert_type = True ) :
""": Description : Return the given attribute of the target element .
: param element : Element for browser instance to target .
: type element : WebElement
: param attribute : Attribute of target element to return .
: type attribute :... | attribute = self . browser . execute_script ( 'return arguments[0].getAttribute("%s");' % attribute , element )
return self . __type2python ( attribute ) if convert_type else attribute |
def enable_contact_host_notifications ( self , contact ) :
"""Enable host notifications for a contact
Format of the line that triggers function call : :
ENABLE _ CONTACT _ HOST _ NOTIFICATIONS ; < contact _ name >
: param contact : contact to enable
: type contact : alignak . objects . contact . Contact
:... | if not contact . host_notifications_enabled :
contact . modified_attributes |= DICT_MODATTR [ "MODATTR_NOTIFICATIONS_ENABLED" ] . value
contact . host_notifications_enabled = True
self . send_an_element ( contact . get_update_status_brok ( ) ) |
def add_property ( self , set_property , name , starting_value , tag_name = None ) :
"""Set properies of atributes stored in content using stored common fdel and fget and given fset .
Args :
set _ property - - Function that sets given property .
name - - Name of the atribute this property must simulate . Used... | def del_property ( self , tag_name ) :
try :
del self . _content [ tag_name ]
except KeyError :
pass
def get_property ( self , tag_name ) :
try :
return self . _content [ tag_name ]
except KeyError :
return None
tag_name = ( name if tag_name is None else tag_name )
fget =... |
def get_configuration ( ) :
"""Combine defaults with the Django configuration .""" | configuration = { "get_object_function" : None , "hcard_path" : "/hcard/users/" , "nodeinfo2_function" : None , "process_payload_function" : None , "search_path" : None , # TODO remove or default to True once AP support is more ready
"activitypub" : False , }
configuration . update ( settings . FEDERATION )
if not all ... |
def _ProcessSources ( self , source_path_specs , storage_writer , filter_find_specs = None ) :
"""Processes the sources .
Args :
source _ path _ specs ( list [ dfvfs . PathSpec ] ) : path specifications of
the sources to process .
storage _ writer ( StorageWriter ) : storage writer for a session storage .
... | if self . _processing_profiler :
self . _processing_profiler . StartTiming ( 'process_sources' )
self . _status = definitions . STATUS_INDICATOR_COLLECTING
self . _number_of_consumed_event_tags = 0
self . _number_of_consumed_events = 0
self . _number_of_consumed_reports = 0
self . _number_of_consumed_sources = 0
se... |
def precompute_optimzation_S ( laplacian_matrix , n_samples , relaxation_kwds ) :
"""compute Rk , A , ATAinv , neighbors and pairs for projected mode""" | relaxation_kwds . setdefault ( 'presave' , False )
relaxation_kwds . setdefault ( 'presave_name' , 'pre_comp_current.npy' )
relaxation_kwds . setdefault ( 'verbose' , False )
if relaxation_kwds [ 'verbose' ] :
print ( 'Pre-computing quantities Y to S conversions' )
print ( 'Making A and Pairs' )
A , pairs = mak... |
def present ( name , properties = None , filesystem_properties = None , layout = None , config = None ) :
'''ensure storage pool is present on the system
name : string
name of storage pool
properties : dict
optional set of properties to set for the storage pool
filesystem _ properties : dict
optional se... | ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' }
# config defaults
default_config = { 'import' : True , 'import_dirs' : None , 'device_dir' : None , 'force' : False }
if __grains__ [ 'kernel' ] == 'SunOS' :
default_config [ 'device_dir' ] = '/dev/dsk'
elif __grains__ [ 'kernel' ] == 'Lin... |
def vqa_v2_preprocess_image ( image , height , width , mode , resize_side = 512 , distort = True , image_model_fn = "resnet_v1_152" , ) :
"""vqa v2 preprocess image .""" | image = tf . image . convert_image_dtype ( image , dtype = tf . float32 )
assert resize_side > 0
if resize_side :
image = _aspect_preserving_resize ( image , resize_side )
if mode == tf . estimator . ModeKeys . TRAIN :
image = tf . random_crop ( image , [ height , width , 3 ] )
else : # Central crop , assuming ... |
def SolveClosestFacility ( self , facilities = None , incidents = None , barriers = None , polylineBarriers = None , polygonBarriers = None , attributeParameterValues = None , returnDirections = None , directionsLanguage = None , directionsStyleName = None , directionsLengthUnits = None , directionsTimeAttributeName = ... | raise NotImplementedError ( ) |
def set ( self , value , field = None , index = None , check = 1 ) :
"""Set value of this parameter from a string or other value .
Field is optional parameter field ( p _ prompt , p _ minimum , etc . )
Index is optional array index ( zero - based ) . Set check = 0 to
assign the value without checking to see i... | if index is not None :
sumindex = self . _sumindex ( index )
try :
value = self . _coerceOneValue ( value )
if check :
self . value [ sumindex ] = self . checkOneValue ( value )
else :
self . value [ sumindex ] = value
return
except IndexError : # shou... |
def convert_broadcast_to ( node , ** kwargs ) :
"""Map MXNet ' s broadcast _ to operator attributes to onnx ' s Expand
operator and return the created node .""" | name , input_nodes , attrs = get_inputs ( node , kwargs )
shape_list = convert_string_to_list ( attrs [ "shape" ] )
initializer = kwargs [ "initializer" ]
output_shape_np = np . array ( shape_list , dtype = 'int64' )
data_type = onnx . mapping . NP_TYPE_TO_TENSOR_TYPE [ output_shape_np . dtype ]
dims = np . shape ( out... |
def Debugger_setBlackboxPatterns ( self , patterns ) :
"""Function path : Debugger . setBlackboxPatterns
Domain : Debugger
Method name : setBlackboxPatterns
WARNING : This function is marked ' Experimental ' !
Parameters :
Required arguments :
' patterns ' ( type : array ) - > Array of regexps that will... | assert isinstance ( patterns , ( list , tuple ) ) , "Argument 'patterns' must be of type '['list', 'tuple']'. Received type: '%s'" % type ( patterns )
subdom_funcs = self . synchronous_command ( 'Debugger.setBlackboxPatterns' , patterns = patterns )
return subdom_funcs |
def unpack2D ( _x ) :
"""Helper function for splitting 2D data into x and y component to make
equations simpler""" | _x = np . atleast_2d ( _x )
x = _x [ : , 0 ]
y = _x [ : , 1 ]
return x , y |
def annotate ( self , fname , tables , feature_strand = False , in_memory = False , header = None , out = sys . stdout , parallel = False ) :
"""annotate a file with a number of tables
Parameters
fname : str or file
file name or file - handle
tables : list
list of tables with which to annotate ` fname `
... | from . annotate import annotate
return annotate ( self , fname , tables , feature_strand , in_memory , header = header , out = out , parallel = parallel ) |
def init_scheduler ( db_uri ) :
"""Initialise and configure the scheduler .""" | global scheduler
scheduler = apscheduler . Scheduler ( )
scheduler . misfire_grace_time = 3600
scheduler . add_jobstore ( sqlalchemy_store . SQLAlchemyJobStore ( url = db_uri ) , 'default' )
scheduler . add_listener ( job_listener , events . EVENT_JOB_EXECUTED | events . EVENT_JOB_MISSED | events . EVENT_JOB_ERROR )
re... |
def setEditorData ( self , editor , value ) :
"""Sets the value for the given editor to the inputed value .
: param editor | < QWidget >
value | < variant >""" | # set the data for a multitagedit
if ( isinstance ( editor , XMultiTagEdit ) ) :
if ( not isinstance ( value , list ) ) :
value = [ nativestring ( value ) ]
else :
value = map ( nativestring , value )
editor . setTags ( value )
editor . setCurrentItem ( editor . createItem ( ) )
# set th... |
def image ( request , obj_id ) :
"""Handles a request based on method and calls the appropriate function""" | obj = Image . objects . get ( pk = obj_id )
if request . method == 'POST' :
return post ( request , obj )
elif request . method == 'PUT' :
getPutData ( request )
return put ( request , obj )
elif request . method == 'DELETE' :
getPutData ( request )
return delete ( request , obj ) |
def claim_messages ( self , queue , ttl , grace , count = None ) :
"""Claims up to ` count ` unclaimed messages from the specified queue . If
count is not specified , the default is to claim 10 messages .
The ` ttl ` parameter specifies how long the server should wait before
releasing the claim . The ttl valu... | return queue . claim_messages ( ttl , grace , count = count ) |
def StopTaskStorage ( self , abort = False ) :
"""Removes the temporary path for the task storage .
The results of tasks will be lost on abort .
Args :
abort ( bool ) : True to indicate the stop is issued on abort .
Raises :
IOError : if the storage type is not supported .
OSError : if the storage type ... | if self . _storage_type != definitions . STORAGE_TYPE_SESSION :
raise IOError ( 'Unsupported storage type.' )
if os . path . isdir ( self . _merge_task_storage_path ) :
if abort :
shutil . rmtree ( self . _merge_task_storage_path )
else :
os . rmdir ( self . _merge_task_storage_path )
if os ... |
def prepopulate ( self , queryset ) :
"""Perpopulate a descendants query ' s children efficiently .
Call like : blah . prepopulate ( blah . get _ descendants ( ) . select _ related ( stuff ) )""" | objs = list ( queryset )
hashobjs = dict ( [ ( x . pk , x ) for x in objs ] + [ ( self . pk , self ) ] )
for descendant in hashobjs . values ( ) :
descendant . _cached_children = [ ]
for descendant in objs :
assert descendant . _closure_parent_pk in hashobjs
parent = hashobjs [ descendant . _closure_parent_... |
def get_path_components ( path ) :
"""Extract the module name and class name out of the fully qualified path to the class .
: param str path : The full path to the class .
: return : The module path and the class name .
: rtype : str , str
: raise : ` ` VerifyingDoubleImportError ` ` if the path is to a top... | path_segments = path . split ( '.' )
module_path = '.' . join ( path_segments [ : - 1 ] )
if module_path == '' :
raise VerifyingDoubleImportError ( 'Invalid import path: {}.' . format ( path ) )
class_name = path_segments [ - 1 ]
return module_path , class_name |
def leaf_sections ( h ) :
"""Returns a list of all sections that have no children .""" | leaves = [ ]
for section in h . allsec ( ) :
sref = h . SectionRef ( sec = section )
# nchild returns a float . . . cast to bool
if sref . nchild ( ) < 0.9 :
leaves . append ( section )
return leaves |
def translate_path ( self , path ) :
"""Translate a / - separated PATH to the local filename syntax .
Components that mean special things to the local file system
( e . g . drive or directory names ) are ignored . ( XXX They should
probably be diagnosed . )""" | # abandon query parameters
path = path . split ( '?' , 1 ) [ 0 ]
path = path . split ( '#' , 1 ) [ 0 ]
# Don ' t forget explicit trailing slash when normalizing . Issue17324
trailing_slash = path . rstrip ( ) . endswith ( '/' )
path = posixpath . normpath ( urllib . parse . unquote ( path ) )
words = path . split ( '/'... |
def get_all_attribute_value ( self , tag_name , attribute , format_value = True , ** attribute_filter ) :
"""Yields all the attribute values in xml files which match with the tag name and the specific attribute
: param str tag _ name : specify the tag name
: param str attribute : specify the attribute
: param... | tags = self . find_tags ( tag_name , ** attribute_filter )
for tag in tags :
value = tag . get ( attribute ) or tag . get ( self . _ns ( attribute ) )
if value is not None :
if format_value :
yield self . _format_value ( value )
else :
yield value |
def keyboard ( table , day = None ) :
"""Handler for showing the keyboard statistics page .""" | cols , group = "realkey AS key, COUNT(*) AS count" , "realkey"
where = ( ( "day" , day ) , ) if day else ( )
counts_display = counts = db . fetch ( table , cols , where , group , "count DESC" )
if "combos" == table :
counts_display = db . fetch ( table , "key, COUNT(*) AS count" , where , "key" , "count DESC" )
eve... |
def randompaths ( request , num_paths = 1 , size = 250 , mu = 0 , sigma = 1 ) :
'''Lists of random walks .''' | r = [ ]
for p in range ( num_paths ) :
v = 0
path = [ v ]
r . append ( path )
for t in range ( size ) :
v += normalvariate ( mu , sigma )
path . append ( v )
return r |
def deserialize_decimal ( attr ) :
"""Deserialize string into Decimal object .
: param str attr : response string to be deserialized .
: rtype : Decimal
: raises : DeserializationError if string format invalid .""" | if isinstance ( attr , ET . Element ) :
attr = attr . text
try :
return decimal . Decimal ( attr )
except decimal . DecimalException as err :
msg = "Invalid decimal {}" . format ( attr )
raise_with_traceback ( DeserializationError , msg , err ) |
def snapshot_registry ( self ) :
'''Give the dictionary of recorders detached from the existing instances .
It is safe to store those references for future use . Used by feattool .''' | unserializer = banana . Unserializer ( externalizer = self )
serializer = banana . Serializer ( externalizer = self )
return unserializer . convert ( serializer . convert ( self . registry ) ) |
def _validate_claim_request ( claims , ignore_errors = False ) :
"""Validates a claim request section ( ` userinfo ` or ` id _ token ` ) according
to section 5.5 of the OpenID Connect specification :
- http : / / openid . net / specs / openid - connect - core - 1_0 . html # ClaimsParameter
Returns a copy of t... | results = { }
claims = claims if claims else { }
for name , value in claims . iteritems ( ) :
if value is None :
results [ name ] = None
elif isinstance ( value , dict ) :
results [ name ] = _validate_claim_values ( name , value , ignore_errors )
else :
if not ignore_errors :
... |
def repr_text ( text , indent ) :
"""Return a debug representation of a multi - line text ( e . g . the result
of another repr . . . ( ) function ) .""" | if text is None :
return 'None'
ret = _indent ( text , amount = indent )
return ret . lstrip ( ' ' ) |
def _vertex_different_colors_qubo ( G , x_vars ) :
"""For each vertex , it should not have the same color as any of its
neighbors . Generates the QUBO to enforce this constraint .
Notes
Does not enforce each node having a single color .
Ground energy is 0 , infeasible gap is 1.""" | Q = { }
for u , v in G . edges :
if u not in x_vars or v not in x_vars :
continue
for color in x_vars [ u ] :
if color in x_vars [ v ] :
Q [ ( x_vars [ u ] [ color ] , x_vars [ v ] [ color ] ) ] = 1.
return Q |
def checkout_default_branch ( self ) :
"""git checkout default branch""" | set_state ( WORKFLOW_STATES . CHECKING_OUT_DEFAULT_BRANCH )
cmd = "git" , "checkout" , self . config [ "default_branch" ]
self . run_cmd ( cmd )
set_state ( WORKFLOW_STATES . CHECKED_OUT_DEFAULT_BRANCH ) |
def get_ordered_entries ( self , queryset = False ) :
"""Custom ordering . First we get the average views and rating for
the categories ' s entries . Second we created a rank by multiplying
both . Last , we sort categories by this rank from top to bottom .
Example :
- Cat _ 1
- Entry _ 1 ( 500 Views , Rat... | if queryset :
self . queryset = queryset
else :
self . queryset = EntryCategory . objects . all ( )
if self . queryset :
for category in self . queryset :
entries = category . get_entries ( )
if entries :
amount_list = [ e . amount_of_views for e in entries ]
rating_l... |
def get_referenced_object ( self ) :
""": rtype : core . BunqModel
: raise : BunqException""" | if self . _Payment is not None :
return self . _Payment
if self . _PaymentBatch is not None :
return self . _PaymentBatch
raise exception . BunqException ( self . _ERROR_NULL_FIELDS ) |
def transform ( im , mean , std ) :
"""transform into mxnet tensor ,
subtract pixel size and transform to correct format
: param im : [ height , width , channel ] in BGR
: param mean : [ RGB pixel mean ]
: param std : [ RGB pixel std var ]
: return : [ batch , channel , height , width ]""" | im_tensor = np . zeros ( ( 3 , im . shape [ 0 ] , im . shape [ 1 ] ) )
for i in range ( 3 ) :
im_tensor [ i , : , : ] = ( im [ : , : , 2 - i ] - mean [ i ] ) / std [ i ]
return im_tensor |
def update ( self , infos ) :
"""Process received infos .""" | for info in infos :
if isinstance ( info , LearningGene ) :
self . replicate ( info ) |
def tree ( bary , n , standardization , symbolic = False ) :
"""Evaluates the entire tree of orthogonal triangle polynomials .
The return value is a list of arrays , where ` out [ k ] ` hosts the ` 2 * k + 1 `
values of the ` k ` th level of the tree
(0 , 0)
(0 , 1 ) ( 1 , 1)
(0 , 2 ) ( 1 , 2 ) ( 2 , 2)
... | S = numpy . vectorize ( sympy . S ) if symbolic else lambda x : x
sqrt = numpy . vectorize ( sympy . sqrt ) if symbolic else numpy . sqrt
if standardization == "1" :
p0 = 1
def alpha ( n ) :
r = numpy . arange ( n )
return S ( n * ( 2 * n + 1 ) ) / ( ( n - r ) * ( n + r + 1 ) )
def beta ( n ... |
def start_site ( name ) :
'''Start a Web Site in IIS .
. . versionadded : : 2017.7.0
Args :
name ( str ) : The name of the website to start .
Returns :
bool : True if successful , otherwise False
CLI Example :
. . code - block : : bash
salt ' * ' win _ iis . start _ site name = ' My Test Site ' ''' | ps_cmd = [ 'Start-WebSite' , r"'{0}'" . format ( name ) ]
cmd_ret = _srvmgr ( ps_cmd )
return cmd_ret [ 'retcode' ] == 0 |
def url_report ( self , scan_url , apikey ) :
"""Send URLS for list of past malicous associations""" | url = self . base_url + "url/report"
params = { "apikey" : apikey , 'resource' : scan_url }
rate_limit_clear = self . rate_limit ( )
if rate_limit_clear :
response = requests . post ( url , params = params , headers = self . headers )
if response . status_code == self . HTTP_OK :
json_response = respons... |
def acit ( rest ) :
"Look up an acronym" | word = rest . strip ( )
res = util . lookup_acronym ( word )
if res is None :
return "Arg! I couldn't expand that..."
else :
return ' | ' . join ( res ) |
def permissions_for ( self , user ) :
"""Handles permission resolution for a : class : ` User ` .
This function is there for compatibility with other channel types .
Actual direct messages do not really have the concept of permissions .
This returns all the Text related permissions set to true except :
- se... | base = Permissions . text ( )
base . send_tts_messages = False
base . manage_messages = False
base . mention_everyone = True
if user . id == self . owner . id :
base . kick_members = True
return base |
def user_avatar_update ( self , userid , payload ) :
'''updated avatar by userid''' | response , status_code = self . __pod__ . User . post_v1_admin_user_uid_avatar_update ( sessionToken = self . __session , uid = userid , payload = payload ) . result ( )
self . logger . debug ( '%s: %s' % ( status_code , response ) )
return status_code , response |
def get_steam_id ( vanityurl , ** kwargs ) :
"""Get a players steam id from their steam name / vanity url""" | params = { "vanityurl" : vanityurl }
return make_request ( "ResolveVanityURL" , params , version = "v0001" , base = "http://api.steampowered.com/ISteamUser/" , ** kwargs ) |
def gps_offset ( lat , lon , east , north ) :
'''return new lat / lon after moving east / north
by the given number of meters''' | bearing = math . degrees ( math . atan2 ( east , north ) )
distance = math . sqrt ( east ** 2 + north ** 2 )
return gps_newpos ( lat , lon , bearing , distance ) |
def Upload ( cls , filename ) :
"""文件上传 , 非原生input
@ todo : some upload . exe not prepared
@ param file : 文件名 ( 文件必须存在在工程resource目录下 ) , upload . exe工具放在工程tools目录下""" | raise Exception ( "to do" )
TOOLS_PATH = ""
RESOURCE_PATH = ""
tool_4path = os . path . join ( TOOLS_PATH , "upload.exe" )
file_4path = os . path . join ( RESOURCE_PATH , filename )
# file _ 4path . decode ( ' utf - 8 ' ) . encode ( ' gbk ' )
if os . path . isfile ( file_4path ) :
cls . Click ( )
os . system ( ... |
def isExe ( self ) :
"""Determines if the current L { PE } instance is an Executable file .
@ rtype : bool
@ return : C { True } if the current L { PE } instance is an Executable file . Otherwise , returns C { False } .""" | if not self . isDll ( ) and not self . isDriver ( ) and ( consts . IMAGE_FILE_EXECUTABLE_IMAGE & self . ntHeaders . fileHeader . characteristics . value ) == consts . IMAGE_FILE_EXECUTABLE_IMAGE :
return True
return False |
def cells_from_defaults ( clz , jsonobj ) :
"""Creates a referent instance of type ` json . kind ` and
initializes it to default values .""" | # convert strings to dicts
if isinstance ( jsonobj , ( str , unicode ) ) :
jsonobj = json . loads ( jsonobj )
assert 'cells' in jsonobj , "No cells in object"
domain = TaxonomyCell . get_domain ( )
cells = [ ]
for num , cell_dna in enumerate ( jsonobj [ 'cells' ] ) :
assert 'kind' in cell_dna , "No type definit... |
def resume ( self ) :
"""Resumes the response stream .""" | with self . _wake :
self . _paused = False
self . _wake . notifyAll ( ) |
def competitions_data_list_files ( self , id , ** kwargs ) : # noqa : E501
"""List competition data files # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . competitions _ data _ list _ files ( id ,... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . competitions_data_list_files_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . competitions_data_list_files_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def get_success_url ( self ) :
"""Returns the success URL .
This is either the given ` next ` URL parameter or the content object ' s
` get _ absolute _ url ` method ' s return value .""" | if self . next :
return self . next
if self . object and self . object . content_object :
return self . object . content_object . get_absolute_url ( )
raise Exception ( 'No content object given. Please provide ``next`` in your POST' ' data' ) |
def locate_range ( self , chrom , start = None , stop = None ) :
"""Locate slice of index containing all entries within the range
` key ` : ` start ` - ` stop ` * * inclusive * * .
Parameters
chrom : object
Chromosome or contig .
start : int , optional
Position start value .
stop : int , optional
Po... | slice_chrom = self . locate_key ( chrom )
if start is None and stop is None :
return slice_chrom
else :
pos_chrom = SortedIndex ( self . pos [ slice_chrom ] )
try :
slice_within_chrom = pos_chrom . locate_range ( start , stop )
except KeyError :
raise KeyError ( chrom , start , stop )
... |
def path_options ( line = False , radius = False , ** kwargs ) :
"""Contains options and constants shared between vector overlays
( Polygon , Polyline , Circle , CircleMarker , and Rectangle ) .
Parameters
stroke : Bool , True
Whether to draw stroke along the path .
Set it to false to disable borders on p... | extra_options = { }
if line :
extra_options = { 'smoothFactor' : kwargs . pop ( 'smooth_factor' , 1.0 ) , 'noClip' : kwargs . pop ( 'no_clip' , False ) , }
if radius :
extra_options . update ( { 'radius' : radius } )
color = kwargs . pop ( 'color' , '#3388ff' )
fill_color = kwargs . pop ( 'fill_color' , False )... |
def __PrintAdditionalImports ( self , imports ) :
"""Print additional imports needed for protorpc .""" | google_imports = [ x for x in imports if 'google' in x ]
other_imports = [ x for x in imports if 'google' not in x ]
if other_imports :
for import_ in sorted ( other_imports ) :
self . __printer ( import_ )
self . __printer ( )
# Note : If we ever were going to add imports from this package , we ' d
# n... |
def get_agents_by_ids ( self , agent_ids ) :
"""Gets an ` ` AgentList ` ` corresponding to the given ` ` IdList ` ` .
In plenary mode , the returned list contains all of the agents
specified in the ` ` Id ` ` list , in the order of the list ,
including duplicates , or an error results if an ` ` Id ` ` in the ... | # Implemented from template for
# osid . resource . ResourceLookupSession . get _ resources _ by _ ids
# NOTE : This implementation currently ignores plenary view
collection = JSONClientValidated ( 'authentication' , collection = 'Agent' , runtime = self . _runtime )
object_id_list = [ ]
for i in agent_ids :
object... |
def _apply_loffset ( self , result ) :
"""If loffset is set , offset the result index .
This is NOT an idempotent routine , it will be applied
exactly once to the result .
Parameters
result : Series or DataFrame
the result of resample""" | needs_offset = ( isinstance ( self . loffset , ( DateOffset , timedelta , np . timedelta64 ) ) and isinstance ( result . index , DatetimeIndex ) and len ( result . index ) > 0 )
if needs_offset :
result . index = result . index + self . loffset
self . loffset = None
return result |
def _read_isotopedatabase ( self , ffname = 'isotopedatabase.txt' ) :
'''This private method reads the isotopedatabase . txt file in sldir
run dictory and returns z , a , elements , the cutoff mass for each
species that delineate beta + and beta - decay and the logical in
the last column . Also provides charg... | name = self . sldir + ffname
z_db , a_db , el_db , stable_a_db , logic_db = np . loadtxt ( name , unpack = True , dtype = 'str' )
z_db = np . array ( z_db , dtype = 'int' )
a_db = np . array ( a_db , dtype = 'int' )
stable_a_db = np . array ( stable_a_db , dtype = 'int' )
# charge number for element name from dictionar... |
def compare_ordereddict ( self , X , Y ) :
"""Compares two instances of an OrderedDict .""" | # check if OrderedDict instances have the same keys and values
child = self . compare_dicts ( X , Y )
if isinstance ( child , DeepExplanation ) :
return child
# check if the order of the keys is the same
for i , j in zip ( X . items ( ) , Y . items ( ) ) :
if i [ 0 ] != j [ 0 ] :
c = self . get_context ... |
def _get_stddevs ( self , C , stddev_types , num_sites ) :
"""Return total standard deviation .""" | # standard deviation is converted from log10 to ln
std_total = np . log ( 10 ** C [ 'sigma' ] )
stddevs = [ ]
for _ in stddev_types :
stddevs . append ( np . zeros ( num_sites ) + std_total )
return stddevs |
def get_jid ( jid ) :
'''Return the information returned when the specified job id was executed''' | with _get_serv ( ret = None , commit = True ) as cur :
sql = '''SELECT id, full_ret FROM salt_returns
WHERE jid = %s'''
cur . execute ( sql , ( jid , ) )
data = cur . fetchall ( )
ret = { }
if data :
for minion , full_ret in data :
ret [ minion ] = full_ret
re... |
def supervisor_command ( parser_args ) :
"""Supervisor - related commands""" | import logging
from synergy . supervisor . supervisor_configurator import SupervisorConfigurator , set_box_id
if parser_args . boxid :
set_box_id ( logging , parser_args . argument )
return
sc = SupervisorConfigurator ( )
if parser_args . reset :
sc . reset_db ( )
elif parser_args . start :
sc . mark_fo... |
def split_into ( iterable , sizes ) :
"""Yield a list of sequential items from * iterable * of length ' n ' for each
integer ' n ' in * sizes * .
> > > list ( split _ into ( [ 1,2,3,4,5,6 ] , [ 1,2,3 ] ) )
[ [ 1 ] , [ 2 , 3 ] , [ 4 , 5 , 6 ] ]
If the sum of * sizes * is smaller than the length of * iterable... | # convert the iterable argument into an iterator so its contents can
# be consumed by islice in case it is a generator
it = iter ( iterable )
for size in sizes :
if size is None :
yield list ( it )
return
else :
yield list ( islice ( it , size ) ) |
def logistic ( x , a = 0. , b = 1. ) :
r"""Computes the logistic function with range : math : ` \ in ( a , b ) ` .
This is given by :
. . math : :
\ mathrm { logistic } ( x ; a , b ) = \ frac { a + b e ^ x } { 1 + e ^ x } .
Note that this is also the inverse of the logit function with domain
: math : ` ( ... | expx = numpy . exp ( x )
return ( a + b * expx ) / ( 1. + expx ) |
def connection_key ( self ) :
"""Return an index key used to cache the sampler connection .""" | return "{host}:{namespace}:{username}" . format ( host = self . host , namespace = self . namespace , username = self . username ) |
def _parse_kraken_output ( out_dir , db , data ) :
"""Parse kraken stat info comming from stderr ,
generating report with kraken - report""" | in_file = os . path . join ( out_dir , "kraken_out" )
stat_file = os . path . join ( out_dir , "kraken_stats" )
out_file = os . path . join ( out_dir , "kraken_summary" )
kraken_cmd = config_utils . get_program ( "kraken-report" , data [ "config" ] )
classify = unclassify = None
with open ( stat_file , 'r' ) as handle ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.