signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def is_venv ( ) :
"""Check whether if this workspace is a virtualenv .""" | dir_path = os . path . dirname ( SRC )
is_venv_flag = True
if SYS_NAME == "Windows" :
executable_list = [ "activate" , "pip.exe" , "python.exe" ]
elif SYS_NAME in [ "Darwin" , "Linux" ] :
executable_list = [ "activate" , "pip" , "python" ]
for executable in executable_list :
path = os . path . join ( dir_pa... |
def to_dataset ( self , dim = None , name = None ) :
"""Convert a DataArray to a Dataset .
Parameters
dim : str , optional
Name of the dimension on this array along which to split this array
into separate variables . If not provided , this array is converted
into a Dataset of one variable .
name : str ,... | if dim is not None and dim not in self . dims :
warnings . warn ( 'the order of the arguments on DataArray.to_dataset ' 'has changed; you now need to supply ``name`` as ' 'a keyword argument' , FutureWarning , stacklevel = 2 )
name = dim
dim = None
if dim is not None :
if name is not None :
rais... |
def send ( self , packet , mac_addr = broadcast_addr ) :
"""place sent packets directly into the reciever ' s queues ( as if they are connected by wire )""" | if self . keep_listening :
if mac_addr == self . broadcast_addr :
for addr , recv_queue in self . inq . items ( ) :
recv_queue . put ( packet )
else :
self . inq [ mac_addr ] . put ( packet )
self . inq [ self . broadcast_addr ] . put ( packet )
else :
self . log ( "is do... |
def server_close ( self ) :
"""Called to clean - up the server .
May be overridden .""" | if self . remove_file :
try :
os . remove ( self . remove_file )
except :
pass
self . socket . close ( ) |
def preorder_iter ( expression ) :
"""Iterate over the expression in preorder .""" | yield expression
if isinstance ( expression , Operation ) :
for operand in op_iter ( expression ) :
yield from preorder_iter ( operand ) |
def prepare_child_message ( self , gas : int , to : Address , value : int , data : BytesOrView , code : bytes , ** kwargs : Any ) -> Message :
"""Helper method for creating a child computation .""" | kwargs . setdefault ( 'sender' , self . msg . storage_address )
child_message = Message ( gas = gas , to = to , value = value , data = data , code = code , depth = self . msg . depth + 1 , ** kwargs )
return child_message |
def plot_vyz ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) :
"""Plot the Vyz component of the tensor .
Usage
x . plot _ vyz ( [ tick _ interval , xlabel , ylabel , ax , colorbar ,
cb _ orientation , cb _ label , show , fname ] )... | if cb_label is None :
cb_label = self . _vyz_label
if ax is None :
fig , axes = self . vyz . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs )
if show :
fig . show ( )
if fname is not None :
fig . savefig ( fname )
return ... |
def set_cli_options ( config , arguments = None ) :
"""Set any configuration options which have a CLI value set .
Args :
config ( confpy . core . config . Configuration ) : A configuration object which
has been initialized with options .
arguments ( iter of str ) : An iterable of strings which contains the ... | arguments = arguments or sys . argv [ 1 : ]
parser = argparse . ArgumentParser ( )
for section_name , section in config :
for option_name , _ in section :
var_name = '{0}_{1}' . format ( section_name . lower ( ) , option_name . lower ( ) , )
parser . add_argument ( '--{0}' . format ( var_name ) )
ar... |
def to_hdf5 ( cls , network = None , phases = [ ] , element = [ 'pore' , 'throat' ] , filename = '' , interleave = True , flatten = False , categorize_by = [ ] ) :
r"""Creates an HDF5 file containing data from the specified objects ,
and categorized according to the given arguments .
Parameters
network : Open... | project , network , phases = cls . _parse_args ( network = network , phases = phases )
if filename == '' :
filename = project . name
filename = cls . _parse_filename ( filename , ext = 'hdf' )
dct = Dict . to_dict ( network = network , phases = phases , element = element , interleave = interleave , flatten = flatte... |
def read_creds_from_ec2_instance_metadata ( ) :
"""Read credentials from EC2 instance metadata ( IAM role )
: return :""" | creds = init_creds ( )
try :
has_role = requests . get ( 'http://169.254.169.254/latest/meta-data/iam/security-credentials' , timeout = 1 )
if has_role . status_code == 200 :
iam_role = has_role . text
credentials = requests . get ( 'http://169.254.169.254/latest/meta-data/iam/security-credentia... |
def app_template_global ( self , name : Optional [ str ] = None ) -> Callable :
"""Add an application wide template global .
This is designed to be used as a decorator , and has the same arguments
as : meth : ` ~ quart . Quart . template _ global ` . An example usage ,
. . code - block : : python
blueprint ... | def decorator ( func : Callable ) -> Callable :
self . add_app_template_global ( func , name = name )
return func
return decorator |
def _build_default_options ( self ) :
"""" Provide the default value for all allowed fields .
Custom FactoryOptions classes should override this method
to update ( ) its return value .""" | return [ OptionDefault ( 'model' , None , inherit = True ) , OptionDefault ( 'abstract' , False , inherit = False ) , OptionDefault ( 'strategy' , enums . CREATE_STRATEGY , inherit = True ) , OptionDefault ( 'inline_args' , ( ) , inherit = True ) , OptionDefault ( 'exclude' , ( ) , inherit = True ) , OptionDefault ( 'r... |
def finalize_options ( self ) :
"""Alter the installation path .""" | install . finalize_options ( self )
if self . prefix is None : # no place for man page ( like in a ' snap ' )
man_dir = None
else :
man_dir = os . path . join ( self . prefix , "share" , "man" , "man1" )
# if we have ' root ' , put the building path also under it ( used normally
# by pbuilder )
if s... |
def copy_file ( src , target ) :
"""copy _ file
copy source to target""" | LOGGER . info ( "Copying {} to {}" . format ( src , target ) )
shutil . copyfile ( src , target )
shutil . copymode ( src , target ) |
def unixtime2str ( timestamp , fmt = '%Y-%m-%d %H:%M:%S' ) :
"""将 ` ` 秒级别的时间戳 ` ` 转换成字符串
. . warning :
时间戳是以 ` ` 秒 ` ` 为单位的
: param timestamp : unix timestamp
: type timestamp : int
: param fmt : show format
: type fmt : str
: return :
: rtype : str""" | dt = None
try :
timestamp = time . localtime ( timestamp )
dt = time . strftime ( fmt , timestamp )
except Exception as err :
print ( err )
return dt |
def dependency_tree ( installed_keys , root_key ) :
"""Calculate the dependency tree for the package ` root _ key ` and return
a collection of all its dependencies . Uses a DFS traversal algorithm .
` installed _ keys ` should be a { key : requirement } mapping , e . g .
{ ' django ' : from _ line ( ' django ... | dependencies = set ( )
queue = collections . deque ( )
if root_key in installed_keys :
dep = installed_keys [ root_key ]
queue . append ( dep )
while queue :
v = queue . popleft ( )
key = key_from_req ( v )
if key in dependencies :
continue
dependencies . add ( key )
for dep_specifie... |
def to_haab ( jd ) :
'''Determine Mayan Haab " month " and day from Julian day''' | # Number of days since the start of the long count
lcount = trunc ( jd ) + 0.5 - EPOCH
# Long Count begins 348 days after the start of the cycle
day = ( lcount + 348 ) % 365
count = day % 20
month = trunc ( day / 20 )
return int ( count ) , HAAB_MONTHS [ month ] |
def _init_config ( self ) :
"""If no config file exists , create it and add default options .
Defaults : -
- Default LevelDB path is specified based on OS
- dynamic loading is set to infura by default in the file
This function also sets self . leveldb _ dir path""" | leveldb_default_path = self . _get_default_leveldb_path ( )
if not os . path . exists ( self . config_path ) :
log . info ( "No config file found. Creating default: " + self . config_path )
open ( self . config_path , "a" ) . close ( )
config = ConfigParser ( allow_no_value = True )
config . optionxform = str
c... |
def __ilwdchar ( self , istr ) :
"""If the ilwd : char field contains octal data , it is translated
to a binary string and returned . Otherwise a lookup is done
in the unique id dictionary and a binary string containing the
correct unique id is returned .""" | istr_orig = istr
istr = self . licrx . sub ( '' , istr . encode ( 'ascii' ) )
istr = self . ricrx . sub ( '' , istr )
if self . octrx . match ( istr ) :
exec "istr = '"
+ istr + "'"
# if the DB2 module is loaded , the string should be converted
# to an instance of the DB2 . Binary class . If not , leave... |
def wrap_fusion ( job , fastqs , star_output , univ_options , star_fusion_options , fusion_inspector_options ) :
"""A wrapper for run _ fusion using the results from cutadapt and star as input .
: param tuple fastqs : RNA - Seq FASTQ Filestore IDs
: param dict star _ output : Dictionary containing STAR output f... | # Give user option to skip fusion calling
if not star_fusion_options [ 'run' ] :
job . fileStore . logToMaster ( 'Skipping STAR-Fusion on %s' % univ_options [ 'patient' ] )
return
fusion = job . wrapJobFn ( run_fusion , fastqs , star_output [ 'rnaChimeric.out.junction' ] , univ_options , star_fusion_options , f... |
def binary ( self , name , flag ) :
"""Build all dependencies of a package""" | if self . meta . rsl_deps in [ "on" , "ON" ] and "--resolve-off" not in flag :
sys . setrecursionlimit ( 10000 )
dependencies = [ ]
requires = Requires ( name , self . repo ) . get_deps ( )
if requires :
for req in requires :
status ( 0 )
if req and req not in self . blac... |
def get_limits ( self ) :
"""Return all known limits for this service , as a dict of their names
to : py : class : ` ~ . AwsLimit ` objects .
: returns : dict of limit names to : py : class : ` ~ . AwsLimit ` objects
: rtype : dict""" | if self . limits != { } :
return self . limits
limits = { }
limits [ 'Groups' ] = AwsLimit ( 'Groups' , self , 300 , self . warning_threshold , self . critical_threshold , limit_type = 'AWS::IAM::Group' , )
limits [ 'Users' ] = AwsLimit ( 'Users' , self , 5000 , self . warning_threshold , self . critical_threshold ... |
def update_status ( self , id_number , new_value ) :
"""Update a status name
: type id _ number : int
: param id _ number : status ID number
: type new _ value : str
: param new _ value : The new status name
: rtype : dict
: return : an empty dictionary""" | data = { 'id' : id_number , 'new_value' : new_value }
return self . post ( 'updateStatus' , data ) |
def in_qtconsole ( ) :
"""check if we ' re inside an IPython qtconsole
DEPRECATED : This is no longer needed , or working , in IPython 3 and above .""" | try :
ip = get_ipython ( )
front_end = ( ip . config . get ( 'KernelApp' , { } ) . get ( 'parent_appname' , "" ) or ip . config . get ( 'IPKernelApp' , { } ) . get ( 'parent_appname' , "" ) )
if 'qtconsole' in front_end . lower ( ) :
return True
except :
return False
return False |
def filter_query ( self , query ) :
"""Filter the given query using the filter classes specified on the view if any are specified .""" | for filter_class in list ( self . filter_classes ) :
query = filter_class ( ) . filter_query ( self . request , query , self )
return query |
def set_spyder_breakpoints ( self , force = False ) :
"""Set Spyder breakpoints into a debugging session""" | if self . _reading or force :
breakpoints_dict = CONF . get ( 'run' , 'breakpoints' , { } )
# We need to enclose pickled values in a list to be able to
# send them to the kernel in Python 2
serialiazed_breakpoints = [ pickle . dumps ( breakpoints_dict , protocol = PICKLE_PROTOCOL ) ]
breakpoints = t... |
def mute ( self ) :
"""Mutes all existing communication , most notably the device will no
longer generate a 13.56 MHz carrier signal when operating as
Initiator .""" | fname = "mute"
cname = self . __class__ . __module__ + '.' + self . __class__ . __name__
raise NotImplementedError ( "%s.%s() is required" % ( cname , fname ) ) |
def build ( self ) :
'''Connect nodes according to status of targets''' | # right now we do not worry about status of nodes
# connecting the output to the input of other nodes
# NOTE : This is implemented in the least efficient way just for
# testing . It has to be re - implemented .
# refer to http : / / stackoverflow . com / questions / 33494376 / networkx - add - edges - to - graph - from... |
def _find_all_first_files ( self , item ) :
"""Does not support the full range of ways rar can split
as it ' d require reading the file to ensure you are using the
correct way .""" | for listed_item in item . list ( ) :
new_style = re . findall ( r'(?i)\.part(\d+)\.rar^' , listed_item . id )
if new_style :
if int ( new_style [ 0 ] ) == 1 :
yield 'new' , listed_item
elif listed_item . id . lower ( ) . endswith ( '.rar' ) :
yield 'old' , listed_item |
def _drawContents ( self , reason = None , initiator = None ) :
"""Draws the plot contents from the sliced array of the collected repo tree item .
The reason parameter is used to determine if the axes will be reset ( the initiator
parameter is ignored ) . See AbstractInspector . updateContents for their descrip... | self . slicedArray = self . collector . getSlicedArray ( )
if not self . _hasValidData ( ) :
self . _clearContents ( )
raise InvalidDataError ( "No data available or it does not contain real numbers" )
# - - Valid plot data from here on - -
# PyQtGraph doesn ' t handle masked arrays so we convert the masked val... |
def _clean ( self , value ) :
"""Validate and clean a candidate value for this field .""" | if value is None :
return None
elif self . type_ is None :
return value
elif self . check_type ( value ) :
return value
elif self . is_type_castable : # noqa
return self . type_ ( value )
error_fmt = "%s must be a %s, not a %s"
error = error_fmt % ( self . name , self . type_ , type ( value ) )
raise Ty... |
def pipe_createrss ( context = None , _INPUT = None , conf = None , ** kwargs ) :
"""An operator that converts a source into an RSS stream . Not loopable .""" | conf = DotDict ( conf )
for item in _INPUT :
item = DotDict ( item )
yield { value : item . get ( conf . get ( key , ** kwargs ) ) for key , value in RSS_FIELDS . items ( ) } |
def output ( self ) :
"""Use the digest version , since URL can be ugly .""" | return luigi . LocalTarget ( path = self . path ( digest = True , ext = 'html' ) ) |
def adev ( self , tau0 , tau ) :
"""return predicted ADEV of noise - type at given tau""" | prefactor = self . adev_from_qd ( tau0 = tau0 , tau = tau )
c = self . c_avar ( )
avar = pow ( prefactor , 2 ) * pow ( tau , c )
return np . sqrt ( avar ) |
def remove_signal_receiver ( self , signal ) :
"""Remove an installed signal receiver by signal name .
See also : py : meth : ` add _ signal _ receiver `
: py : exc : ` exceptions . ConnSignalNameNotRecognisedException `
: param str signal :
Signal name to uninstall e . g . , : py : attr : ` SIGNAL _ PROPER... | if ( signal in self . _signal_names ) :
s = self . _signals . get ( signal )
if ( s ) :
self . _bus . remove_signal_receiver ( s . signal_handler , signal , dbus_interface = self . _dbus_addr )
# noqa
self . _signals . pop ( signal )
else :
raise ConnSignalNameNotRecognisedException |
def connect ( filename : str , mode : str = 'r+' , * , validate : bool = True , spec_version : str = "2.0.1" ) -> LoomConnection :
"""Establish a connection to a . loom file .
Args :
filename : Path to the Loom file to open
mode : Read / write mode , ' r + ' ( read / write ) or ' r ' ( read - only ) , default... | return LoomConnection ( filename , mode , validate = validate , spec_version = spec_version ) |
def batch_delete_jobs ( self , parent , filter_ , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Deletes a list of ` ` Job ` ` \ s by filter .
Example :
> > > from google . cloud import talent _ v4beta1
> > > clien... | # Wrap the transport method to add retry and timeout logic .
if "batch_delete_jobs" not in self . _inner_api_calls :
self . _inner_api_calls [ "batch_delete_jobs" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . batch_delete_jobs , default_retry = self . _method_configs [ "BatchDeleteJob... |
def get_ipv4_range ( start_addr = None , end_addr = None , return_fields = None , ** api_opts ) :
'''Get ip range
CLI Example :
. . code - block : : bash
salt - call infoblox . get _ ipv4 _ range start _ addr = 123.123.122.12''' | infoblox = _get_infoblox ( ** api_opts )
return infoblox . get_range ( start_addr , end_addr , return_fields ) |
def get_connections_by_dests ( self , dests ) :
'''Search for all connections involving this and all other ports .''' | with self . _mutex :
res = [ ]
for c in self . connections :
if not c . has_port ( self ) :
continue
has_dest = False
for d in dests :
if c . has_port ( d ) :
has_dest = True
break
if has_dest :
res . append ( c ... |
def request_goto ( self , tc = None ) :
"""Request a go to assignment .
: param tc : Text cursor which contains the text that we must look for
its assignment . Can be None to go to the text that is under
the text cursor .
: type tc : QtGui . QTextCursor""" | if not tc :
tc = TextHelper ( self . editor ) . word_under_cursor ( select_whole_word = True )
if not self . _definition or isinstance ( self . sender ( ) , QAction ) :
self . select_word ( tc )
if self . _definition is not None :
QTimer . singleShot ( 100 , self . _goto_def ) |
def channelRelease ( BaRange_presence = 0 , GroupChannelDescription_presence = 0 , GroupCipherKeyNumber_presence = 0 , GprsResumption_presence = 0 , BaListPref_presence = 0 ) :
"""CHANNEL RELEASE Section 9.1.7""" | a = TpPd ( pd = 0x6 )
b = MessageType ( mesType = 0xD )
# 00001101
c = RrCause ( )
packet = a / b / c
if BaRange_presence is 1 :
d = BaRangeHdr ( ieiBR = 0x73 , eightBitBR = 0x0 )
packet = packet / d
if GroupChannelDescription_presence is 1 :
e = GroupChannelDescriptionHdr ( ieiGCD = 0x74 , eightBitGCD = 0x... |
def clone ( self , debug = False , trace = False ) :
"""Copy the simulation just enough to be able to run the copy without modifying the original simulation""" | new = empty_clone ( self )
new_dict = new . __dict__
for key , value in self . __dict__ . items ( ) :
if key not in ( 'debug' , 'trace' , 'tracer' ) :
new_dict [ key ] = value
new . persons = self . persons . clone ( new )
setattr ( new , new . persons . entity . key , new . persons )
new . populations = { ... |
def disk_set ( device , flag , state ) :
'''Changes a flag on selected device .
A flag can be either " on " or " off " ( make sure to use proper
quoting , see : ref : ` YAML Idiosyncrasies
< yaml - idiosyncrasies > ` ) . Some or all of these flags will be
available , depending on what disk label you are usi... | _validate_device ( device )
if flag not in VALID_DISK_FLAGS :
raise CommandExecutionError ( 'Invalid flag passed to partition.disk_set' )
if state not in set ( [ 'on' , 'off' ] ) :
raise CommandExecutionError ( 'Invalid state passed to partition.disk_set' )
cmd = [ 'parted' , '-m' , '-s' , device , 'disk_set' ,... |
def move_rule_after ( self , other_rule ) :
"""Add this rule after another . This process will make a copy of
the existing rule and add after the specified rule . If this
raises an exception , processing is stopped . Otherwise the original
rule is then deleted .
You must re - retrieve the new element after ... | self . make_request ( CreateRuleFailed , href = other_rule . get_relation ( 'add_after' ) , method = 'create' , json = self )
self . delete ( ) |
def remote ( self , action ) :
"""Function specific for MMI , not BMI .
action is one of : " play " , " stop " , " pause " , " rewind " , " quit " """ | method = "remote"
A = None
metadata = { method : action }
send_array ( self . socket , A , metadata )
A , metadata = recv_array ( self . socket , poll = self . poll , poll_timeout = self . poll_timeout , flags = self . zmq_flags )
return metadata [ method ] |
def list_cleared_orders ( self , bet_status = 'SETTLED' , event_type_ids = None , event_ids = None , market_ids = None , runner_ids = None , bet_ids = None , customer_order_refs = None , customer_strategy_refs = None , side = None , settled_date_range = time_range ( ) , group_by = None , include_item_description = None... | params = clean_locals ( locals ( ) )
method = '%s%s' % ( self . URI , 'listClearedOrders' )
( response , elapsed_time ) = self . request ( method , params , session )
return self . process_response ( response , resources . ClearedOrders , elapsed_time , lightweight ) |
def com_google_fonts_check_ttx_roundtrip ( font ) :
"""Checking with fontTools . ttx""" | from fontTools import ttx
import sys
ttFont = ttx . TTFont ( font )
failed = False
class TTXLogger :
msgs = [ ]
def __init__ ( self ) :
self . original_stderr = sys . stderr
self . original_stdout = sys . stdout
sys . stderr = self
sys . stdout = self
def write ( self , data ... |
def get_optional_artifacts_per_task_id ( upstream_artifacts ) :
"""Return every optional artifact defined in ` ` upstream _ artifacts ` ` , ordered by taskId .
Args :
upstream _ artifacts : the list of upstream artifact definitions
Returns :
dict : list of paths to downloaded artifacts ordered by taskId""" | # A given taskId might be defined many times in upstreamArtifacts . Thus , we can ' t
# use a dict comprehension
optional_artifacts_per_task_id = { }
for artifact_definition in upstream_artifacts :
if artifact_definition . get ( 'optional' , False ) is True :
task_id = artifact_definition [ 'taskId' ]
... |
def _parse_authors ( html_chunk ) :
"""Parse authors of the book .
Args :
html _ chunk ( obj ) : HTMLElement containing slice of the page with details .
Returns :
list : List of : class : ` structures . Author ` objects . Blank if no author found .""" | authors = html_chunk . match ( [ "div" , { "class" : "comment" } ] , "h3" , "a" , )
if not authors :
return [ ]
authors = map ( lambda x : Author ( # create Author objects
x . getContent ( ) . strip ( ) , normalize_url ( BASE_URL , x . params . get ( "href" , None ) ) ) , authors )
return filter ( lambda x : x . na... |
def crc8 ( data ) :
"""Perform the 1 - Wire CRC check on the provided data .
: param bytearray data : 8 byte array representing 64 bit ROM code""" | crc = 0
for byte in data :
crc ^= byte
for _ in range ( 8 ) :
if crc & 0x01 :
crc = ( crc >> 1 ) ^ 0x8C
else :
crc >>= 1
crc &= 0xFF
return crc |
def parse_sws_date ( date_string ) :
"""Takes a date from the SWS response object
and attempts to parse it using one of the several
datetime formats used by the SWS
: param date _ string :
: return : date object""" | if date_string is None :
return None
date_formats = [ "%m/%d/%Y" , "%Y-%m-%d" , "%Y%m%d" ]
datetime_obj = None
for fmt in date_formats :
try :
datetime_obj = datetime . strptime ( date_string , fmt )
except ValueError :
continue
break
if datetime_obj is None :
raise ValueError ( "Unk... |
def render_property ( property ) :
"""Render a property for bosh manifest , according to its type .""" | # This ain ' t the prettiest thing , but it should get the job done .
# I don ' t think we have anything more elegant available at bosh - manifest - generation time .
# See https : / / docs . pivotal . io / partners / product - template - reference . html for list .
if 'type' in property and property [ 'type' ] in PROP... |
def molecules2symbols ( molecules , add_hydrogen = True ) :
"""Take a list of molecules and return just a list of atomic
symbols , possibly adding hydrogen""" | symbols = sorted ( list ( set ( ase . symbols . string2symbols ( '' . join ( map ( lambda _x : '' . join ( ase . symbols . string2symbols ( _x ) ) , molecules ) ) ) ) ) , key = lambda _y : ase . data . atomic_numbers [ _y ] )
if add_hydrogen and 'H' not in symbols :
symbols . insert ( 0 , 'H' )
return symbols |
def nvmlDeviceGetSerial ( handle ) :
r"""* Retrieves the globally unique board serial number associated with this device ' s board .
* For all products with an inforom .
* The serial number is an alphanumeric string that will not exceed 30 characters ( including the NULL terminator ) .
* This number matches t... | c_serial = create_string_buffer ( NVML_DEVICE_SERIAL_BUFFER_SIZE )
fn = _nvmlGetFunctionPointer ( "nvmlDeviceGetSerial" )
ret = fn ( handle , c_serial , c_uint ( NVML_DEVICE_SERIAL_BUFFER_SIZE ) )
_nvmlCheckReturn ( ret )
return bytes_to_str ( c_serial . value ) |
def is_prime ( n , mr_rounds = 25 ) :
"""Test whether n is probably prime
See < https : / / en . wikipedia . org / wiki / Primality _ test # Probabilistic _ tests >
Arguments :
n ( int ) : the number to be tested
mr _ rounds ( int , optional ) : number of Miller - Rabin iterations to run ;
defaults to 25 ... | # as an optimization we quickly detect small primes using the list above
if n <= first_primes [ - 1 ] :
return n in first_primes
# for small dividors ( relatively frequent ) , euclidean division is best
for p in first_primes :
if n % p == 0 :
return False
# the actual generic test ; give a false prime w... |
def estimator_status_send ( self , time_usec , flags , vel_ratio , pos_horiz_ratio , pos_vert_ratio , mag_ratio , hagl_ratio , tas_ratio , pos_horiz_accuracy , pos_vert_accuracy , force_mavlink1 = False ) :
'''Estimator status message including flags , innovation test ratios and
estimated accuracies . The flags m... | return self . send ( self . estimator_status_encode ( time_usec , flags , vel_ratio , pos_horiz_ratio , pos_vert_ratio , mag_ratio , hagl_ratio , tas_ratio , pos_horiz_accuracy , pos_vert_accuracy ) , force_mavlink1 = force_mavlink1 ) |
def create_certificate_signing_request ( self , body , ** kwargs ) :
"""create a CertificateSigningRequest
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . create _ certificate _ signing _ request ( body , asyn... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . create_certificate_signing_request_with_http_info ( body , ** kwargs )
else :
( data ) = self . create_certificate_signing_request_with_http_info ( body , ** kwargs )
return data |
def _expectation ( p , mean1 , none1 , mean2 , none2 , nghp = None ) :
"""Compute the expectation :
expectation [ n ] = < m1 ( x _ n ) ^ T m2 ( x _ n ) > _ p ( x _ n )
- m1 ( . ) , m2 ( . ) : : Linear mean functions
: return : NxQ1xQ2""" | with params_as_tensors_for ( mean1 , mean2 ) :
e_xxt = p . cov + ( p . mu [ : , : , None ] * p . mu [ : , None , : ] )
# NxDxD
e_A1t_xxt_A2 = tf . einsum ( "iq,nij,jz->nqz" , mean1 . A , e_xxt , mean2 . A )
# NxQ1xQ2
e_A1t_x_b2t = tf . einsum ( "iq,ni,z->nqz" , mean1 . A , p . mu , mean2 . b )
#... |
def _get_ptr_details ( self , device , device_type ) :
"""Takes a device and device type and returns the corresponding HREF link
and service name for use with PTR record management .""" | context = self . api . identity
region = self . api . region_name
if device_type . lower ( ) . startswith ( "load" ) :
ep = pyrax . _get_service_endpoint ( context , "load_balancer" , region )
svc = "loadbalancers"
svc_name = "cloudLoadBalancers"
else :
ep = pyrax . _get_service_endpoint ( context , "co... |
def read_user_mapping ( self , user_name , mount_point = DEFAULT_MOUNT_POINT ) :
"""Read the GitHub user policy mapping .
Supported methods :
GET : / auth / { mount _ point } / map / users / { user _ name } . Produces : 200 application / json
: param user _ name : GitHub user name
: type user _ name : str |... | api_path = '/v1/auth/{mount_point}/map/users/{user_name}' . format ( mount_point = mount_point , user_name = user_name , )
response = self . _adapter . get ( url = api_path )
return response . json ( ) |
def always_win ( cls , request ) -> [ ( 200 , 'Ok' , String ) ] :
'''Perform an always succeeding task .''' | task_id = uuid4 ( ) . hex . upper ( ) [ : 5 ]
log . info ( 'Starting always OK task {}' . format ( task_id ) )
for i in range ( randint ( 0 , MAX_LOOP_DURATION ) ) :
yield
log . info ( 'Finished always OK task {}' . format ( task_id ) )
msg = 'I am finally done with task {}!' . format ( task_id )
Respond ( 200 , ms... |
def oaiid_fetcher ( record_uuid , data ) :
"""Fetch a record ' s identifier .
: param record _ uuid : The record UUID .
: param data : The record data .
: returns : A : class : ` invenio _ pidstore . fetchers . FetchedPID ` instance .""" | pid_value = data . get ( '_oai' , { } ) . get ( 'id' )
if pid_value is None :
raise PersistentIdentifierError ( )
return FetchedPID ( provider = OAIIDProvider , pid_type = OAIIDProvider . pid_type , pid_value = str ( pid_value ) , ) |
def switch_off ( self ) :
"""Turn the switch off .""" | success = self . set_status ( CONST . STATUS_OFF_INT )
if success :
self . _json_state [ 'status' ] = CONST . STATUS_OFF
return success |
def _GetApprovals ( self , approval_type , offset , count , filter_func = None , token = None ) :
"""Gets all approvals for a given user and approval type .
Args :
approval _ type : The type of approvals to get .
offset : The starting index within the collection .
count : The number of items to return .
f... | approvals_base_urn = aff4 . ROOT_URN . Add ( "users" ) . Add ( token . username ) . Add ( "approvals" ) . Add ( approval_type )
all_children = aff4 . FACTORY . RecursiveMultiListChildren ( [ approvals_base_urn ] )
approvals_urns = [ ]
for subject , children in all_children : # We only want to process leaf nodes .
i... |
def dimensions ( self ) -> Tuple [ str , ... ] :
"""The dimension names of the NetCDF variable .
Usually , the string defined by property | IOSequence . descr _ sequence |
prefixes the first dimension name related to the location , which
allows storing different sequences types in one NetCDF file :
> > > fr... | self : NetCDFVariableBase
return self . sort_timeplaceentries ( dimmapping [ 'nmb_timepoints' ] , '%s%s' % ( self . prefix , dimmapping [ 'nmb_subdevices' ] ) ) |
def observable_copy ( value , name , instance ) :
"""Return an observable container for HasProperties notifications
This method creates a new container class to allow HasProperties
instances to : code : ` observe _ mutations ` . It returns a copy of the
input value as this new class .
The output class behav... | container_class = value . __class__
if container_class in OBSERVABLE_REGISTRY :
observable_class = OBSERVABLE_REGISTRY [ container_class ]
elif container_class in OBSERVABLE_REGISTRY . values ( ) :
observable_class = container_class
else :
observable_class = add_properties_callbacks ( type ( container_class... |
def _add ( self , sprite , index = None ) :
"""add one sprite at a time . used by add _ child . split them up so that
it would be possible specify the index externally""" | if sprite == self :
raise Exception ( "trying to add sprite to itself" )
if sprite . parent :
sprite . x , sprite . y = self . from_scene_coords ( * sprite . to_scene_coords ( ) )
sprite . parent . remove_child ( sprite )
if index is not None :
self . sprites . insert ( index , sprite )
else :
self ... |
def _get_supercells ( self , struct1 , struct2 , fu , s1_supercell ) :
"""Computes all supercells of one structure close to the lattice of the
other
if s1 _ supercell = = True , it makes the supercells of struct1 , otherwise
it makes them of s2
yields : s1 , s2 , supercell _ matrix , average _ lattice , sup... | def av_lat ( l1 , l2 ) :
params = ( np . array ( l1 . lengths_and_angles ) + np . array ( l2 . lengths_and_angles ) ) / 2
return Lattice . from_lengths_and_angles ( * params )
def sc_generator ( s1 , s2 ) :
s2_fc = np . array ( s2 . frac_coords )
if fu == 1 :
cc = np . array ( s1 . cart_coords )... |
def from_github ( user_repo_pair , file = 'plashfile' ) :
"build and use a file ( default ' plashfile ' ) from github repo" | from urllib . request import urlopen
url = 'https://raw.githubusercontent.com/{}/master/{}' . format ( user_repo_pair , file )
with utils . catch_and_die ( [ Exception ] , debug = url ) :
resp = urlopen ( url )
plashstr = resp . read ( )
return utils . run_write_read ( [ 'plash' , 'build' , '--eval-stdin' ] , plash... |
def _find_regular_images ( container , contentsinfo ) :
"""Find images stored in the container ' s / Resources / XObject
Usually the container is a page , but it could also be a Form XObject
that contains images .
Generates images with their DPI at time of drawing .""" | for pdfimage , xobj in _image_xobjects ( container ) : # For each image that is drawn on this , check if we drawing the
# current image - yes this is O ( n ^ 2 ) , but n = = 1 almost always
for draw in contentsinfo . xobject_settings :
if draw . name != xobj :
continue
if draw . stack_de... |
def __apf_cmd ( cmd ) :
'''Return the apf location''' | apf_cmd = '{0} {1}' . format ( salt . utils . path . which ( 'apf' ) , cmd )
out = __salt__ [ 'cmd.run_all' ] ( apf_cmd )
if out [ 'retcode' ] != 0 :
if not out [ 'stderr' ] :
msg = out [ 'stdout' ]
else :
msg = out [ 'stderr' ]
raise CommandExecutionError ( 'apf failed: {0}' . format ( msg ... |
def setDirty ( self , state = True ) :
"""Flags the connection as being dirty and needing a rebuild .
: param state | < bool >""" | self . _dirty = state
# set if this connection should be visible
if self . _inputNode and self . _outputNode :
vis = self . _inputNode . isVisible ( ) and self . _outputNode . isVisible ( )
self . setVisible ( vis ) |
def mask ( self , vector , mask_shape_nodata = False ) :
"""Set pixels outside vector as nodata .
: param vector : GeoVector , GeoFeature , FeatureCollection
: param mask _ shape _ nodata : if True - pixels inside shape are set nodata , if False - outside shape is nodata
: return : GeoRaster2""" | from telluric . collections import BaseCollection
# crop raster to reduce memory footprint
cropped = self . crop ( vector )
if isinstance ( vector , BaseCollection ) :
shapes = [ cropped . to_raster ( feature ) for feature in vector ]
else :
shapes = [ cropped . to_raster ( vector ) ]
mask = geometry_mask ( sha... |
def u_product ( a , b ) :
r"""Inner product in the Hilbert space of : math : ` U ` - centered distance matrices .
This inner product is defined as
. . math : :
\ frac { 1 } { n ( n - 3 ) } \ sum _ { i , j = 1 } ^ n a _ { i , j } b _ { i , j }
Parameters
a : array _ like
First input array to be multiplie... | n = np . size ( a , 0 )
return np . sum ( a * b ) / ( n * ( n - 3 ) ) |
def dirpath_int ( self ) :
"""Absolute path of the directory of the internal data file .
Normally , each sequence queries its current " internal " directory
path from the | SequenceManager | object stored in module | pub | :
> > > from hydpy import pub , repr _ , TestIO
> > > from hydpy . core . filetools i... | try :
return hydpy . pub . sequencemanager . tempdirpath
except RuntimeError :
raise RuntimeError ( f'For sequence {objecttools.devicephrase(self)} ' f'the directory of the internal data file cannot ' f'be determined. Either set it manually or prepare ' f'`pub.sequencemanager` correctly.' ) |
def decoder ( decoder_input , encoder_output , decoder_self_attention_bias , encoder_decoder_attention_bias , hparams , name = "decoder" , save_weights_to = None , make_image_summary = True , ) :
"""A stack of transformer layers .
Args :
decoder _ input : a Tensor
encoder _ output : a Tensor
decoder _ self ... | x = decoder_input
with tf . variable_scope ( name ) :
for layer in range ( hparams . num_decoder_layers or hparams . num_hidden_layers ) :
layer_name = "layer_%d" % layer
with tf . variable_scope ( layer_name ) :
with tf . variable_scope ( "self_attention" ) :
y = common_... |
def remote_is_page_blob ( self ) : # type : ( Descriptor ) - > bool
"""Remote destination is an Azure Page Blob
: param Descriptor self : this
: rtype : bool
: return : remote is an Azure Page Blob""" | return self . dst_entity . mode == blobxfer . models . azure . StorageModes . Page |
def update_views ( self ) :
"""Update the stats views .
The V of MVC
A dict of dict with the needed information to display the stats .
Example for the stat xxx :
' xxx ' : { ' decoration ' : ' DEFAULT ' ,
' optional ' : False ,
' additional ' : False ,
' splittable ' : False }""" | ret = { }
if ( isinstance ( self . get_raw ( ) , list ) and self . get_raw ( ) is not None and self . get_key ( ) is not None ) : # Stats are stored in a list of dict ( ex : NETWORK , FS . . . )
for i in self . get_raw ( ) :
ret [ i [ self . get_key ( ) ] ] = { }
for key in listkeys ( i ) :
... |
def link ( self , key1 , key2 ) :
"""Make these two keys have the same value
: param key1:
: param key2:
: return :""" | # TODO make this have more than one key linked
# TODO Maybe make the value a set ?
self . _linked_keys [ key1 ] = key2
self . _linked_keys [ key2 ] = key1 |
def set_geometry ( self , im , geometry , options = None ) :
"""Rescale the image to the new geometry .""" | if not geometry :
return im
options = options or { }
width , height = geometry
if not width and not height :
return im
imw , imh = self . get_size ( im )
# Geometry match the current size ?
if ( width is None ) or ( imw == width ) :
if ( height is None ) or ( imh == height ) :
return im
ratio = floa... |
def killBatchJobs ( self , jobIDs ) :
"""Kills jobs by ID .""" | log . debug ( 'Killing jobs: {}' . format ( jobIDs ) )
for jobID in jobIDs :
if jobID in self . runningJobs :
info = self . runningJobs [ jobID ]
info . killIntended = True
if info . popen != None :
os . kill ( info . popen . pid , 9 )
else : # No popen if running in fork... |
def mk_package ( contents ) :
"""Instantiates a package specification from a parsed " AST " of a
package .
Parameters
contents : dict
Returns
PackageSpecification""" | package = contents . get ( 'package' , None )
description = contents . get ( 'description' , None )
include = contents . get ( 'include' , [ ] )
definitions = contents . get ( 'definitions' , [ ] )
resolved = [ mk_definition ( defn ) for defn in definitions ]
return sbp . PackageSpecification ( identifier = package , d... |
def create_environment ( ApplicationName = None , EnvironmentName = None , GroupName = None , Description = None , CNAMEPrefix = None , Tier = None , Tags = None , VersionLabel = None , TemplateName = None , SolutionStackName = None , PlatformArn = None , OptionSettings = None , OptionsToRemove = None ) :
"""Launch... | pass |
def pinch ( self , scale , velocity ) :
"""Args :
scale ( float ) : scale must > 0
velocity ( float ) : velocity must be less than zero when scale is less than 1
Example :
pinchIn - > scale : 0.5 , velocity : - 1
pinchOut - > scale : 2.0 , velocity : 1""" | data = { 'scale' : scale , 'velocity' : velocity }
return self . _wda_req ( 'post' , '/pinch' , data ) |
def _nvram_changed ( self , path ) :
"""Called when the NVRAM file has changed""" | log . debug ( "NVRAM changed: {}" . format ( path ) )
self . save_configs ( )
self . updated ( ) |
def download ( self , obj , directory , structure = True ) :
"""Fetches the object from storage , and writes it to the specified
directory . The directory must exist before calling this method .
If the object name represents a nested folder structure , such as
" foo / bar / baz . txt " , that folder structure... | return self . object_manager . download ( obj , directory , structure = structure ) |
def where_pivot ( self , column , operator = None , value = None , boolean = "and" ) :
"""Set a where clause for a pivot table column .
: param column : The column of the where clause , can also be a QueryBuilder instance for sub where
: type column : str | Builder
: param operator : The operator of the where... | self . _pivot_wheres . append ( [ column , operator , value , boolean ] )
return self . _query . where ( "%s.%s" % ( self . _table , column ) , operator , value , boolean ) |
def clone_action ( action , new_project , new_action_name , new_properties ) :
"""Takes an ' action ' instances and creates new instance of it
and all produced target . The rule - name and properties are set
to ' new - rule - name ' and ' new - properties ' , if those are specified .
Returns the cloned action... | if __debug__ :
from . targets import ProjectTarget
assert isinstance ( action , Action )
assert isinstance ( new_project , ProjectTarget )
assert isinstance ( new_action_name , basestring )
assert isinstance ( new_properties , property_set . PropertySet )
if not new_action_name :
new_action_name... |
def get_cohp_by_label ( self , label ) :
"""Get specific COHP object .
Args :
label : string ( for newer Lobster versions : a number )
Returns :
Returns the COHP object to simplify plotting""" | if label . lower ( ) == "average" :
return Cohp ( efermi = self . efermi , energies = self . energies , cohp = self . cohp , are_coops = self . are_coops , icohp = self . icohp )
else :
try :
return Cohp ( efermi = self . efermi , energies = self . energies , cohp = self . all_cohps [ label ] . get_cohp... |
def DeSelectByIndex ( cls , index ) :
'''通过索引 , 取消选择下拉框选项 ,
@ param index : 下拉框 索引''' | try :
Select ( cls . _element ( ) ) . deselect_by_index ( int ( index ) )
except :
return False |
def remove_types ( self , types , ** kwargs ) :
""": param types : Types to remove from the object
: type types : list of strings
: raises : : class : ` ~ dxpy . exceptions . DXAPIError ` if the object is not in the " open " state
Removes each the specified types from the remote object . Takes
no action for... | self . _remove_types ( self . _dxid , { "types" : types } , ** kwargs ) |
def _range ( self , link_map , radius ) :
"""Return range of linked pages to substiture placeholder in pattern""" | leftmost_page = max ( self . first_page , ( self . page - radius ) )
rightmost_page = min ( self . last_page , ( self . page + radius ) )
nav_items = [ ]
# Create a link to the first page ( unless we are on the first page
# or there would be no need to insert ' . . ' spacers )
if self . page != self . first_page and se... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'documents' ) and self . documents is not None :
_dict [ 'documents' ] = self . documents . _to_dict ( )
if hasattr ( self , 'disk_usage' ) and self . disk_usage is not None :
_dict [ 'disk_usage' ] = self . disk_usage . _to_dict ( )
if hasattr ( self , 'collections' ) and self .... |
def create ( self , task_type_id , task_queue_id , arguments = None , name = "" ) :
"""Create a task instance .
Args :
task _ type _ id ( int ) : The ID of the task type to base the task
instance on .
task _ queue _ id ( int ) : The ID of the task queue to run the job
on .
arguments ( dict , optional ) ... | # Make arguments an empty dictionary if None
if arguments is None :
arguments = { }
# Create the object
request_url = self . _client . base_api_url + self . list_url
data_to_post = { "name" : name , "arguments" : json . dumps ( arguments ) , "task_type" : task_type_id , "task_queue" : task_queue_id , }
response = s... |
def show_closed_prs ( self ) :
"""Log only closed PRs .""" | all_prs = self . collect_prs_info ( )
for pr_info in all_prs . get ( 'closed' , [ ] ) :
logger . info ( '{url} in state {state} ({merged})' . format ( ** pr_info ) ) |
def get_max_cost ( self , class_value , inst = None ) :
"""Gets the maximum cost for a particular class value .
: param class _ value : the class value to get the maximum cost for
: type class _ value : int
: param inst : the Instance
: type inst : Instance
: return : the cost
: rtype : float""" | if inst is None :
return javabridge . call ( self . jobject , "getMaxCost" , "(I)D" , class_value )
else :
return javabridge . call ( self . jobject , "getElement" , "(ILweka/core/Instance;)D" , class_value , inst . jobject ) |
def install_excepthook ( hook_type = "color" , ** kwargs ) :
"""This function replaces the original python traceback with an improved
version from Ipython . Use ` color ` for colourful traceback formatting ,
` verbose ` for Ka - Ping Yee ' s " cgitb . py " version kwargs are the keyword
arguments passed to th... | try :
from IPython . core import ultratb
except ImportError :
import warnings
warnings . warn ( "Cannot install excepthook, IPyhon.core.ultratb not available" )
return 1
# Select the hook .
hook = dict ( color = ultratb . ColorTB , verbose = ultratb . VerboseTB , ) . get ( hook_type . lower ( ) , None )... |
def plot_i ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) :
"""Plot the dimensionless quantity I of Pedersen and Rasmussen ( 1990)
I = - ( I2/2 ) * * 2 / ( I1/3 ) * * 3
that is bounded by 0 and 1.
Usage
x . plot _ i ( [ tick _ ... | if cb_label is None :
cb_label = self . _i_label
if self . i is None :
self . compute_invar ( )
if ax is None :
fig , axes = self . i . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs )
if show :
fig . show ( )
if fname is not Non... |
def get_default_config ( self ) :
"""Return default config for the handler""" | config = super ( DatadogHandler , self ) . get_default_config ( )
config . update ( { 'api_key' : '' , 'queue_size' : '' , } )
return config |
def plot_pca_component_variance ( clf , title = 'PCA Component Explained Variances' , target_explained_variance = 0.75 , ax = None , figsize = None , title_fontsize = "large" , text_fontsize = "medium" ) :
"""Plots PCA components ' explained variance ratios . ( new in v0.2.2)
Args :
clf : PCA instance that has ... | if not hasattr ( clf , 'explained_variance_ratio_' ) :
raise TypeError ( '"clf" does not have explained_variance_ratio_ ' 'attribute. Has the PCA been fitted?' )
if ax is None :
fig , ax = plt . subplots ( 1 , 1 , figsize = figsize )
ax . set_title ( title , fontsize = title_fontsize )
cumulative_sum_ratios = n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.