signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def fetch_viewers ( self , game ) :
"""Query the viewers and channels of the given game and
set them on the object
: returns : the given game
: rtype : : class : ` models . Game `
: raises : None""" | r = self . kraken_request ( 'GET' , 'streams/summary' , params = { 'game' : game . name } ) . json ( )
game . viewers = r [ 'viewers' ]
game . channels = r [ 'channels' ]
return game |
def from_traverse ( cls , traverse_block ) :
"""Create a GremlinFoldedTraverse block as a copy of the given Traverse block .""" | if isinstance ( traverse_block , Traverse ) :
return cls ( traverse_block . direction , traverse_block . edge_name )
else :
raise AssertionError ( u'Tried to initialize an instance of GremlinFoldedTraverse ' u'with block of type {}' . format ( type ( traverse_block ) ) ) |
def exact_ ( self , column , * values ) :
"""Returns a Dataswim instance with rows that has the exact string
value in a column""" | df = self . _exact ( column , * values )
if df is None :
self . err ( "Can not select exact data" )
return self . _duplicate_ ( df ) |
def index_from_filename ( self , path ) :
"""Checks if the path is already open in an editor tab .
: param path : path to check
: returns : The tab index if found or - 1""" | if path :
for i in range ( self . count ( ) ) :
widget = self . widget ( i )
try :
if widget . file . path == path :
return i
except AttributeError :
pass
# not an editor widget
return - 1 |
def get_choices ( cls , category ) :
"""Get all available options for a category .""" | value = cls . _DEFAULTS [ category ]
if not isinstance ( value , list ) :
raise ValueError ( "{} does not offer choices" . format ( category ) )
return value |
def get_distance ( node1 , node2 ) :
"""Reports the distance in the machine topology between two nodes .
The factors are a multiple of 10 . It returns 0 when the distance cannot be determined . A node has
distance 10 to itself . Reporting the distance requires a Linux kernel version of 2.6.10 or newer .
@ par... | if node1 < 0 or node1 > get_max_node ( ) :
raise ValueError ( node1 )
if node2 < 0 or node2 > get_max_node ( ) :
raise ValueError ( node2 )
return libnuma . numa_distance ( node1 , node2 ) |
def get_node_name_from_id ( node_id , nodes ) :
"""Get the name of a node when given the node _ id
: param int node _ id : The ID of a node
: param list nodes : list of nodes from : py : meth : ` generate _ nodes `
: return : node name
: rtype : str""" | node_name = ''
for node in nodes :
if node [ 'id' ] == node_id :
node_name = node [ 'properties' ] [ 'name' ]
break
return node_name |
def keys ( self , args ) :
"""keys wrapper that queries every shard . This is an expensive
operation .
This method should be invoked on a TwemRedis instance as if it
were being invoked directly on a StrictRedis instance .""" | results = { }
# TODO : parallelize
for shard_num in range ( 0 , self . num_shards ( ) ) :
shard = self . get_shard_by_num ( shard_num )
results [ shard_num ] = shard . keys ( args )
return results |
def getDistanceRoad ( self , edgeID1 , pos1 , edgeID2 , pos2 , isDriving = False ) :
"""getDistanceRoad ( string , double , string , double , boolean ) - > double
Reads two positions on the road network and an indicator whether the air or the driving distance shall be computed . Returns the according distance .""... | distType = tc . REQUEST_AIRDIST
if isDriving :
distType = tc . REQUEST_DRIVINGDIST
self . _connection . _beginMessage ( tc . CMD_GET_SIM_VARIABLE , tc . DISTANCE_REQUEST , "" , 1 + 4 + 1 + 4 + len ( edgeID1 ) + 8 + 1 + 1 + 4 + len ( edgeID2 ) + 8 + 1 + 1 )
self . _connection . _string += struct . pack ( "!Bi" , tc ... |
def __parse_hgvs_syntax ( self , aa_hgvs ) :
"""Convert HGVS syntax for amino acid change into attributes .
Specific details of the mutation are stored in attributes like
self . intial ( prior to mutation ) , sel . pos ( mutation position ) ,
self . mutated ( mutation ) , and self . stop _ pos ( position of s... | self . is_valid = True
# assume initially the syntax is legitimate
self . is_synonymous = False
# assume not synonymous until proven
if self . unknown_effect or self . is_no_protein : # unknown effect from mutation . usually denoted as p . ?
self . pos = None
pass
elif self . is_lost_stop :
self . initial =... |
def ltrim1 ( l , proportiontocut , tail = 'right' ) :
"""Slices off the passed proportion of items from ONE end of the passed
list ( i . e . , if proportiontocut = 0.1 , slices off ' leftmost ' or ' rightmost '
10 % of scores ) . Slices off LESS if proportion results in a non - integer
slice index ( i . e . ,... | if tail == 'right' :
lowercut = 0
uppercut = len ( l ) - int ( proportiontocut * len ( l ) )
elif tail == 'left' :
lowercut = int ( proportiontocut * len ( l ) )
uppercut = len ( l )
return l [ lowercut : uppercut ] |
def add_network_ipv6 ( self , id_vlan , id_tipo_rede , id_ambiente_vip = None , prefix = None ) :
"""Add new networkipv6
: param id _ vlan : Identifier of the Vlan . Integer value and greater than zero .
: param id _ tipo _ rede : Identifier of the NetworkType . Integer value and greater than zero .
: param i... | vlan_map = dict ( )
vlan_map [ 'id_vlan' ] = id_vlan
vlan_map [ 'id_tipo_rede' ] = id_tipo_rede
vlan_map [ 'id_ambiente_vip' ] = id_ambiente_vip
vlan_map [ 'prefix' ] = prefix
code , xml = self . submit ( { 'vlan' : vlan_map } , 'POST' , 'network/ipv6/add/' )
return self . response ( code , xml ) |
def ReplaceIxes ( self , path , old_prefix , old_suffix , new_prefix , new_suffix ) :
"""Replace old _ prefix with new _ prefix and old _ suffix with new _ suffix .
env - Environment used to interpolate variables .
path - the path that will be modified .
old _ prefix - construction variable for the old prefix... | old_prefix = self . subst ( '$' + old_prefix )
old_suffix = self . subst ( '$' + old_suffix )
new_prefix = self . subst ( '$' + new_prefix )
new_suffix = self . subst ( '$' + new_suffix )
dir , name = os . path . split ( str ( path ) )
if name [ : len ( old_prefix ) ] == old_prefix :
name = name [ len ( old_prefix ... |
def should_stop ( self , result ) :
"""Whether the given result meets this trial ' s stopping criteria .""" | if result . get ( DONE ) :
return True
for criteria , stop_value in self . stopping_criterion . items ( ) :
if criteria not in result :
raise TuneError ( "Stopping criteria {} not provided in result {}." . format ( criteria , result ) )
if result [ criteria ] >= stop_value :
return True
retu... |
def cmd_cammsg ( self , args ) :
'''cammsg''' | params = [ 0 , 0 , 0 , 0 , 1 , 0 , 0 ]
# fill in any args passed by user
for i in range ( min ( len ( args ) , len ( params ) ) ) :
params [ i ] = float ( args [ i ] )
print ( "Sent DIGICAM_CONTROL CMD_LONG" )
self . master . mav . command_long_send ( self . settings . target_system , # target _ system
0 , # target... |
def largest_divisor ( n : int ) -> int :
"""For a given positive number n , find the largest number that divides n evenly , smaller than n .
Args :
n ( int ) : number to find the largest divisor for , n > 0
Returns :
int : the largest divisor of n that is less than n
Examples :
> > > largest _ divisor (... | for i in range ( n - 1 , 0 , - 1 ) :
if n % i == 0 :
return i
# the smallest positive number does not have a divisor other than 1
return 1 |
def read_byte ( self , addr ) :
"""Read a single byte from static memory area ( blocks 0-14 ) .""" | if addr < 0 or addr > 127 :
raise ValueError ( "invalid byte address" )
log . debug ( "read byte at address {0} ({0:02X}h)" . format ( addr ) )
cmd = "\x01" + chr ( addr ) + "\x00" + self . uid
return self . transceive ( cmd ) [ - 1 ] |
def logger ( ref = 0 ) :
"""Finds a module logger .
If the argument passed is a module , find the logger for that module using
the modules ' name ; if it ' s a string , finds a logger of that name ; if an
integer , walks the stack to the module at that height .
The logger is always extended with a ` ` . con... | if inspect . ismodule ( ref ) :
return extend ( logging . getLogger ( ref . __name__ ) )
if isinstance ( ref , basestring ) :
return extend ( logging . getLogger ( ref ) )
return extend ( logging . getLogger ( stackclimber ( ref + 1 ) ) ) |
def _check_forward_mode_input_array ( self , X : np . ndarray ) -> int :
"""Check whether one forward mode input array is of valid shape
Returns inferred value of T""" | # Find the length of each variable to infer T
if not isinstance ( X , np . ndarray ) :
raise ValueError ( 'X must be a numpy array, dict, or scalar' )
# Get the shape and tensor rank
shape = X . shape
tensor_rank = len ( shape )
T = 0
# Only 1D and 2D arrays are supported
if tensor_rank not in ( 0 , 1 , 2 ) :
r... |
def connect ( self ) :
"""connect to the device
: return : bool""" | self . end_live_capture = False
if not self . ommit_ping and not self . helper . test_ping ( ) :
raise ZKNetworkError ( "can't reach device (ping %s)" % self . __address [ 0 ] )
if not self . force_udp and self . helper . test_tcp ( ) == 0 :
self . user_packet_size = 72
# default zk8
self . __create_socket ... |
def save ( self , filename ) :
"""Saves the data for this settings instance to the given filename .
: param filename | < str >""" | dirname = os . path . dirname ( filename )
if not os . path . exists ( dirname ) :
os . makedirs ( dirname )
try :
f = open ( filename , 'w' )
except StandardError :
log . error ( 'Failed to access file: {0}' . format ( filename ) )
return False
try :
f . write ( yaml . dump ( self . _root , default... |
def congestion ( self ) :
"""Retrieves the congestion information of the incident / incidents from
the output response
Returns :
congestion ( namedtuple ) : List of named tuples of congestion info of
the incident / incidents""" | resource_list = self . traffic_incident ( )
congestion = namedtuple ( 'congestion' , 'congestion' )
if len ( resource_list ) == 1 and resource_list [ 0 ] is None :
return None
else :
try :
return [ congestion ( resource [ 'congestion' ] ) for resource in resource_list ]
except ( KeyError , TypeError... |
def _run_in_parallel ( programs , nsamples , cxn ) :
"""See docs for ` ` run _ in _ parallel ( ) ` ` .
: param Union [ np . ndarray , List [ List [ Program ] ] ] programs : A rectangular list of lists , or a 2d
array of Quil Programs . The outer list iterates over disjoint qubit groups as targets , the
inner ... | n_groups = len ( programs )
n_progs_per_group = len ( programs [ 0 ] )
for progs in programs [ 1 : ] :
if not len ( progs ) == n_progs_per_group :
raise ValueError ( "Non-rectangular grid of programs specified: {}" . format ( programs ) )
# identify qubit groups , ensure disjointedness
qubit_groups = [ set ... |
def get_payload ( self , data ) :
"""Parse length of payload and return it .""" | start = 2
length = ord ( data [ 1 : 2 ] )
if length == 126 : # Payload information are an extra 2 bytes .
start = 4
length , = unpack ( ">H" , data [ 2 : 4 ] )
elif length == 127 : # Payload information are an extra 6 bytes .
start = 8
length , = unpack ( ">I" , data [ 2 : 6 ] )
end = start + length
pay... |
def check_statement ( self , stmt , max_paths = 1 , max_path_length = 5 ) :
"""Check a single Statement against the model .
Parameters
stmt : indra . statements . Statement
The Statement to check .
max _ paths : Optional [ int ]
The maximum number of specific paths to return for each Statement
to be exp... | # Make sure the influence map is initialized
self . get_im ( )
# Check if this is one of the statement types that we can check
if not isinstance ( stmt , ( Modification , RegulateAmount , RegulateActivity , Influence ) ) :
return PathResult ( False , 'STATEMENT_TYPE_NOT_HANDLED' , max_paths , max_path_length )
# Ge... |
def setup_actions ( self ) :
"""Connects slots to signals""" | self . actionOpen . triggered . connect ( self . on_open )
self . actionNew . triggered . connect ( self . on_new )
self . actionSave . triggered . connect ( self . on_save )
self . actionSave_as . triggered . connect ( self . on_save_as )
self . actionQuit . triggered . connect ( QtWidgets . QApplication . instance ( ... |
def validate_line ( self , line ) :
"""Validate Unicode IPA string relative to panphon .
line - - String of IPA characters . Can contain whitespace and limited
punctuation .""" | line0 = line
pos = 0
while line :
seg_m = self . ft . seg_regex . match ( line )
wsp_m = self . ws_punc_regex . match ( line )
if seg_m :
length = len ( seg_m . group ( 0 ) )
line = line [ length : ]
pos += length
elif wsp_m :
length = len ( wsp_m . group ( 0 ) )
... |
def assert_close ( a , b , rtol = 1e-07 , atol = 0 , context = None ) :
"""Compare for equality up to a given precision two composite objects
which may contain floats . NB : if the objects are or contain generators ,
they are exhausted .
: param a : an object
: param b : another object
: param rtol : rela... | if isinstance ( a , float ) or isinstance ( a , numpy . ndarray ) and a . shape : # shortcut
numpy . testing . assert_allclose ( a , b , rtol , atol )
return
if isinstance ( a , ( str , bytes , int ) ) : # another shortcut
assert a == b , ( a , b )
return
if hasattr ( a , '_slots_' ) : # record - like o... |
def ReadFrom ( self , byte_stream ) :
"""Read values from a byte stream .
Args :
byte _ stream ( bytes ) : byte stream .
Returns :
tuple [ object , . . . ] : values copies from the byte stream .
Raises :
IOError : if byte stream cannot be read .
OSError : if byte stream cannot be read .""" | try :
return self . _struct . unpack_from ( byte_stream )
except ( TypeError , struct . error ) as exception :
raise IOError ( 'Unable to read byte stream with error: {0!s}' . format ( exception ) ) |
def __method_descriptor ( self , service , method_info , operation_id , protorpc_method_info , security_definitions ) :
"""Describes a method .
Args :
service : endpoints . Service , Implementation of the API as a service .
method _ info : _ MethodInfo , Configuration for the method .
operation _ id : strin... | descriptor = { }
request_message_type = ( resource_container . ResourceContainer . get_request_message ( protorpc_method_info . remote ) )
request_kind = self . __get_request_kind ( method_info )
remote_method = protorpc_method_info . remote
path = method_info . get_path ( service . api_info )
descriptor [ 'parameters'... |
def _clean_props ( self ) :
"""Makes sure all properties are legit for isochrone .
Not done in _ _ init _ _ in order to save speed on loading .""" | remove = [ ]
for p in self . properties . keys ( ) :
if not hasattr ( self . ic , p ) and p not in self . ic . bands and p not in [ 'parallax' , 'feh' , 'age' , 'mass_B' , 'mass_C' ] and not re . search ( 'delta_' , p ) :
remove . append ( p )
for p in remove :
del self . properties [ p ]
if len ( remov... |
def GetMetadataAttribute ( self , attribute_name ) :
"""Retrieves the metadata attribute .
Args :
attribute _ name ( str ) : name of the metadata attribute .
Returns :
str : the metadata attribute or None .
Raises :
RuntimeError : if more than one value is found in the database .""" | table_name = 'metadata'
has_table = self . _database_file . HasTable ( table_name )
if not has_table :
return None
column_names = [ 'value' ]
condition = 'name == "{0:s}"' . format ( attribute_name )
values = list ( self . _database_file . GetValues ( [ table_name ] , column_names , condition ) )
number_of_values =... |
def fill_values_to_nan ( masked_array ) :
"""Replaces the fill _ values of the masked array by NaNs
If the array is None or it does not contain floating point values , it cannot contain NaNs .
In that case the original array is returned .""" | if masked_array is not None and masked_array . dtype . kind == 'f' :
check_class ( masked_array , ma . masked_array )
logger . debug ( "Replacing fill_values by NaNs" )
masked_array [ : ] = ma . filled ( masked_array , np . nan )
masked_array . set_fill_value ( np . nan )
else :
return masked_array |
def _attrib_to_transform ( attrib ) :
"""Extract a homogenous transform from a dictionary .
Parameters
attrib : dict , optionally containing ' transform '
Returns
transform : ( 4 , 4 ) float , homogeonous transformation""" | transform = np . eye ( 4 , dtype = np . float64 )
if 'transform' in attrib : # wangle their transform format
values = np . array ( attrib [ 'transform' ] . split ( ) , dtype = np . float64 ) . reshape ( ( 4 , 3 ) ) . T
transform [ : 3 , : 4 ] = values
return transform |
def decode_int ( stream , signed = False ) :
"""Decode C { int } .""" | n = result = 0
b = stream . read_uchar ( )
while b & 0x80 != 0 and n < 3 :
result <<= 7
result |= b & 0x7f
b = stream . read_uchar ( )
n += 1
if n < 3 :
result <<= 7
result |= b
else :
result <<= 8
result |= b
if result & 0x10000000 != 0 :
if signed :
result -= 0x... |
def pipe_datebuilder ( context = None , _INPUT = None , conf = None , ** kwargs ) :
"""A date module that converts a text string into a datetime value . Useful
as terminal data . Loopable .
Parameters
context : pipe2py . Context object
_ INPUT : pipeforever pipe or an iterable of items
conf : { ' DATE ' :... | conf = DotDict ( conf )
for item in _INPUT :
_input = DotDict ( item )
date = utils . get_value ( conf [ 'DATE' ] , _input , ** kwargs ) . lower ( )
if date . endswith ( ' day' ) or date . endswith ( ' days' ) :
count = int ( date . split ( ' ' ) [ 0 ] )
new_date = dt . today ( ) + timedelta... |
def change_node_affiliations ( self , jid , node , affiliations_to_set ) :
"""Update the affiliations at a node .
: param jid : Address of the PubSub service .
: type jid : : class : ` aioxmpp . JID `
: param node : Name of the node to modify
: type node : : class : ` str `
: param affiliations _ to _ set... | iq = aioxmpp . stanza . IQ ( type_ = aioxmpp . structs . IQType . SET , to = jid , payload = pubsub_xso . OwnerRequest ( pubsub_xso . OwnerAffiliations ( node , affiliations = [ pubsub_xso . OwnerAffiliation ( jid , affiliation ) for jid , affiliation in affiliations_to_set ] ) ) )
yield from self . client . send ( iq ... |
def _label_names_correct ( self , labels ) :
"""Raise exception ( ValueError ) if labels not correct""" | for k , v in labels . items ( ) : # Check reserved labels
if k in RESTRICTED_LABELS_NAMES :
raise ValueError ( "Labels not correct" )
# Check prefixes
if any ( k . startswith ( i ) for i in RESTRICTED_LABELS_PREFIXES ) :
raise ValueError ( "Labels not correct" )
return True |
def from_attrdict ( cls , attrdict : OrderedNamespace ) -> object :
"""Builds a new instance of the ORM object from values in an attrdict .""" | dictionary = attrdict . __dict__
# noinspection PyArgumentList
return cls ( ** dictionary ) |
def query ( self , variables , evidence = None , args = 'exact' ) :
"""Query method for Dynamic Bayesian Network using Interface Algorithm .
Parameters :
variables : list
list of variables for which you want to compute the probability
evidence : dict
a dict key , value pair as { var : state _ of _ var _ o... | if args == 'exact' :
return self . backward_inference ( variables , evidence ) |
def unpack ( self , buff , offset = 0 ) :
"""Unpack a binary message into this object ' s attributes .
Unpack the binary value * buff * and update this object attributes based
on the results .
Args :
buff ( bytes ) : Binary data package to be unpacked .
offset ( int ) : Where to begin unpacking .
Raises... | header = UBInt16 ( )
header . unpack ( buff [ offset : offset + 2 ] )
self . tlv_type = header . value >> 9
length = header . value & 511
begin , end = offset + 2 , offset + 2 + length
sub_type = UBInt8 ( )
sub_type . unpack ( buff [ begin : begin + 1 ] )
self . sub_type = sub_type . value
self . sub_value = BinaryData... |
def kill_session ( self ) :
"""` ` $ tmux kill - session ` ` .""" | proc = self . cmd ( 'kill-session' , '-t%s' % self . id )
if proc . stderr :
raise exc . LibTmuxException ( proc . stderr ) |
def getCeilingZoom ( self , resolution , unit = 'meters' ) :
"""Return the maximized zoom level for a given resolution
Parameters :
resolution - - max . resolution
unit - - unit for output ( default = ' meters ' )""" | if resolution in self . RESOLUTIONS :
return self . getZoom ( resolution )
lo , hi = self . _getZoomLevelRange ( resolution , unit )
if lo == 0 or lo == hi :
return lo
if hi == len ( self . RESOLUTIONS ) :
return hi - 1
return lo + 1 |
def roll_die ( qvm , number_of_sides ) :
"""Roll an n - sided quantum die .""" | die_compiled = qvm . compile ( die_program ( number_of_sides ) )
return process_results ( qvm . run ( die_compiled ) ) |
def _parse_sequence_tag ( self ) :
'''Parses the sequence and atomic mass .''' | # main _ tags = self . _ dom . getElementsByTagName ( " uniprot " )
# assert ( len ( main _ tags ) = = 1)
# entry _ tags = main _ tags [ 0 ] . getElementsByTagName ( " entry " )
# assert ( len ( entry _ tags ) = = 1)
# entry _ tags [ 0]
entry_tag = self . entry_tag
# only get sequence tags that are direct children of t... |
def contrail_error_handler ( f ) :
"""Handle HTTP errors returned by the API server""" | @ wraps ( f )
def wrapper ( * args , ** kwargs ) :
try :
return f ( * args , ** kwargs )
except HttpError as e : # Replace message by details to provide a
# meaningful message
if e . details :
e . message , e . details = e . details , e . message
e . args = ( "%s (HTT... |
def SaveName_Conv ( Mod = None , Cls = None , Type = None , Name = None , Deg = None , Exp = None , Diag = None , shot = None , version = None , usr = None , Include = defInclude ) :
"""Return a default name for saving the object
Includes key info for fast identification of the object from file name
Used on obj... | Modstr = dModes [ Mod ] if Mod is not None else None
Include = defInclude if Include is None else Include
if Cls is not None and Type is not None and 'Type' in Include :
Clsstr = Cls + Type
else :
Clsstr = Cls
Dict = { 'Mod' : Modstr , 'Cls' : Clsstr , 'Name' : Name }
for ii in Include :
if not ii in [ 'Mod... |
def post ( self , resource_endpoint , data = { } , files = None ) :
"""Don ' t use it .""" | url = self . _create_request_url ( resource_endpoint )
if files :
data = self . _prepare_params_for_file_upload ( data )
return req . post ( url , headers = self . auth_header , files = files , data = data )
else :
return req . post ( url , headers = self . auth_header , json = data ) |
def _readResponse ( self ) :
"""Yield each row of response untill ! done is received .
: throws TrapError : If one ! trap is received .
: throws MultiTrapError : If > 1 ! trap is received .""" | traps = [ ]
reply_word = None
while reply_word != '!done' :
reply_word , words = self . _readSentence ( )
if reply_word == '!trap' :
traps . append ( TrapError ( ** words ) )
elif reply_word in ( '!re' , '!done' ) and words :
yield words
if len ( traps ) > 1 :
raise MultiTrapError ( * tr... |
def index ( self ) :
"""Returns the first occurrence of the pedalboard in your bank""" | if self . bank is None :
raise IndexError ( 'Pedalboard not contains a bank' )
return self . bank . pedalboards . index ( self ) |
def pretty_echo ( cls , message ) :
"""Display message using pretty print formatting .""" | if cls . intty ( ) :
if message :
from pprint import pprint
pprint ( message ) |
def is_read_only ( object ) :
"""Returns if given object is read only ( built - in or extension ) .
: param object : Object .
: type object : object
: return : Is object read only .
: rtype : bool""" | try :
attribute = "_trace__read__"
setattr ( object , attribute , True )
delattr ( object , attribute )
return False
except ( TypeError , AttributeError ) :
return True |
def plot ( data , pconfig = None ) :
"""Plot a line graph with X , Y data .
: param data : 2D dict , first keys as sample names , then x : y data pairs
: param pconfig : optional dict with config key : value pairs . See CONTRIBUTING . md
: return : HTML and JS , ready to be inserted into the page""" | # Don ' t just use { } as the default argument as it ' s mutable . See :
# http : / / python - guide - pt - br . readthedocs . io / en / latest / writing / gotchas /
if pconfig is None :
pconfig = { }
# Allow user to overwrite any given config for this plot
if 'id' in pconfig and pconfig [ 'id' ] and pconfig [ 'id'... |
def userContent ( self ) :
"""allows access into the individual user ' s content to get at the
items owned by the current user""" | replace_start = self . _url . lower ( ) . find ( "/community/" )
len_replace = len ( "/community/" )
url = self . _url . replace ( self . _url [ replace_start : replace_start + len_replace ] , '/content/' )
from . _content import User as UserContent
return UserContent ( url = url , securityHandler = self . _securityHan... |
def get_execution_engine ( self , name ) :
"""Return an execution engine instance .""" | try :
return self . execution_engines [ name ]
except KeyError :
raise InvalidEngineError ( "Unsupported execution engine: {}" . format ( name ) ) |
def _load_class_entry_point ( cls , entry_point ) :
"""Load ` entry _ point ` , and set the ` entry _ point . name ` as the
attribute ` plugin _ name ` on the loaded object""" | class_ = entry_point . load ( )
setattr ( class_ , 'plugin_name' , entry_point . name )
return class_ |
def forkexec ( argv , env = None ) :
"""Fork a child process .""" | child_pid = os . fork ( )
if child_pid == 0 :
os . closerange ( 3 , MAXFD )
environ = os . environ . copy ( )
if env is not None :
environ . update ( env )
os . execve ( argv [ 0 ] , argv , environ )
return child_pid |
def get_repository ( self , repository_id ) :
"""Gets the ` ` Repository ` ` specified by its ` ` Id ` ` .
In plenary mode , the exact ` ` Id ` ` is found or a ` ` NotFound ` `
results . Otherwise , the returned ` ` Repository ` ` may have a
different ` ` Id ` ` than requested , such as the case where a
dup... | # Implemented from template for
# osid . resource . BinLookupSession . get _ bin
if self . _catalog_session is not None :
return self . _catalog_session . get_catalog ( catalog_id = repository_id )
collection = JSONClientValidated ( 'repository' , collection = 'Repository' , runtime = self . _runtime )
# Need to co... |
def HandleVerack ( self ) :
"""Handle the ` verack ` response .""" | m = Message ( 'verack' )
self . SendSerializedMessage ( m )
self . leader . NodeCount += 1
self . identifier = self . leader . NodeCount
logger . debug ( f"{self.prefix} Handshake complete!" )
self . handshake_complete = True
self . ProtocolReady ( ) |
def fan_maxcfm ( ddtt ) :
"""return the fan max cfm""" | if str ( ddtt . Maximum_Flow_Rate ) . lower ( ) == 'autosize' : # str can fail with unicode chars : - (
return 'autosize'
else :
m3s = float ( ddtt . Maximum_Flow_Rate )
return m3s2cfm ( m3s ) |
def find_column ( token ) :
"""Compute column :
input is the input text string
token is a token instance""" | i = token . lexpos
input = token . lexer . lexdata
while i > 0 :
if input [ i - 1 ] == '\n' :
break
i -= 1
column = token . lexpos - i + 1
return column |
def recursive_build_tree ( self , intervals ) :
"""recursively builds a BST based on the elementary intervals .
each node is an array : [ interval value , left descendent nodes , right descendent nodes , [ ids ] ] .
nodes with no descendents have a - 1 value in left / right descendent positions .
for example ... | center = int ( round ( len ( intervals ) / 2 ) )
left = intervals [ : center ]
right = intervals [ center + 1 : ]
node = intervals [ center ]
if len ( left ) > 1 :
left = self . recursive_build_tree ( left )
elif len ( left ) == 1 :
left = [ left [ 0 ] , [ - 1 , - 1 , - 1 , [ ] ] , [ - 1 , - 1 , - 1 , [ ] ] , [... |
def _set_adj_use ( self , v , load = False ) :
"""Setter method for adj _ use , mapped from YANG variable / adj _ neighbor _ entries _ state / adj _ neighbor / adj _ use ( isis - spf - level )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ adj _ use is considered as a ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'level-1-2' : { 'value' : 3 } , u'level-2' : { 'value' : 2 } , u'level-1' : { 'value' : 1 } } , ) , is_leaf = True , yang_name =... |
def check_compound_consistency ( database , solver , exchange = set ( ) , zeromass = set ( ) ) :
"""Yield each compound in the database with assigned mass
Each compound will be assigned a mass and the number of compounds having a
positive mass will be approximately maximized .
This is an implementation of the... | # Create mass balance problem
prob = solver . create_problem ( )
compound_set = _non_localized_compounds ( database )
mass_compounds = compound_set . difference ( zeromass )
# Define mass variables
m = prob . namespace ( mass_compounds , lower = 0 )
# Define z variables
z = prob . namespace ( mass_compounds , lower = 0... |
def calculate_entropy ( self , entropy_string ) :
"""Calculates the entropy of a string based on known frequency of
English letters .
Args :
entropy _ string : A str representing the string to calculate .
Returns :
A negative float with the total entropy of the string ( higher
is better ) .""" | total = 0
for char in entropy_string :
if char . isalpha ( ) :
prob = self . frequency [ char . lower ( ) ]
total += - math . log ( prob ) / math . log ( 2 )
logging . debug ( "Entropy score: {0}" . format ( total ) )
return total |
def is_connection_dropped ( conn ) : # Platform - specific
"""Returns True if the connection is dropped and should be closed .
: param conn :
: class : ` httplib . HTTPConnection ` object .
Note : For platforms like AppEngine , this will always return ` ` False ` ` to
let the platform handle connection recy... | sock = getattr ( conn , 'sock' , False )
if sock is False : # Platform - specific : AppEngine
return False
if sock is None : # Connection already closed ( such as by httplib ) .
return True
if not HAS_SELECT :
return False
try :
return bool ( wait_for_read ( sock , timeout = 0.0 ) )
except SelectorError... |
def check_output_format ( expected_formats ) :
"""Decorator for stream outputs that checks the format of the outputs after modifiers have been applied
: param expected _ formats : The expected output formats
: type expected _ formats : tuple , set
: return : the decorator""" | def output_format_decorator ( func ) :
def func_wrapper ( * args , ** kwargs ) :
self = args [ 0 ]
if self . output_format not in expected_formats :
raise ValueError ( "expected output format {}, got {}" . format ( 'doc_gen' , self . output_format ) )
return func ( * args , ** kw... |
def _make_tonnetz_matrix ( ) :
"""Return the tonnetz projection matrix .""" | pi = np . pi
chroma = np . arange ( 12 )
# Define each row of the transform matrix
fifth_x = r_fifth * ( np . sin ( ( 7 * pi / 6 ) * chroma ) )
fifth_y = r_fifth * ( np . cos ( ( 7 * pi / 6 ) * chroma ) )
minor_third_x = r_minor_thirds * ( np . sin ( 3 * pi / 2 * chroma ) )
minor_third_y = r_minor_thirds * ( np . cos (... |
def process_log_config_section ( config , log_config ) :
"""Processes the log section from a configuration data dict .
: param config : The config reference of the object that will hold the
configuration data from the config _ data .
: param log _ config : Log section from a config data dict .""" | if 'format' in log_config :
config . log [ 'format' ] = log_config [ 'format' ]
if 'level' in log_config :
config . log [ 'level' ] = log_level_from_string ( log_config [ 'level' ] ) |
def indication ( self , apdu ) :
"""This function is called after the device has bound a new transaction
and wants to start the process rolling .""" | if _debug :
ClientSSM . _debug ( "indication %r" , apdu )
# make sure we ' re getting confirmed requests
if ( apdu . apduType != ConfirmedRequestPDU . pduType ) :
raise RuntimeError ( "invalid APDU (1)" )
# save the request and set the segmentation context
self . set_segmentation_context ( apdu )
# if the max a... |
def _convert_to_border ( cls , border_dict ) :
"""Convert ` ` border _ dict ` ` to an openpyxl v2 Border object
Parameters
border _ dict : dict
A dict with zero or more of the following keys ( or their synonyms ) .
' left '
' right '
' top '
' bottom '
' diagonal '
' diagonal _ direction '
' ver... | from openpyxl . styles import Border
_border_key_map = { 'diagonalup' : 'diagonalUp' , 'diagonaldown' : 'diagonalDown' , }
border_kwargs = { }
for k , v in border_dict . items ( ) :
if k in _border_key_map :
k = _border_key_map [ k ]
if k == 'color' :
v = cls . _convert_to_color ( v )
if k i... |
def dateheure ( objet ) :
"""abstractRender d ' une date - heure datetime . datetime au format JJ / MM / AAAAàHH : mm""" | if objet :
return "{}/{}/{} à {:02}:{:02}" . format ( objet . day , objet . month , objet . year , objet . hour , objet . minute )
return "" |
def sailthru_http_request ( url , data , method , file_data = None , headers = None , request_timeout = 10 ) :
"""Perform an HTTP GET / POST / DELETE request""" | data = flatten_nested_hash ( data )
method = method . upper ( )
params , data = ( None , data ) if method == 'POST' else ( data , None )
sailthru_headers = { 'User-Agent' : 'Sailthru API Python Client %s; Python Version: %s' % ( '2.3.5' , platform . python_version ( ) ) }
if headers and isinstance ( headers , dict ) :
... |
def splitext ( path ) : # type : ( Text ) - > Tuple [ Text , Text ]
"""Split the extension from the path .
Arguments :
path ( str ) : A path to split .
Returns :
( str , str ) : A tuple containing the path and the extension .
Example :
> > > splitext ( ' baz . txt ' )
( ' baz ' , ' . txt ' )
> > > s... | parent_path , pathname = split ( path )
if pathname . startswith ( "." ) and pathname . count ( "." ) == 1 :
return path , ""
if "." not in pathname :
return path , ""
pathname , ext = pathname . rsplit ( "." , 1 )
path = join ( parent_path , pathname )
return path , "." + ext |
def update ( self , points , pointvol = 0. , vol_dec = 0.5 , vol_check = 2. , rstate = None , bootstrap = 0 , pool = None , mc_integrate = False ) :
"""Update the set of ellipsoids to bound the collection of points .
Parameters
points : ` ~ numpy . ndarray ` with shape ( npoints , ndim )
The set of points to ... | if rstate is None :
rstate = np . random
if not HAVE_KMEANS :
raise ValueError ( "scipy.cluster.vq.kmeans2 is required " "to compute ellipsoid decompositions." )
npoints , ndim = points . shape
# Calculate the bounding ellipsoid for the points , possibly
# enlarged to a minimum volume .
firstell = bounding_elli... |
def call_command ( self , cmd , * argv ) :
"""Runs a command .
: param cmd : command to run ( key at the registry )
: param argv : arguments that would be passed to the command""" | parser = self . get_parser ( )
args = [ cmd ] + list ( argv )
namespace = parser . parse_args ( args )
self . run_command ( namespace ) |
def process ( self ) :
"""Processes the Client queue , and passes the data to the respective
methods .
: return :""" | while self . running :
if self . _processor_lock . acquire ( blocking = False ) :
if self . ping_timer :
try :
self . _check_ping ( )
except TimeoutError :
log . exception ( "BitfinexWSS.ping(): TimedOut! (%ss)" % self . ping_timer )
except... |
def get_artist ( self ) :
""": returns : the : mod : ` Artist < deezer . resources . Artist > ` of the resource
: raises AssertionError : if the object is not album or track""" | # pylint : disable = E1101
assert isinstance ( self , ( Album , Track ) )
return self . client . get_artist ( self . artist . id ) |
def get_asset_from_edit_extension_draft ( self , publisher_name , draft_id , asset_type , extension_name , ** kwargs ) :
"""GetAssetFromEditExtensionDraft .
[ Preview API ]
: param str publisher _ name :
: param str draft _ id :
: param str asset _ type :
: param str extension _ name :
: rtype : object"... | route_values = { }
if publisher_name is not None :
route_values [ 'publisherName' ] = self . _serialize . url ( 'publisher_name' , publisher_name , 'str' )
if draft_id is not None :
route_values [ 'draftId' ] = self . _serialize . url ( 'draft_id' , draft_id , 'str' )
if asset_type is not None :
route_value... |
def get_server_list ( self , filter_text , max_servers = 10 , timeout = 20 ) :
"""Get list of servers . Works similiarly to : meth : ` query ` , but the response has more details .
: param filter _ text : filter for servers
: type filter _ text : str
: param max _ servers : ( optional ) number of servers to r... | resp , error = self . _um . send_and_wait ( "GameServers.GetServerList#1" , { "filter" : filter_text , "limit" : max_servers , } , timeout = 20 , )
if error :
raise error
if resp is None :
return None
resp = proto_to_dict ( resp )
if not resp :
return [ ]
else :
for server in resp [ 'servers' ] :
... |
def update_bbox ( self ) :
"""Recalculates the bbox region attribute for the entire file .
Useful after adding and / or removing features .
No need to use this method just for saving , because saving
automatically updates the bbox .""" | xmins , ymins , xmaxs , ymaxs = zip ( * ( feat . geometry . bbox for feat in self if feat . geometry . type != "Null" ) )
bbox = [ min ( xmins ) , min ( ymins ) , max ( xmaxs ) , max ( ymaxs ) ]
self . _data [ "bbox" ] = bbox |
def _itodq ( self , n ) :
"""Convert long to dotquad or hextet .""" | if self . v == 4 :
return '.' . join ( map ( str , [ ( n >> 24 ) & 0xff , ( n >> 16 ) & 0xff , ( n >> 8 ) & 0xff , n & 0xff , ] ) )
else :
n = '%032x' % n
return ':' . join ( n [ 4 * x : 4 * x + 4 ] for x in range ( 0 , 8 ) ) |
def _set_autocommit ( connection ) :
"""Make sure a connection is in autocommit mode .""" | if hasattr ( connection . connection , "autocommit" ) :
if callable ( connection . connection . autocommit ) :
connection . connection . autocommit ( True )
else :
connection . connection . autocommit = True
elif hasattr ( connection . connection , "set_isolation_level" ) :
connection . conn... |
def get_dag_configs ( self ) -> Dict [ str , Dict [ str , Any ] ] :
"""Returns configuration for each the DAG in factory
: returns : dict with configuration for dags""" | return { dag : self . config [ dag ] for dag in self . config . keys ( ) if dag != "default" } |
def collect_frames_for_random_starts ( storage_env , stacked_env , agent , frame_stack_size , random_starts_step_limit , log_every_steps = None ) :
"""Collects frames from real env for random starts of simulated env .""" | del frame_stack_size
storage_env . start_new_epoch ( 0 )
tf . logging . info ( "Collecting %d frames for random starts." , random_starts_step_limit )
rl_utils . run_rollouts ( stacked_env , agent , stacked_env . reset ( ) , step_limit = random_starts_step_limit , many_rollouts_from_each_env = True , log_every_steps = l... |
def iterdfs ( self , start , end = None , forward = True ) :
"""Collecting nodes in some depth first traversal .
The forward parameter specifies whether it is a forward or backward
traversal .""" | visited , stack = set ( [ start ] ) , deque ( [ start ] )
if forward :
get_edges = self . out_edges
get_next = self . tail
else :
get_edges = self . inc_edges
get_next = self . head
while stack :
curr_node = stack . pop ( )
yield curr_node
if curr_node == end :
break
for edge in ... |
def main ( ) :
"""Handles calling this module as a script
: return : None""" | log = logging . getLogger ( mod_logger + '.main' )
parser = argparse . ArgumentParser ( description = 'This Python module retrieves artifacts from Nexus.' )
parser . add_argument ( '-u' , '--url' , help = 'Nexus Server URL' , required = False )
parser . add_argument ( '-g' , '--groupId' , help = 'Group ID' , required =... |
def add_user ( self , recipient_email ) :
"""Add user to encryption""" | self . import_key ( emailid = recipient_email )
emailid_list = self . list_user_emails ( )
self . y = self . decrypt ( )
emailid_list . append ( recipient_email )
self . encrypt ( emailid_list = emailid_list ) |
def save_structure_to_file ( structure : JsonExportable , filename : str ) -> None :
"""Saves a : class : ` Post ` , : class : ` Profile ` or : class : ` StoryItem ` to a ' . json ' or ' . json . xz ' file such that it can
later be loaded by : func : ` load _ structure _ from _ file ` .
If the specified filenam... | json_structure = { 'node' : structure . _asdict ( ) , 'instaloader' : { 'version' : __version__ , 'node_type' : structure . __class__ . __name__ } }
compress = filename . endswith ( '.xz' )
if compress :
with lzma . open ( filename , 'wt' , check = lzma . CHECK_NONE ) as fp :
json . dump ( json_structure , ... |
def stop_socket ( self , conn_key ) :
"""Stop a websocket given the connection key
: param conn _ key : Socket connection key
: type conn _ key : string
: returns : connection key string if successful , False otherwise""" | if conn_key not in self . _conns :
return
# disable reconnecting if we are closing
self . _conns [ conn_key ] . factory = WebSocketClientFactory ( self . STREAM_URL + 'tmp_path' )
self . _conns [ conn_key ] . disconnect ( )
del ( self . _conns [ conn_key ] )
# check if we have a user stream socket
if len ( conn_key... |
def _construct_permission ( self , function , source_arn = None , source_account = None , suffix = "" , event_source_token = None ) :
"""Constructs the Lambda Permission resource allowing the source service to invoke the function this event
source triggers .
: returns : the permission resource
: rtype : model... | lambda_permission = LambdaPermission ( self . logical_id + 'Permission' + suffix , attributes = function . get_passthrough_resource_attributes ( ) )
try : # Name will not be available for Alias resources
function_name_or_arn = function . get_runtime_attr ( "name" )
except NotImplementedError :
function_name_or_... |
def patch ( self , resource_id ) :
"""Return an HTTP response object resulting from an HTTP PATCH call .
: returns : ` ` HTTP 200 ` ` if the resource already exists
: returns : ` ` HTTP 400 ` ` if the request is malformed
: returns : ` ` HTTP 404 ` ` if the resource is not found
: param resource _ id : The ... | resource = self . _resource ( resource_id )
error_message = is_valid_method ( self . __model__ , resource )
if error_message :
raise BadRequestException ( error_message )
if not request . json :
raise BadRequestException ( 'No JSON data received' )
resource . update ( request . json )
db . session ( ) . merge (... |
def _scatter ( sequence , n ) :
"""Scatters elements of ` ` sequence ` ` into ` ` n ` ` blocks .""" | chunklen = int ( math . ceil ( float ( len ( sequence ) ) / float ( n ) ) )
return [ sequence [ i * chunklen : ( i + 1 ) * chunklen ] for i in range ( n ) ] |
def _diagonalize ( self ) :
"""Performs SVD on covariance matrices and save left , right singular vectors and values in the model .
Parameters
scaling : None or string , default = None
Scaling to be applied to the VAMP modes upon transformation
* None : no scaling will be applied , variance of the singular ... | L0 = spd_inv_split ( self . C00 , epsilon = self . epsilon )
self . _rank0 = L0 . shape [ 1 ] if L0 . ndim == 2 else 1
Lt = spd_inv_split ( self . Ctt , epsilon = self . epsilon )
self . _rankt = Lt . shape [ 1 ] if Lt . ndim == 2 else 1
W = np . dot ( L0 . T , self . C0t ) . dot ( Lt )
from scipy . linalg import svd
A... |
def start_parallel ( self ) :
"""Initialize all queues and start the worker processes and the log
thread .""" | self . num_processes = get_num_processes ( )
self . task_queue = multiprocessing . Queue ( maxsize = Q_MAX_SIZE )
self . result_queue = multiprocessing . Queue ( )
self . log_queue = multiprocessing . Queue ( )
# Used to signal worker processes when a result is found that allows
# the computation to terminate early .
s... |
def load_spectrum ( path , smoothing = 181 , DF = - 8. ) :
"""Load a Phoenix model atmosphere spectrum .
path : string
The file path to load .
smoothing : integer
Smoothing to apply . If None , do not smooth . If an integer , smooth with a
Hamming window . Otherwise , the variable is assumed to be a diffe... | try :
ang , lflam = np . loadtxt ( path , usecols = ( 0 , 1 ) ) . T
except ValueError : # In some files , the numbers in the first columns fill up the
# whole 12 - character column width , and are given in exponential
# notation with a ' D ' character , so we must be more careful :
with open ( path , 'rb' ) as ... |
def get_bids_examples ( data_dir = None , url = None , resume = True , verbose = 1 , variant = 'BIDS-examples-1-1.0.0-rc3u5' ) :
"""Download BIDS - examples - 1""" | warn ( DEPRECATION_MSG )
variant = 'BIDS-examples-1-1.0.0-rc3u5' if variant not in BIDS_EXAMPLES else variant
if url is None :
url = BIDS_EXAMPLES [ variant ] [ 0 ]
md5 = BIDS_EXAMPLES [ variant ] [ 1 ]
return fetch_file ( variant , url , data_dir , resume = resume , verbose = verbose , md5sum = md5 ) |
def get_return_list ( self , data ) :
"""Get the list of returned values .
The list contains tuples ( name = None , desc , type = None )
: param data : the data to proceed""" | return_list = [ ]
lst = self . get_list_key ( data , 'return' )
for l in lst :
name , desc , rtype = l
if l [ 2 ] is None :
rtype = l [ 0 ]
name = None
desc = desc . strip ( )
return_list . append ( ( name , desc , rtype ) )
return return_list |
def put ( self , request , * args , ** kwargs ) :
"""custom put method to support django - reversion""" | with reversion . create_revision ( ) :
reversion . set_user ( request . user )
reversion . set_comment ( 'changed through the RESTful API from ip %s' % request . META [ 'REMOTE_ADDR' ] )
return self . update ( request , * args , ** kwargs ) |
def handle_api_errors ( self , status_code , json_data ) :
"""This method parses all the HTTP responses sent by the REST API and
raises exceptions if required . Basically tries to find responses with
this format :
' error ' : [ ' The domain foo . com already exists . ' ]
Or this other :
" scans " : {
" ... | error_list = [ ]
if 'error' in json_data and len ( json_data ) == 1 and isinstance ( json_data , dict ) and isinstance ( json_data [ 'error' ] , list ) :
error_list = json_data [ 'error' ]
elif status_code == 400 :
for main_error_key in json_data :
for sub_error_key in json_data [ main_error_key ] :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.