signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def users ( self , proc ) :
"""Searches for all users running a given command .
Returns :
dict : each username as a key to a list of PIDs ( as strings ) that
are running the given process .
` ` { } ` ` if neither ` ` USER ` ` nor ` ` UID ` ` is found or ` ` proc ` ` is not found .
. . note : :
' proc ' ... | ret = { }
if self . first_column in [ 'USER' , 'UID' ] :
for row in self . data :
if proc == row [ self . command_name ] :
if row [ self . first_column ] not in ret :
ret [ row [ self . first_column ] ] = [ ]
ret [ row [ self . first_column ] ] . append ( row [ "PID" ... |
def _timestamp ( ) :
"""Return a timestamp with microsecond precision .""" | moment = time . time ( )
moment_us = repr ( moment ) . split ( '.' ) [ 1 ]
return time . strftime ( "%Y-%m-%d-%H-%M-%S-{}" . format ( moment_us ) , time . gmtime ( moment ) ) |
def _get_upper_bound ( self ) :
r"""Return an upper bound on the eigenvalues of the Laplacian .""" | if self . lap_type == 'normalized' :
return 2
# Equal iff the graph is bipartite .
elif self . lap_type == 'combinatorial' :
bounds = [ ]
# Equal for full graphs .
bounds += [ self . n_vertices * np . max ( self . W ) ]
# Gershgorin circle theorem . Equal for regular bipartite graphs .
# Spe... |
def get_all_bundle_tasks ( self , bundle_ids = None , filters = None ) :
"""Retrieve current bundling tasks . If no bundle id is specified , all
tasks are retrieved .
: type bundle _ ids : list
: param bundle _ ids : A list of strings containing identifiers for
previously created bundling tasks .
: type f... | params = { }
if bundle_ids :
self . build_list_params ( params , bundle_ids , 'BundleId' )
if filters :
self . build_filter_params ( params , filters )
return self . get_list ( 'DescribeBundleTasks' , params , [ ( 'item' , BundleInstanceTask ) ] , verb = 'POST' ) |
def _tab_type ( self ) :
"""Private method to define the tab type""" | with open ( self . abspath ) as fobj :
contents = fobj . readlines ( )
for line in contents :
if 'COMPONENTS' in line :
return 'keyword'
else :
return 'fixed' |
def _write_bin ( self , stream , byte_order ) :
'''Save a PLY element to a binary PLY file . The element may
contain list properties .''' | for rec in self . data :
for prop in self . properties :
prop . _write_bin ( rec [ prop . name ] , stream , byte_order ) |
def compile_authors ( authors ) :
"""Compiles authors " Last , First " into a single list
: param list authors : Raw author data retrieved from doi . org
: return list : Author objects""" | author_list = [ ]
for person in authors :
author_list . append ( { 'name' : person [ 'family' ] + ", " + person [ 'given' ] } )
return author_list |
def get_map_title ( hazard , exposure , hazard_category ) :
"""Helper to get map title .
: param hazard : A hazard definition .
: type hazard : dict
: param exposure : An exposure definition .
: type exposure : dict
: param hazard _ category : A hazard category definition .
: type hazard _ category : di... | if hazard == hazard_generic :
map_title = tr ( '{exposure_name} affected' ) . format ( exposure_name = exposure [ 'name' ] )
else :
if hazard_category == hazard_category_single_event :
map_title = tr ( '{exposure_name} affected by {hazard_name} event' ) . format ( exposure_name = exposure [ 'name' ] , h... |
def _verify_or_create_domain ( self ) :
"""Verify that a domain with the name self . domain exists . Else create it .
: return :""" | # Get all domains registered with the user
r = requests . get ( url = self . server + "/domains" , auth = ( self . username , self . password ) , headers = self . headers , json = self . data )
if r . ok :
names = [ ]
d = r . json ( )
rdata = d [ "data" ]
if rdata :
for d in rdata :
... |
def kabsch_rmsd ( P , Q , translate = False ) :
"""Rotate matrix P unto Q using Kabsch algorithm and calculate the RMSD .
Parameters
P : array
( N , D ) matrix , where N is points and D is dimension .
Q : array
( N , D ) matrix , where N is points and D is dimension .
translate : bool
Use centroids to... | if translate :
Q = Q - centroid ( Q )
P = P - centroid ( P )
P = kabsch_rotate ( P , Q )
return rmsd ( P , Q ) |
def from_surface ( renderer , surface ) :
"""Create a texture from an existing surface .
Args :
surface ( Surface ) : The surface containing pixel data used to fill the texture .
Returns :
Texture : A texture containing the pixels from surface .
Raises :
SDLError : If an error is encountered .""" | texture = object . __new__ ( Texture )
texture . _ptr = check_ptr_err ( lib . SDL_CreateTextureFromSurface ( renderer . _ptr , surface . _ptr ) )
return texture |
def _get_chromecast_from_host ( host , tries = None , retry_wait = None , timeout = None , blocking = True ) :
"""Creates a Chromecast object from a zeroconf host .""" | # Build device status from the mDNS info , this information is
# the primary source and the remaining will be fetched
# later on .
ip_address , port , uuid , model_name , friendly_name = host
_LOGGER . debug ( "_get_chromecast_from_host %s" , host )
cast_type = CAST_TYPES . get ( model_name . lower ( ) , CAST_TYPE_CHRO... |
def CheckHashes ( self , hashes , unused_external = True ) :
"""Checks a list of hashes for presence in the store .
Only unique sha1 hashes are checked , if there is duplication in the hashes
input it is the caller ' s responsibility to maintain any necessary mappings .
Args :
hashes : A list of Hash object... | hash_map = { }
for hsh in hashes :
if hsh . HasField ( "sha1" ) :
hash_urn = self . PATH . Add ( str ( hsh . sha1 ) )
logging . debug ( "Checking URN %s" , str ( hash_urn ) )
hash_map [ hash_urn ] = hsh
for metadata in aff4 . FACTORY . Stat ( list ( hash_map ) ) :
yield metadata [ "urn" ... |
def zoneToRegion ( zone ) :
"""Get a region ( e . g . us - west - 2 ) from a zone ( e . g . us - west - 1c ) .""" | from toil . lib . context import Context
return Context . availability_zone_re . match ( zone ) . group ( 1 ) |
def get_xy_environment ( self , xy ) :
'''Get manager address for the environment which should have the agent
with given * xy * coordinate , or None if no such environment is in this
multi - environment .''' | x = xy [ 0 ]
y = xy [ 1 ]
for origin , addr in self . _slave_origins :
ox = origin [ 0 ]
oy = origin [ 1 ]
if ox <= x < ox + self . gs [ 0 ] and oy <= y < oy + self . gs [ 1 ] :
return addr
return None |
def _on_connection_open ( self , connection ) :
"""Callback invoked when the connection is successfully established .
Args :
connection ( pika . connection . SelectConnection ) : The newly - estabilished
connection .""" | _log . info ( "Successfully opened connection to %s" , connection . params . host )
self . _channel = connection . channel ( on_open_callback = self . _on_channel_open ) |
def write_min_config ( self , filename , header = "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n" ) :
"""Writes out a " minimal " configuration file , omitting symbols whose value
matches their default value . The format matches the one produced by
' make savedefconfig ' .
The resultin... | with self . _open ( filename , "w" ) as f :
f . write ( header )
for sym in self . unique_defined_syms : # Skip symbols that cannot be changed . Only check
# non - choice symbols , as selects don ' t affect choice
# symbols .
if not sym . choice and sym . visibility <= expr_value ( sym . rev_dep... |
def op_list_apps ( self ) :
"""Prints out and returns a list of known applications .
: rtype : list
: return : list of applications""" | self . logger . info ( 'Listing known applications ...' )
apps = self . get_apps ( )
for app in apps :
self . logger . info ( 'Found `%s`' % app )
else :
self . logger . info ( '\nDONE. No applications found in `%s` directory.\n' % APPS_DIRNAME )
return apps |
def parse_assign_target ( self , with_tuple = True , name_only = False , extra_end_rules = None , with_namespace = False ) :
"""Parse an assignment target . As Jinja2 allows assignments to
tuples , this function can parse all allowed assignment targets . Per
default assignments to tuples are parsed , that can b... | if with_namespace and self . stream . look ( ) . type == 'dot' :
token = self . stream . expect ( 'name' )
next ( self . stream )
# dot
attr = self . stream . expect ( 'name' )
target = nodes . NSRef ( token . value , attr . value , lineno = token . lineno )
elif name_only :
token = self . strea... |
def lookup_hostname ( self , ip ) :
"""Look up a lease object with given ip address and return the associated client hostname .
@ type ip : str
@ rtype : str or None
@ raises ValueError :
@ raises OmapiError :
@ raises OmapiErrorNotFound : if no lease object with the given ip address could be found
@ ra... | res = self . lookup_by_lease ( ip = ip )
if "client-hostname" not in res :
raise OmapiErrorAttributeNotFound ( )
return res [ "client-hostname" ] . decode ( 'utf-8' ) |
def launch ( thing , title = False ) :
"""analyze a thing , create a nice HTML document , and launch it .""" | html = htmlFromThing ( thing , title = title )
if not html :
print ( "no HTML was generated." )
return
fname = "%s/%s.html" % ( tempfile . gettempdir ( ) , str ( time . time ( ) ) )
with open ( fname , 'w' ) as f :
f . write ( html )
webbrowser . open ( fname ) |
def index_based_complete ( self , text : str , line : str , begidx : int , endidx : int , index_dict : Mapping [ int , Union [ Iterable , Callable ] ] , all_else : Union [ None , Iterable , Callable ] = None ) -> List [ str ] :
"""Tab completes based on a fixed position in the input string
: param text : the stri... | # Get all tokens through the one being completed
tokens , _ = self . tokens_for_completion ( line , begidx , endidx )
if not tokens :
return [ ]
matches = [ ]
# Get the index of the token being completed
index = len ( tokens ) - 1
# Check if token is at an index in the dictionary
if index in index_dict :
match_... |
def get_default_config ( self ) :
"""Returns the default collector settings""" | config = super ( VMSDomsCollector , self ) . get_default_config ( )
config . update ( { 'path' : 'vms' } )
return config |
def create_api_v4_ipv4 ( self ) :
"""Get an instance of Api V4 IPv4 services facade .""" | return ApiV4IPv4 ( self . networkapi_url , self . user , self . password , self . user_ldap ) |
def collect_results ( ) :
"""Runs all platforms / backends / benchmarks and returns as list of
BenchmarkResults , sorted by benchmark and time taken .""" | results = [ ]
for exe , backendname in EXE_BACKEND_MATRIX :
results . extend ( benchmark_process_and_backend ( exe , backendname ) )
results . extend ( benchmark_go ( ) )
results . sort ( key = lambda br : ( br . benchmark , float ( br . time ) , br . platform , br . backend ) )
return results |
def run ( self , callback = None , limit = 0 ) :
"""Start pcap ' s loop over the interface , calling the given callback for each packet
: param callback : a function receiving ( win _ pcap , param , header , pkt _ data ) for each packet intercepted
: param limit : how many packets to capture ( A value of - 1 or... | if self . _handle is None :
raise self . DeviceIsNotOpen ( )
# Set new callback
self . _callback = callback
# Run loop with callback wrapper
wtypes . pcap_loop ( self . _handle , limit , self . _callback_wrapper , None ) |
def _fqdn ( o , oset = True , recheck = False , pmodule = None ) :
"""Returns the fully qualified name of the object .
Args :
o ( type ) : instance of the object ' s type .
oset ( bool ) : when True , the fqdn will also be set on the object as attribute
` _ _ fqdn _ _ ` .
recheck ( bool ) : for sub - clas... | if id ( o ) in _set_failures or o is None :
return None
if recheck or not _safe_hasattr ( o , "__fqdn__" ) :
import inspect
if not hasattr ( o , "__name__" ) :
msg . warn ( "Skipped object {}: no __name__ attribute." . format ( o ) , 3 )
return
result = None
if hasattr ( o , "__acorn... |
def __open ( self , url , headers = None , data = None , baseurl = "" ) :
"""Use raw urlopen command .""" | headers = headers or { }
if not baseurl :
baseurl = self . baseurl
req = Request ( "%s%s" % ( baseurl , url ) , headers = headers )
_LOGGER . debug ( url )
try :
req . data = urlencode ( data ) . encode ( 'utf-8' )
except TypeError :
pass
opener = build_opener ( )
try :
resp = opener . open ( req )
... |
def invalidate_and_update_screen ( self , screen_id ) :
"""Redraw the specified VM screen .
in screen _ id of type int
The guest screen to redraw .""" | if not isinstance ( screen_id , baseinteger ) :
raise TypeError ( "screen_id can only be an instance of type baseinteger" )
self . _call ( "invalidateAndUpdateScreen" , in_p = [ screen_id ] ) |
def makeLUTfromCTF ( sclist , N = None ) :
"""Use a Color Transfer Function to generate colors in a vtk lookup table .
See ` here < http : / / www . vtk . org / doc / nightly / html / classvtkColorTransferFunction . html > ` _ .
: param list sclist : a list in the form ` ` [ ( scalar1 , [ r , g , b ] ) , ( scal... | ctf = vtk . vtkColorTransferFunction ( )
ctf . SetColorSpaceToDiverging ( )
for sc in sclist :
scalar , col = sc
r , g , b = getColor ( col )
ctf . AddRGBPoint ( scalar , r , g , b )
if N is None :
N = len ( sclist )
lut = vtk . vtkLookupTable ( )
lut . SetNumberOfTableValues ( N )
lut . Build ( )
for i... |
def get_exptime ( self , img ) :
"""Obtain EXPTIME""" | header = self . get_header ( img )
if 'EXPTIME' in header . keys ( ) :
etime = header [ 'EXPTIME' ]
elif 'EXPOSED' in header . keys ( ) :
etime = header [ 'EXPOSED' ]
else :
etime = 1.0
return etime |
def get_form ( self , form_class = None ) :
form = super ( LineAlbaranUpdate , self ) . get_form ( form_class )
raise Exception ( "Cambiar ProductStock por ProductUnique" )
"""ps = ProductStock . objects . filter ( line _ albaran = self . object ) . first ( )
if ps :
# initial field
form . fields [ ' ... | return form |
def _rpc ( self , method , * args ) :
"""Sends an rpc to the app .
Args :
method : str , The name of the method to execute .
args : any , The args of the method .
Returns :
The result of the rpc .
Raises :
ProtocolError : Something went wrong with the protocol .
ApiError : The rpc went through , how... | with self . _lock :
apiid = next ( self . _counter )
data = { 'id' : apiid , 'method' : method , 'params' : args }
request = json . dumps ( data )
self . _client_send ( request )
response = self . _client_receive ( )
if not response :
raise ProtocolError ( self . _ad , ProtocolError . NO_RESPONS... |
def SLIT_DIFFRACTION ( x , g ) :
"""Instrumental ( slit ) function .""" | y = zeros ( len ( x ) )
index_zero = x == 0
index_nonzero = ~ index_zero
dk_ = pi / g
x_ = dk_ * x [ index_nonzero ]
w_ = sin ( x_ )
r_ = w_ ** 2 / x_ ** 2
y [ index_zero ] = 1
y [ index_nonzero ] = r_ / g
return y |
def operator_complexity ( self ) :
"""Operator complexity of this multigrid hierarchy .
Defined as :
Number of nonzeros in the matrix on all levels /
Number of nonzeros in the matrix on the finest level""" | return sum ( [ level . A . nnz for level in self . levels ] ) / float ( self . levels [ 0 ] . A . nnz ) |
def use_kwargs ( args , locations = None , inherit = None , apply = None , ** kwargs ) :
"""Inject keyword arguments from the specified webargs arguments into the
decorated view function .
Usage :
. . code - block : : python
from marshmallow import fields
@ use _ kwargs ( { ' name ' : fields . Str ( ) , '... | kwargs . update ( { 'locations' : locations } )
def wrapper ( func ) :
options = { 'args' : args , 'kwargs' : kwargs , }
annotate ( func , 'args' , [ options ] , inherit = inherit , apply = apply )
return activate ( func )
return wrapper |
async def emit ( self , event , data , namespace = None , room = None , skip_sid = None , callback = None , ** kwargs ) :
"""Emit a message to a single client , a room , or all the clients
connected to the namespace .
This method takes care or propagating the message to all the servers
that are connected thro... | if kwargs . get ( 'ignore_queue' ) :
return await super ( ) . emit ( event , data , namespace = namespace , room = room , skip_sid = skip_sid , callback = callback )
namespace = namespace or '/'
if callback is not None :
if self . server is None :
raise RuntimeError ( 'Callbacks can only be issued from ... |
def normalize ( A , axis = None , inplace = False ) :
"""Normalize the input array so that it sums to 1.
Parameters
A : array , shape ( n _ samples , n _ features )
Non - normalized input data .
axis : int
Dimension along which normalization is performed .
Returns
normalized _ A : array , shape ( n _ ... | if not inplace :
A = A . copy ( )
A += np . finfo ( float ) . eps
Asum = A . sum ( axis )
if axis and A . ndim > 1 : # Make sure we don ' t divide by zero .
Asum [ Asum == 0 ] = 1
shape = list ( A . shape )
shape [ axis ] = 1
Asum . shape = shape
A /= Asum
return A |
def ssn ( self ) :
"""Ukrainian " Реєстраційний номер облікової картки платника податків "
also known as " Ідентифікаційний номер фізичної особи " .""" | digits = [ ]
# Number of days between 1899-12-31 and a birth date
for digit in str ( ( self . generator . date_object ( ) - date ( 1899 , 12 , 31 ) ) . days ) :
digits . append ( int ( digit ) )
# Person ' s sequence number
for _ in range ( 4 ) :
digits . append ( self . random_int ( 0 , 9 ) )
checksum = ( digi... |
def get_chain ( self , group_name ) :
"""Provides the component and group names for an analysis chain .
: param group _ name : The group name of the last step in the analysis
chain e . g . ' Basecall _ 1D _ 000'
: returns : A list of component - name / group - name pairs ( tuples ) . This
will include each ... | self . assert_open ( )
endgroup = 'Analyses/{}' . format ( group_name )
attr = self . handle [ endgroup ] . attrs
if 'component' in attr :
component = attr [ 'component' ]
else :
component = LEGACY_COMPONENT_NAMES [ group_name [ : - 4 ] ]
chain = deque ( )
chain . append ( ( component , group_name ) )
groups_to... |
def _getClassDefinition ( self , ref ) :
"""Reads class definition from the stream .""" | is_ref = ref & REFERENCE_BIT == 0
ref >>= 1
if is_ref :
class_def = self . context . getClassByReference ( ref )
return class_def
name = self . readBytes ( )
alias = None
if name == '' :
name = pyamf . ASObject
try :
alias = pyamf . get_class_alias ( name )
except pyamf . UnknownClassAlias :
if self... |
def check_id_has_no_blanks ( self , ds ) :
'''Check if there are blanks in the id field
: param netCDF4 . Dataset ds : An open netCDF dataset''' | if not hasattr ( ds , u'id' ) :
return
if ' ' in getattr ( ds , u'id' ) :
return Result ( BaseCheck . MEDIUM , False , 'no_blanks_in_id' , msgs = [ u'There should be no blanks in the id field' ] )
else :
return Result ( BaseCheck . MEDIUM , True , 'no_blanks_in_id' , msgs = [ ] ) |
def run_head ( self , proposals , stage ) :
"""Args :
proposals : BoxProposals
stage : 0 , 1 , 2
Returns :
FastRCNNHead
Nx4 , updated boxes""" | reg_weights = tf . constant ( cfg . CASCADE . BBOX_REG_WEIGHTS [ stage ] , dtype = tf . float32 )
pooled_feature = self . roi_func ( proposals . boxes )
# N , C , S , S
pooled_feature = self . scale_gradient ( pooled_feature )
head_feature = self . fastrcnn_head_func ( 'head' , pooled_feature )
label_logits , box_logit... |
def plotTimeline ( dataTask , filename ) :
"""Build a timeline""" | fig = plt . figure ( )
ax = fig . gca ( )
worker_names = [ x for x in dataTask . keys ( ) if "broker" not in x ]
min_time = getMinimumTime ( dataTask )
ystep = 1. / ( len ( worker_names ) + 1 )
y = 0
for worker , vals in dataTask . items ( ) :
if "broker" in worker :
continue
y += ystep
if hasattr (... |
def Reverse ( self , copy = False ) :
"""Reverse the order of the points""" | numPoints = self . GetN ( )
if copy :
revGraph = self . Clone ( )
else :
revGraph = self
X = self . GetX ( )
EXlow = self . GetEXlow ( )
EXhigh = self . GetEXhigh ( )
Y = self . GetY ( )
EYlow = self . GetEYlow ( )
EYhigh = self . GetEYhigh ( )
for i in range ( numPoints ) :
index = numPoints - 1 - i
re... |
def put ( local , remote ) :
"""Put a file or folder and its contents on the board .
Put will upload a local file or folder to the board . If the file already
exists on the board it will be overwritten with no warning ! You must pass
at least one argument which is the path to the local file / folder to
uplo... | # Use the local filename if no remote filename is provided .
if remote is None :
remote = os . path . basename ( os . path . abspath ( local ) )
# Check if path is a folder and do recursive copy of everything inside it .
# Otherwise it ' s a file and should simply be copied over .
if os . path . isdir ( local ) : #... |
def attach_foreignkey ( objects , field , related = [ ] , database = None ) :
"""Shortcut method which handles a pythonic LEFT OUTER JOIN .
` ` attach _ foreignkey ( posts , Post . thread ) ` `
Works with both ForeignKey and OneToOne ( reverse ) lookups .""" | if not objects :
return
if database is None :
database = list ( objects ) [ 0 ] . _state . db
is_foreignkey = isinstance ( field , SingleRelatedObjectDescriptor )
if not is_foreignkey :
field = field . field
accessor = '_%s_cache' % field . name
model = field . rel . to
lookup = 'pk'
column ... |
def sort ( self , column_name = None , reverse = False ) :
"""Sort rows in this table , preserving a record of how that
sorting is done in TableFu . options [ ' sorted _ by ' ]""" | if not column_name and self . options . has_key ( 'sorted_by' ) :
column_name = self . options [ 'sorted_by' ] . keys ( ) [ 0 ]
if column_name not in self . default_columns :
raise ValueError ( "%s isn't a column in this table" % column_name )
index = self . default_columns . index ( column_name )
self . table ... |
def mavlink_packet ( self , m ) :
'''handle an incoming mavlink packet''' | # do nothing if not caibrating
if ( self . calibrating == False ) :
return
if m . get_type ( ) == 'RC_CHANNELS_RAW' :
for i in range ( 1 , self . num_channels + 1 ) :
v = getattr ( m , 'chan%u_raw' % i )
if self . get_cal_min ( i ) > v :
self . set_cal_min ( i , v )
self ... |
def error_handler ( _ , err , arg ) :
"""Update the mutable integer ` arg ` with the error code .""" | arg . value = err . error
return libnl . handlers . NL_STOP |
def host2id ( self , hostname ) :
"""return member id by hostname""" | for key , value in self . server_map . items ( ) :
if value == hostname :
return key |
def cli ( env , abuse , address1 , address2 , city , company , country , firstname , lastname , postal , public , state ) :
"""Edit the RWhois data on the account .""" | mgr = SoftLayer . NetworkManager ( env . client )
update = { 'abuse_email' : abuse , 'address1' : address1 , 'address2' : address2 , 'company_name' : company , 'city' : city , 'country' : country , 'first_name' : firstname , 'last_name' : lastname , 'postal_code' : postal , 'state' : state , 'private_residence' : publi... |
def execute_lite ( self , instructions , context = None ) :
"""Execute a list of instructions . It does not support loops .""" | if context :
self . __cpu . registers = dict ( context )
for instr in instructions :
self . __execute_one ( instr )
return dict ( self . __cpu . registers ) , self . __mem |
def encode ( self , value ) :
"""Return a bytestring representation of the value""" | if isinstance ( value , Token ) :
return b ( value . value )
if isinstance ( value , bytes ) :
return value
elif isinstance ( value , ( int , long ) ) :
value = b ( str ( value ) )
elif isinstance ( value , float ) :
value = repr ( value )
elif not isinstance ( value , basestring ) :
value = str ( v... |
def text_has_been_edited ( self , text ) :
"""Find text has been edited ( this slot won ' t be triggered when
setting the search pattern combo box text programmatically )""" | self . find ( changed = True , forward = True , start_highlight_timer = True ) |
def splitclass ( classofdevice ) :
"""Splits the given class of device to return a 3 - item tuple with the
major service class , major device class and minor device class values .
These values indicate the device ' s major services and the type of the
device ( e . g . mobile phone , laptop , etc . ) . If you ... | if not isinstance ( classofdevice , int ) :
try :
classofdevice = int ( classofdevice )
except ( TypeError , ValueError ) :
raise TypeError ( "Given device class '%s' cannot be split" % str ( classofdevice ) )
data = classofdevice >> 2
# skip over the 2 " format " bits
service = data >> 11
major... |
async def message_from_token ( self , token : Text , payload : Any ) -> Optional [ BaseMessage ] :
"""There is two ways of getting a FB user : either with a signed request or
either with a platform token . Both are tried out .""" | methods = [ self . _message_from_sr , self . _message_from_token , ]
for method in methods :
msg = method ( token , payload )
if msg :
return msg |
def set_temperature ( self , max_set_point = None ) :
""": param max _ set _ point : a float for the max set point value in celsius
: return : nothing""" | desired_state = { }
if max_set_point :
desired_state [ 'max_set_point' ] = max_set_point
response = self . api_interface . set_device_state ( self , { "desired_state" : desired_state } )
self . _update_state_from_response ( response ) |
def sftp ( task : Task , src : str , dst : str , action : str , dry_run : Optional [ bool ] = None ) -> Result :
"""Transfer files from / to the device using sftp protocol
Example : :
nornir . run ( files . sftp ,
action = " put " ,
src = " README . md " ,
dst = " / tmp / README . md " )
Arguments :
d... | dry_run = task . is_dry_run ( dry_run )
actions = { "put" : put , "get" : get }
client = task . host . get_connection ( "paramiko" , task . nornir . config )
scp_client = SCPClient ( client . get_transport ( ) )
sftp_client = paramiko . SFTPClient . from_transport ( client . get_transport ( ) )
files_changed = actions ... |
def writeFile ( self , directory = None ) :
"""Writes back the file to a temporary path ( optionaly specified )""" | if directory : # If a directory was specified
full_path = os . path . join ( directory , self . filename )
with open ( full_path , 'wb' ) as f :
f . write ( pickle . loads ( self . data ) . read ( ) )
return full_path
# if no directory was specified , create a temporary file
this_file = tempfile . N... |
def open ( self , path , encoding = None , use_cached_encoding = True ) :
"""Open a file and set its content on the editor widget .
pyqode does not try to guess encoding . It ' s up to the client code to
handle encodings . You can either use a charset detector to detect
encoding or rely on a settings in your ... | ret_val = False
if encoding is None :
encoding = locale . getpreferredencoding ( )
self . opening = True
settings = Cache ( )
self . _path = path
# get encoding from cache
if use_cached_encoding :
try :
cached_encoding = settings . get_file_encoding ( path , preferred_encoding = encoding )
except Ke... |
def view ( route : str ) :
"""Retrieves the contents of the file specified by the view route if it
exists .""" | project = cauldron . project . get_internal_project ( )
results_path = project . results_path if project else None
if not project or not results_path :
return '' , 204
path = os . path . join ( results_path , route )
if not os . path . exists ( path ) :
return '' , 204
return flask . send_file ( path , mimetype... |
def _add_subscribers_for_type ( self , callback_type , subscribers , callbacks , ** kwargs ) :
'''add a done / queued / progress callback to the appropriate list''' | for subscriber in subscribers :
callback_name = 'on_' + callback_type
if hasattr ( subscriber , callback_name ) :
_function = functools . partial ( getattr ( subscriber , callback_name ) , ** kwargs )
callbacks . append ( _function ) |
def __decode_data_time ( self , payload ) :
"""Extract time and decode payload ( based on mime type ) from payload . Applies to E _ FEEDDATA and E _ RECENTDATA .
Returns tuple of data , mime , time .""" | data , mime = self . __bytes_to_share_data ( payload )
try :
time = datetime . strptime ( payload . get ( P_TIME ) , self . __share_time_fmt )
except ( ValueError , TypeError ) :
logger . warning ( 'Share payload from container has invalid timestamp (%s), will use naive local time' , payload . get ( P_TIME ) )
... |
def set_last_build_date ( self ) :
"""Parses last build date and set value""" | try :
self . last_build_date = self . soup . find ( 'lastbuilddate' ) . string
except AttributeError :
self . last_build_date = None |
def generate_null_timeseries ( self , ts , mu , sigma ) :
"""Generate a time series with a given mu and sigma . This serves as the
NULL distribution .""" | l = len ( ts )
return np . random . normal ( mu , sigma , l ) |
def _partial_corr ( self , x = None , y = None , covar = None , x_covar = None , y_covar = None , tail = 'two-sided' , method = 'pearson' ) :
"""Partial and semi - partial correlation .""" | stats = partial_corr ( data = self , x = x , y = y , covar = covar , x_covar = x_covar , y_covar = y_covar , tail = tail , method = method )
return stats |
def partial_trace ( self , qubits : Qubits ) -> 'QubitVector' :
"""Return the partial trace over some subset of qubits""" | N = self . qubit_nb
R = self . rank
if R == 1 :
raise ValueError ( 'Cannot take trace of vector' )
new_qubits : List [ Qubit ] = list ( self . qubits )
for q in qubits :
new_qubits . remove ( q )
if not new_qubits :
raise ValueError ( 'Cannot remove all qubits with partial_trace.' )
indices = [ self . qubit... |
def multihead_attention ( queries , keys , scope = "multihead_attention" , num_units = None , num_heads = 4 , dropout_rate = 0 , is_training = True , causality = False ) :
'''Applies multihead attention .
Args :
queries : A 3d tensor with shape of [ N , T _ q , C _ q ] .
keys : A 3d tensor with shape of [ N ,... | global look5
with tf . variable_scope ( scope ) : # Set the fall back option for num _ units
if num_units is None :
num_units = queries . get_shape ( ) . as_list ( ) [ - 1 ]
Q_ = [ ]
K_ = [ ]
V_ = [ ]
for head_i in range ( num_heads ) :
Q = tf . layers . dense ( queries , num_units /... |
def pday ( dayfmt ) :
"""P the day
> > > print ( pday ( ' 2012-08-24 ' ) )
Friday the 24th""" | year , month , day = map ( int , dayfmt . split ( '-' ) )
return '{day} the {number}' . format ( day = calendar . day_name [ calendar . weekday ( year , month , day ) ] , number = inflect . engine ( ) . ordinal ( day ) , ) |
def calculate_size ( name , timeout_millis ) :
"""Calculates the request payload size""" | data_size = 0
data_size += calculate_size_str ( name )
data_size += LONG_SIZE_IN_BYTES
return data_size |
def prodmix ( I , K , a , p , epsilon , LB ) :
"""prodmix : robust production planning using soco
Parameters :
I - set of materials
K - set of components
a [ i ] [ k ] - coef . matrix
p [ i ] - price of material i
LB [ k ] - amount needed for k
Returns a model , ready to be solved .""" | model = Model ( "robust product mix" )
x , rhs = { } , { }
for i in I :
x [ i ] = model . addVar ( vtype = "C" , name = "x(%s)" % i )
for k in K :
rhs [ k ] = model . addVar ( vtype = "C" , name = "rhs(%s)" % k )
model . addCons ( quicksum ( x [ i ] for i in I ) == 1 )
for k in K :
model . addCons ( rhs [ k... |
def _init_trace ( self , n , color , style , linewidth = 2.5 , zorder = None , marker = None , markersize = 6 ) :
"""used for building set of traces""" | while n >= len ( self . traces ) :
self . traces . append ( LineProperties ( ) )
line = self . traces [ n ]
label = "trace %i" % ( n + 1 )
line . label = label
line . drawstyle = 'default'
if zorder is None :
zorder = 5 * ( n + 1 )
line . zorder = zorder
if color is not None :
line . color = color
if style ... |
def update_resources ( Cnt ) :
'''Update resources . py with the paths to the new installed apps .''' | # list of path names which will be saved
key_list = [ 'PATHTOOLS' , 'RESPATH' , 'REGPATH' , 'DCM2NIIX' , 'HMUDIR' ]
# get the local path to NiftyPET resources . py
path_resources = cs . path_niftypet_local ( )
resources_file = os . path . join ( path_resources , 'resources.py' )
# update resources . py
if os . path . i... |
def eci2geodetic ( eci : np . ndarray , t : datetime , useastropy : bool = True ) -> Tuple [ float , float , float ] :
"""convert ECI to geodetic coordinates
Parameters
eci : tuple of float
[ meters ] Nx3 target ECI location ( x , y , z )
t : datetime . datetime , float
length N vector of datetime OR gree... | ecef = np . atleast_2d ( eci2ecef ( eci , t , useastropy = useastropy ) )
return np . asarray ( ecef2geodetic ( ecef [ : , 0 ] , ecef [ : , 1 ] , ecef [ : , 2 ] ) ) . squeeze ( ) |
def wait_for_zap ( self , timeout ) :
"""Wait for ZAP to be ready to receive API calls .""" | timeout_time = time . time ( ) + timeout
while not self . is_running ( ) :
if time . time ( ) > timeout_time :
raise ZAPError ( 'Timed out waiting for ZAP to start.' )
time . sleep ( 2 ) |
def _add_token_span_to_document ( self , span_element ) :
"""adds an < intro > , < act > or < conclu > token span to the document .""" | for token in span_element . text . split ( ) :
token_id = self . _add_token_to_document ( token )
if span_element . tag == 'act' : # doc can have 0 + acts
self . _add_spanning_relation ( 'act_{}' . format ( self . act_count ) , token_id )
else : # < intro > or < conclu >
self . _add_spanning... |
def pre ( self ) :
"""Initialize system for power flow study
Returns
None""" | logger . info ( '-> Power flow study: {} method, {} start' . format ( self . config . method . upper ( ) , 'flat' if self . config . flatstart else 'non-flat' ) )
t , s = elapsed ( )
system = self . system
dae = self . system . dae
system . dae . init_xy ( )
for device , pflow , init0 in zip ( system . devman . devices... |
def get_raw_query ( self ) :
"""Returns the raw query to use for current search , based on the
base query + update query""" | query = self . base_query . copy ( )
search_query = self . search_query . copy ( )
query . update ( search_query )
# Add sorting criteria
sorting = self . resolve_sorting ( query )
query . update ( sorting )
# Check if sort _ on is an index and if is sortable . Otherwise , assume
# the sorting must be done manually
cat... |
def num_rewards ( self ) :
"""Returns the number of distinct rewards .
Returns :
Returns None if the reward range is infinite or the processed rewards
aren ' t discrete , otherwise returns the number of distinct rewards .""" | # Pre - conditions : reward range is finite .
# : processed rewards are discrete .
if not self . is_reward_range_finite :
tf . logging . error ( "Infinite reward range, `num_rewards returning None`" )
return None
if not self . is_processed_rewards_discrete :
tf . logging . error ( "Processed rewards are not... |
def textFileStream ( self , directory , process_all = False ) :
"""Monitor a directory and process all text files .
File names starting with ` ` . ` ` are ignored .
: param string directory : a path
: param bool process _ all : whether to process pre - existing files
: rtype : DStream
. . warning : :
Th... | deserializer = FileTextStreamDeserializer ( self . _context )
file_stream = FileStream ( directory , process_all )
self . _on_stop_cb . append ( file_stream . stop )
return DStream ( file_stream , self , deserializer ) |
def recalculate_current_specimen_interpreatations ( self ) :
"""recalculates all interpretations on all specimens for all coordinate
systems . Does not display recalcuated data .""" | self . initialize_CART_rot ( self . s )
if str ( self . s ) in self . pmag_results_data [ 'specimens' ] :
for fit in self . pmag_results_data [ 'specimens' ] [ self . s ] :
if fit . get ( 'specimen' ) and 'calculation_type' in fit . get ( 'specimen' ) :
fit . put ( self . s , 'specimen' , self .... |
def stage_tc_create_tag ( self , tag , resource ) :
"""Add a tag to a resource .
Args :
tag ( str ) : The tag to be added to the resource .
resource ( obj ) : An instance of tcex resource class .""" | tag_resource = resource . tags ( self . tcex . safetag ( tag ) )
tag_resource . http_method = 'POST'
t_response = tag_resource . request ( )
if t_response . get ( 'status' ) != 'Success' :
self . log . warning ( '[tcex] Failed adding tag "{}" ({}).' . format ( tag , t_response . get ( 'response' ) . text ) ) |
def debug ( self , msg , indent = 0 , ** kwargs ) :
"""invoke ` ` self . logger . debug ` `""" | return self . logger . debug ( self . _indent ( msg , indent ) , ** kwargs ) |
def calc_common_dist ( df ) :
'''calculate a common distribution ( for col qn only ) that will be used to qn''' | # axis is col
tmp_arr = np . array ( [ ] )
col_names = df . columns . tolist ( )
for inst_col in col_names : # sort column
tmp_vect = df [ inst_col ] . sort_values ( ascending = False ) . values
# stacking rows vertically ( will transpose )
if tmp_arr . shape [ 0 ] == 0 :
tmp_arr = tmp_vect
else... |
def forwards ( self , orm ) :
"Write your forwards methods here ." | db . execute ( 'DELETE FROM cohort_variant' )
db . execute ( 'DELETE FROM cohort_sample' )
db . execute ( 'DELETE FROM cohort' )
samples = orm [ 'samples.Sample' ] . objects . filter ( published = True )
count = samples . count ( )
cohort = orm [ 'samples.Cohort' ] ( name = 'World' , autocreated = True , published = bo... |
def multi_log_probs_from_logits_and_actions ( policy_logits , actions ) :
"""Computes action log - probs from policy logits and actions .
In the notation used throughout documentation and comments , T refers to the
time dimension ranging from 0 to T - 1 . B refers to the batch size and
ACTION _ SPACE refers t... | log_probs = [ ]
for i in range ( len ( policy_logits ) ) :
log_probs . append ( - tf . nn . sparse_softmax_cross_entropy_with_logits ( logits = policy_logits [ i ] , labels = actions [ i ] ) )
return log_probs |
def log_to_file ( filename , level = DEBUG ) :
"""send paramiko logs to a logfile ,
if they ' re not already going somewhere""" | logger = logging . getLogger ( "paramiko" )
if len ( logger . handlers ) > 0 :
return
logger . setLevel ( level )
f = open ( filename , "a" )
handler = logging . StreamHandler ( f )
frm = "%(levelname)-.3s [%(asctime)s.%(msecs)03d] thr=%(_threadid)-3d"
frm += " %(name)s: %(message)s"
handler . setFormatter ( loggin... |
def _build_entry ( parts , existing_list_d , key_value , key_field_num , key_is_field_number , header = None , output_type = OutputType . error_on_dups , ignore_missing_keys = False , keep_key_col = False ) :
"""Build and add an entry to existing _ list _ d .
If the key is a field number , the entry added will be... | if key_value . strip ( ) == "" :
if ignore_missing_keys :
return
raise MissingKeyError ( "missing key value" )
if key_value in existing_list_d :
if output_type is OutputType . error_on_dups :
raise DuplicateKeyError ( key_value + " appears multiple times as key" )
elif ( output_type is O... |
def array2series ( self , array ) :
"""Prefix the information of the actual Timegrid object to the given
array and return it .
The Timegrid information is stored in the first thirteen values of
the first axis of the returned series . Initialize a Timegrid object
and apply its ` array2series ` method on a si... | try :
array = numpy . array ( array , dtype = float )
except BaseException :
objecttools . augment_excmessage ( 'While trying to prefix timegrid information to the ' 'given array' )
if len ( array ) != len ( self ) :
raise ValueError ( f'When converting an array to a sequence, the lengths of the ' f'timegri... |
def paste_action_callback ( self , * event ) :
"""Callback method for paste action""" | if react_to_event ( self . view , self . tree_view , event ) :
sm_selection , _ = self . get_state_machine_selection ( )
# only list specific elements are cut by widget
if len ( sm_selection . states ) == 1 :
global_clipboard . paste ( sm_selection . get_selected_state ( ) , limited = [ 'states' , '... |
def compare ( self ) : # pylint : disable = no - self - use
"""Computes the difference between the candidate config and the running config .""" | # becuase we emulate the configuration history
# the difference is between the last committed config and the running - config
running_config = self . _download_running_config ( )
running_config_lines = running_config . splitlines ( )
last_committed_config = self . _last_working_config
last_committed_config_lines = last... |
def threat ( self , name , ** kwargs ) :
"""Add Threat data to Batch object
Args :
name ( str ) : The name for this Group .
date _ added ( str , kwargs ) : The date timestamp the Indicator was created .
xid ( str , kwargs ) : The external id for this Group .
Returns :
obj : An instance of Threat .""" | group_obj = Threat ( name , ** kwargs )
return self . _group ( group_obj ) |
def _get_channel ( self ) :
""": returns : The detected sound channel
: rtype : string""" | if self . channel is None : # Get default channel as the first one that pops up in
# ' amixer scontrols ' output , which contains strings in the
# following format :
# Simple mixer control ' Master ' , 0
# Simple mixer control ' Capture ' , 0
out = check_output ( [ 'amixer' , 'scontrols' ] ) . decode ( )
m = re... |
def _get_http ( url , temp_file_name , initial_size , file_size , verbose_bool , progressbar , ncols = 80 ) :
"""Safely ( resume a ) download to a file from http ( s ) .""" | # Actually do the reading
req = urllib . request . Request ( url )
if initial_size > 0 :
req . headers [ 'Range' ] = 'bytes=%s-' % ( initial_size , )
try :
response = urllib . request . urlopen ( req )
except Exception : # There is a problem that may be due to resuming , some
# servers may not support the " Ran... |
def _valid_locales ( locales , normalize ) :
"""Return a list of normalized locales that do not throw an ` ` Exception ` `
when set .
Parameters
locales : str
A string where each locale is separated by a newline .
normalize : bool
Whether to call ` ` locale . normalize ` ` on each locale .
Returns
v... | if normalize :
normalizer = lambda x : locale . normalize ( x . strip ( ) )
else :
normalizer = lambda x : x . strip ( )
return list ( filter ( can_set_locale , map ( normalizer , locales ) ) ) |
def get_gif_frames ( img ) :
"""Extracts the frames from an animated gif .
: param img : A PIL Image object
: return : An array of PIL image objects , each corresponding to a frame in the animation .""" | gif_frames = [ ]
n = 0
while img :
if img . mode != "RGB" :
image = img . convert ( mode = "RGB" )
else :
image = img
gif_frames . append ( image )
n += 1
try :
img . seek ( n )
except EOFError :
break
return gif_frames |
def write ( self , filename = None , io = None , coors = None , igs = None , out = None , float_format = None , ** kwargs ) :
"""Write mesh + optional results in ` out ` to a file .
Parameters
filename : str , optional
The file name . If None , the mesh name is used instead .
io : MeshIO instance or ' auto ... | if filename is None :
filename = self . name + '.mesh'
if io is None :
io = self . io
if io is None :
io = 'auto'
if io == 'auto' :
io = MeshIO . any_from_filename ( filename )
if coors is None :
coors = self . coors
if igs is None :
igs = range ( len ( self . conns ) )
aux_mesh = Mesh .... |
def prt_summary ( self , prt = sys . stdout ) :
"""Print summary of grouping / sorting run .""" | # Grouping summary
fmtstr = "Grouped: {U:3,} User GOs, using {h:2,} of {H:,} Grouping GOs, for run: {NAME}\n"
prt . write ( fmtstr . format ( NAME = self . grpname , U = len ( self . usrgos ) , h = len ( self . hdrobj . hdrgos . intersection ( self . hdrgo2usrgos . keys ( ) ) ) , H = self . hdrobj . num_hdrgos ( ) ) ) |
def get_default_ndex_cred ( ndex_cred ) :
"""Gets the NDEx credentials from the dict , or tries the environment if None""" | if ndex_cred :
username = ndex_cred . get ( 'user' )
password = ndex_cred . get ( 'password' )
if username is not None and password is not None :
return username , password
username = get_config ( 'NDEX_USERNAME' )
password = get_config ( 'NDEX_PASSWORD' )
return username , password |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.