signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def exportProfile ( self , filename = '' ) :
"""Exports the current profile to a file .
: param filename | < str >""" | if not ( filename and isinstance ( filename , basestring ) ) :
filename = QtGui . QFileDialog . getSaveFileName ( self , 'Export Layout as...' , QtCore . QDir . currentPath ( ) , 'XView (*.xview)' )
if type ( filename ) == tuple :
filename = filename [ 0 ]
filename = nativestring ( filename )
if not fil... |
def copy_files ( self ) :
"""Copy the LICENSE and CONTRIBUTING files to each folder repo
Generate covers if needed . Dump the metadata .""" | files = [ u'LICENSE' , u'CONTRIBUTING.rst' ]
this_dir = dirname ( abspath ( __file__ ) )
for _file in files :
sh . cp ( '{0}/templates/{1}' . format ( this_dir , _file ) , '{0}/' . format ( self . book . local_path ) )
# copy metadata rdf file
if self . book . meta . rdf_path : # if None , meta is from yaml file
... |
def cxx ( source , libraries = [ ] ) :
r"""> > > cxx ( ' extern " C " { int add ( int a , int b ) { return a + b ; } } ' ) . add ( 40 , 2)
42""" | path = _cc_build_shared_lib ( source , '.cc' , libraries )
return ctypes . cdll . LoadLibrary ( path ) |
def _set_tx_queue ( self , v , load = False ) :
"""Setter method for tx _ queue , mapped from YANG variable / qos / tx _ queue ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ tx _ queue is considered as a private
method . Backends looking to populate thi... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = tx_queue . tx_queue , is_container = 'container' , presence = False , yang_name = "tx-queue" , rest_name = "tx-queue" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = Tr... |
def create ( self , institution_id , initial_products , _options = None , webhook = None , transactions__start_date = None , transactions__end_date = None , ) :
'''Generate a public token for sandbox testing .
: param str institution _ id :
: param [ str ] initial _ products :
: param str webhook :''' | options = _options or { }
if webhook is not None :
options [ 'webhook' ] = webhook
transaction_options = { }
transaction_options . update ( options . get ( 'transactions' , { } ) )
if transactions__start_date is not None :
transaction_options [ 'start_date' ] = transactions__start_date
if transactions__end_date... |
def container_remove_folder ( object_id , input_params = { } , always_retry = False , ** kwargs ) :
"""Invokes the / container - xxxx / removeFolder API method .
For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Folders - and - Deletion # API - method % 3A - % 2Fclass - xxxx... | return DXHTTPRequest ( '/%s/removeFolder' % object_id , input_params , always_retry = always_retry , ** kwargs ) |
def _parallel_compare_helper ( class_obj , pairs , x , x_link = None ) :
"""Internal function to overcome pickling problem in python2.""" | return class_obj . _compute ( pairs , x , x_link ) |
def underscore ( text , lower = True ) :
"""Splits all the words from the inputted text into being
separated by underscores
: sa [ [ # joinWords ] ]
: param text < str >
: return < str >
: usage | import projex . text
| print projex . text . underscore ( ' TheQuick , Brown , Fox ' )""" | out = joinWords ( text , '_' )
if lower :
return out . lower ( )
return out |
def play ( state ) :
"""Play sound for a given state .
: param state : a State value .""" | filename = None
if state == SoundService . State . welcome :
filename = "pad_glow_welcome1.wav"
elif state == SoundService . State . goodbye :
filename = "pad_glow_power_off.wav"
elif state == SoundService . State . hotword_detected :
filename = "pad_soft_on.wav"
elif state == SoundService . State . asr_tex... |
def guess_file_encoding ( fh , default = DEFAULT_ENCODING ) :
"""Guess encoding from a file handle .""" | start = fh . tell ( )
detector = chardet . UniversalDetector ( )
while True :
data = fh . read ( 1024 * 10 )
if not data :
detector . close ( )
break
detector . feed ( data )
if detector . done :
break
fh . seek ( start )
return normalize_result ( detector . result , default = de... |
def p_expr_trig ( p ) :
"""bexpr : math _ fn bexpr % prec UMINUS""" | p [ 0 ] = make_builtin ( p . lineno ( 1 ) , p [ 1 ] , make_typecast ( TYPE . float_ , p [ 2 ] , p . lineno ( 1 ) ) , { 'SIN' : math . sin , 'COS' : math . cos , 'TAN' : math . tan , 'ASN' : math . asin , 'ACS' : math . acos , 'ATN' : math . atan , 'LN' : lambda y : math . log ( y , math . exp ( 1 ) ) , # LN ( x )
'EXP'... |
def p_Body ( p ) :
'''Body : Line
| Body Line''' | if not isinstance ( p [ 1 ] , Body ) :
p [ 0 ] = Body ( None , p [ 1 ] )
else :
p [ 0 ] = Body ( p [ 1 ] , p [ 2 ] ) |
def guess_cls ( self ) :
"""Guess the packet class that must be used on the interface""" | # Get the data link type
try :
ret = fcntl . ioctl ( self . ins , BIOCGDLT , struct . pack ( 'I' , 0 ) )
ret = struct . unpack ( 'I' , ret ) [ 0 ]
except IOError :
cls = conf . default_l2
warning ( "BIOCGDLT failed: unable to guess type. Using %s !" , cls . name )
return cls
# Retrieve the correspon... |
def calculate_cardinality ( angle , earthquake_hazard = None , place_exposure = None ) :
"""Simple postprocessor where we compute the cardinality of an angle .
: param angle : Bearing angle .
: type angle : float
: param earthquake _ hazard : The hazard to use .
: type earthquake _ hazard : str
: param pl... | # this method could still be improved later , since the acquisition interval
# is a bit strange , i . e the input angle of 22.499 ° will return ` N ` even
# though 22.5 ° is the direction for ` NNE `
_ = earthquake_hazard , place_exposure
# NOQA
direction_list = tr ( 'N,NNE,NE,ENE,E,ESE,SE,SSE,S,SSW,SW,WSW,W,WNW,NW,NNW... |
def pvwatts_ac ( self , pdc ) :
"""Calculates AC power according to the PVWatts model using
: py : func : ` pvwatts _ ac ` , ` self . module _ parameters [ ' pdc0 ' ] ` , and
` eta _ inv _ nom = self . inverter _ parameters [ ' eta _ inv _ nom ' ] ` .
See : py : func : ` pvwatts _ ac ` for details .""" | kwargs = _build_kwargs ( [ 'eta_inv_nom' , 'eta_inv_ref' ] , self . inverter_parameters )
return pvwatts_ac ( pdc , self . module_parameters [ 'pdc0' ] , ** kwargs ) |
def create_volume ( zone_name , size = None , snapshot_id = None , volume_type = None , iops = None , encrypted = False , kms_key_id = None , wait_for_creation = False , region = None , key = None , keyid = None , profile = None ) :
'''Create an EBS volume to an availability zone .
zone _ name
( string ) – The ... | if size is None and snapshot_id is None :
raise SaltInvocationError ( 'Size must be provided if not created from snapshot.' )
ret = { }
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
try :
vol = conn . create_volume ( size = size , zone = zone_name , snapshot = snapshot_id ... |
def search ( self , token : dict = None , query : str = "" , bbox : list = None , poly : str = None , georel : str = None , order_by : str = "_created" , order_dir : str = "desc" , page_size : int = 100 , offset : int = 0 , share : str = None , specific_md : list = [ ] , include : list = [ ] , whole_share : bool = True... | # specific resources specific parsing
specific_md = checker . _check_filter_specific_md ( specific_md )
# sub resources specific parsing
include = checker . _check_filter_includes ( include )
# handling request parameters
payload = { "_id" : specific_md , "_include" : include , "_lang" : self . lang , "_limit" : page_s... |
def main ( ) :
"""Main""" | sev_obj = Seviri ( )
for satnum in [ 8 , 9 , 10 , 11 ] :
generate_seviri_file ( sev_obj , 'Meteosat-{0:d}' . format ( satnum ) )
print ( "Meteosat-{0:d} done..." . format ( satnum ) ) |
def messaging ( self ) :
"""Access the Messaging Twilio Domain
: returns : Messaging Twilio Domain
: rtype : twilio . rest . messaging . Messaging""" | if self . _messaging is None :
from twilio . rest . messaging import Messaging
self . _messaging = Messaging ( self )
return self . _messaging |
def skip ( self ) :
"""Skip whitespace and count position""" | buflen = len ( self . buf )
while True :
self . buf = self . buf . lstrip ( )
if self . buf == '' :
self . readline ( )
buflen = len ( self . buf )
else :
self . offset += ( buflen - len ( self . buf ) )
break
# do not keep comments in the syntax tree
if not self . keep_comme... |
def reg_concrete ( self , * args , ** kwargs ) :
"""Returns the contents of a register but , if that register is symbolic ,
raises a SimValueError .""" | e = self . registers . load ( * args , ** kwargs )
if self . solver . symbolic ( e ) :
raise SimValueError ( "target of reg_concrete is symbolic!" )
return self . solver . eval ( e ) |
def personal_sign ( self , message , account , password = None ) :
"""https : / / github . com / ethereum / go - ethereum / wiki / Management - APIs # personal _ sign
: param message : Message for sign
: type message : str
: param account : Account address
: type account : str
: param password : Password ... | return ( yield from self . rpc_call ( 'personal_sign' , [ message , account , password ] ) ) |
def get_removals_int_oxid ( self ) :
"""Returns a set of delithiation steps , e . g . set ( [ 1.0 2.0 4.0 ] ) etc . in order to
produce integer oxidation states of the redox metals .
If multiple redox metals are present , all combinations of reduction / oxidation are tested .
Note that having more than 3 redo... | # the elements that can possibly be oxidized
oxid_els = [ Element ( spec . symbol ) for spec in self . comp if is_redox_active_intercalation ( spec ) ]
numa = set ( )
for oxid_el in oxid_els :
numa = numa . union ( self . _get_int_removals_helper ( self . comp . copy ( ) , oxid_el , oxid_els , numa ) )
# convert fr... |
def dmail_create ( self , to_name , title , body ) :
"""Create a dmail ( Requires login )
Parameters :
to _ name ( str ) : The recipient ' s name .
title ( str ) : The title of the message .
body ( str ) : The body of the message .""" | params = { 'dmail[to_name]' : to_name , 'dmail[title]' : title , 'dmail[body]' : body }
return self . _get ( 'dmails.json' , params , 'POST' , auth = True ) |
def save_configuration_to_text_file ( register , configuration_file ) :
'''Saving configuration to text files from register object
Parameters
register : pybar . fei4 . register object
configuration _ file : string
Filename of the configuration file .''' | configuration_path , filename = os . path . split ( configuration_file )
if os . path . split ( configuration_path ) [ 1 ] == 'configs' :
configuration_path = os . path . split ( configuration_path ) [ 0 ]
filename = os . path . splitext ( filename ) [ 0 ] . strip ( )
register . configuration_file = os . path . joi... |
def collect_and_report ( self ) :
"""Target function for the metric reporting thread . This is a simple loop to
collect and report entity data every 1 second .""" | logger . debug ( "Metric reporting thread is now alive" )
def metric_work ( ) :
self . process ( )
if self . agent . is_timed_out ( ) :
logger . warn ( "Host agent offline for >1 min. Going to sit in a corner..." )
self . agent . reset ( )
return False
return True
every ( 1 , metric... |
def track_rr_ce_entry ( self , extent , offset , length ) : # type : ( int , int , int ) - > rockridge . RockRidgeContinuationBlock
'''Start tracking a new Rock Ridge Continuation Entry entry in this Volume
Descriptor , at the extent , offset , and length provided . Since Rock
Ridge Continuation Blocks are shar... | if not self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'This Primary Volume Descriptor is not yet initialized' )
for block in self . rr_ce_blocks :
if block . extent_location ( ) == extent :
break
else : # We didn ' t find it in the list , add it
block = rockridge . RockRidgeCo... |
def add_inverse_distances ( self , indices , periodic = True , indices2 = None ) :
"""Adds the inverse distances between atoms to the feature list .
Parameters
indices : can be of two types :
ndarray ( ( n , 2 ) , dtype = int ) :
n x 2 array with the pairs of atoms between which the inverse distances shall ... | from . distances import InverseDistanceFeature
atom_pairs = _parse_pairwise_input ( indices , indices2 , self . logger , fname = 'add_inverse_distances()' )
atom_pairs = self . _check_indices ( atom_pairs )
f = InverseDistanceFeature ( self . topology , atom_pairs , periodic = periodic )
self . __add_feature ( f ) |
def ignore ( name ) :
'''Ignore a specific program update . When an update is ignored the ' - ' and
version number at the end will be omitted , so " SecUpd2014-001-1.0 " becomes
" SecUpd2014-001 " . It will be removed automatically if present . An update
is successfully ignored when it no longer shows up afte... | # remove everything after and including the ' - ' in the updates name .
to_ignore = name . rsplit ( '-' , 1 ) [ 0 ]
cmd = [ 'softwareupdate' , '--ignore' , to_ignore ]
salt . utils . mac_utils . execute_return_success ( cmd )
return to_ignore in list_ignored ( ) |
def _modify_run_to_states ( self , state ) :
"""This is a special case . Inside a hierarchy state a step _ over is triggered and affects the last child .
In this case the self . run _ to _ states has to be modified in order to contain the parent of the hierarchy state .
Otherwise the execution won ' t respect t... | if self . _status . execution_mode is StateMachineExecutionStatus . FORWARD_OVER or self . _status . execution_mode is StateMachineExecutionStatus . FORWARD_OUT :
for state_path in copy . deepcopy ( self . run_to_states ) :
if state_path == state . get_path ( ) :
logger . verbose ( "Modifying ru... |
def _load_yml_config ( self , config_file ) :
"""loads a yaml str , creates a few constructs for pyaml , serializes and normalized the config data . Then
assigns the config data to self . _ data .
: param config _ file : A : string : loaded from a yaml file .""" | if not isinstance ( config_file , six . string_types ) :
raise TypeError ( 'config_file must be a str.' )
try :
def construct_yaml_int ( self , node ) :
obj = SafeConstructor . construct_yaml_int ( self , node )
data = ConfigInt ( obj , node . start_mark , node . end_mark )
return data
... |
def use_in ( ContentHandler ) :
"""Modify ContentHandler , a sub - class of
pycbc _ glue . ligolw . LIGOLWContentHandler , to cause it to use the Table ,
Column , and Stream classes defined in this module when parsing XML
documents .
Example :
> > > from pycbc _ glue . ligolw import ligolw
> > > class L... | def startColumn ( self , parent , attrs ) :
return Column ( attrs )
def startStream ( self , parent , attrs , __orig_startStream = ContentHandler . startStream ) :
if parent . tagName == ligolw . Table . tagName :
parent . _end_of_columns ( )
return TableStream ( attrs ) . config ( parent )
... |
def django_field_to_index ( field , ** attr ) :
'''Returns the index field type that would likely be associated with each Django type .''' | dj_type = field . get_internal_type ( )
if dj_type in ( 'DateField' , 'DateTimeField' ) :
return DateField ( ** attr )
elif dj_type in ( 'BooleanField' , 'NullBooleanField' ) :
return BooleanField ( ** attr )
elif dj_type in ( 'DecimalField' , 'FloatField' ) :
return NumberField ( coretype = 'float' , ** at... |
def register_elastic_task ( self , * args , ** kwargs ) :
"""Register an elastic task .""" | kwargs [ "task_class" ] = ElasticTask
return self . register_task ( * args , ** kwargs ) |
def _clean_up_gene_id ( geneid , sp , curie_map ) :
"""A series of identifier rewriting to conform with
standard gene identifiers .
: param geneid :
: param sp :
: return :""" | # special case for MGI
geneid = re . sub ( r'MGI:MGI:' , 'MGI:' , geneid )
# rewrite Ensembl - - > ENSEMBL
geneid = re . sub ( r'Ensembl' , 'ENSEMBL' , geneid )
# rewrite Gene : CELE - - > WormBase
# these are old - school cosmid identifier
geneid = re . sub ( r'Gene:CELE' , 'WormBase:' , geneid )
if sp == 'CAEEL' :
... |
def get_layer_ids ( self , rev = True ) :
"""Get IDs of image layers
: param rev : get layers reversed
: return : list of strings""" | layers = [ x [ 'Id' ] for x in self . d . history ( self . get_id ( ) ) ]
if not rev :
layers . reverse ( )
return layers |
def start ( self ) : # type : ( ) - > bool
"""Starts the framework
: return : True if the bundle has been started , False if it was already
running
: raise BundleException : A bundle failed to start""" | with self . _lock :
if self . _state in ( Bundle . STARTING , Bundle . ACTIVE ) : # Already started framework
return False
# Reset the stop event
self . _fw_stop_event . clear ( )
# Starting . . .
self . _state = Bundle . STARTING
self . _dispatcher . fire_bundle_event ( BundleEvent ( Bu... |
def get_unicode_property ( value , prop = None , is_bytes = False ) :
"""Retrieve the Unicode category from the table .""" | if prop is not None :
prop = unidata . unicode_alias [ '_' ] . get ( prop , prop )
try :
if prop == 'generalcategory' :
return get_gc_property ( value , is_bytes )
elif prop == 'script' :
return get_script_property ( value , is_bytes )
elif prop == 'scriptextensio... |
def rubberstamp ( rest ) :
"Approve something" | parts = [ "Bad credit? No credit? Slow credit?" ]
rest = rest . strip ( )
if rest :
parts . append ( "%s is" % rest )
karma . Karma . store . change ( rest , 1 )
parts . append ( "APPROVED!" )
return " " . join ( parts ) |
def connectionMade ( self ) :
"""Keep a reference to the protocol on the factory , and uses the
factory ' s store to find multiplexed connection factories .
Unfortunately , we can ' t add the protocol by TLS certificate
fingerprint , because the TLS handshake won ' t have completed
yet , so ` ` self . trans... | self . factory . protocols . add ( self )
self . _factories = multiplexing . FactoryDict ( self . store )
super ( AMP , self ) . connectionMade ( ) |
def get_none_packages ( self ) :
"""Get packages with None ( not founded ) , recursively""" | not_found = set ( )
for package_name , package in self . packages . items ( ) :
if package is None :
not_found . add ( package_name )
else :
if package . packages :
not_found = not_found | package . get_none_packages ( )
return not_found |
def unhumanize_delay ( delaystr ) :
'''Accept a string representing link propagation delay ( e . g . ,
'100 milliseconds ' or ' 100 msec ' or 100 millisec ' ) and return
a floating point number representing the delay in seconds .
Recognizes :
- us , usec , micros * all as microseconds
- ms , msec , millis... | if isinstance ( delaystr , float ) :
return delaystr
mobj = re . match ( '^\s*([\d\.]+)\s*(\w*)' , delaystr )
if not mobj :
return None
value , units = mobj . groups ( )
value = float ( value )
if not units :
divisor = 1.0
elif units == 'us' or units == 'usec' or units . startswith ( 'micros' ) :
diviso... |
def _get_minute_window_data ( self , assets , field , minutes_for_window ) :
"""Internal method that gets a window of adjusted minute data for an asset
and specified date range . Used to support the history API method for
minute bars .
Missing bars are filled with NaN .
Parameters
assets : iterable [ Asse... | return self . _minute_history_loader . history ( assets , minutes_for_window , field , False ) |
def K_angle_valve_Crane ( D1 , D2 , fd = None , style = 0 ) :
r'''Returns the loss coefficient for all types of angle valve , ( reduced
seat or throttled ) as shown in [ 1 ] _ .
If β = 1:
. . math : :
K = K _ 1 = K _ 2 = N \ cdot f _ d
Otherwise :
. . math : :
K _ 2 = \ frac { K + \ left [ 0.5(1 - \ b... | beta = D1 / D2
if style not in ( 0 , 1 , 2 ) :
raise Exception ( 'Valve style should be 0, 1, or 2' )
if fd is None :
fd = ft_Crane ( D2 )
if style == 0 or style == 2 :
K1 = 55.0 * fd
else :
K1 = 150.0 * fd
if beta == 1 :
return K1
# upstream and down
else :
return ( K1 + beta * ( 0.5 * ( 1 ... |
def art_msg ( self , arttag , colorname , file = sys . stdout ) :
"""Wrapper for easy emission of the calendar borders""" | self . msg ( self . art [ arttag ] , colorname , file = file ) |
def experiments_predictions_upsert_property ( self , experiment_id , run_id , properties ) :
"""Upsert property of a prodiction for an experiment .
Raises ValueError if given property dictionary results in an illegal
operation .
Parameters
experiment _ id : string
Unique experiment identifier
run _ id :... | # Get predition to ensure that it exists . Ensures that the combination
# of experiment and prediction identifier is valid .
if self . experiments_predictions_get ( experiment_id , run_id ) is None :
return None
# Return result of upsert for identifier model run
return self . predictions . upsert_object_property ( ... |
def collect ( nested_nodes , transform = None ) :
'''Return list containing the result of the ` transform ` function applied to
each item in the supplied list of nested nodes .
A custom transform function may be applied to each entry during the
flattening by specifying a function through the ` transform ` key... | items = [ ]
if transform is None :
transform = lambda node , parents , nodes , * args : node
def __collect__ ( node , parents , nodes , first , last , depth ) :
items . append ( transform ( node , parents , nodes , first , last , depth ) )
apply_depth_first ( nested_nodes , __collect__ )
return items |
def finalize ( self ) :
"""Output the duplicate scripts detected .""" | if self . total_duplicate > 0 :
print ( '{} duplicate scripts found' . format ( self . total_duplicate ) )
for duplicate in self . list_duplicate :
print ( duplicate ) |
def stdout_message ( message , prefix = 'INFO' , quiet = False , multiline = False , tabspaces = 4 , severity = '' ) :
"""Prints message to cli stdout while indicating type and severity
Args :
: message ( str ) : text characters to be printed to stdout
: prefix ( str ) : 4 - letter string message type identif... | prefix = prefix . upper ( )
tabspaces = int ( tabspaces )
# prefix color handling
choices = ( 'RED' , 'BLUE' , 'WHITE' , 'GREEN' , 'ORANGE' )
critical_status = ( 'ERROR' , 'FAIL' , 'WTF' , 'STOP' , 'HALT' , 'EXIT' , 'F*CK' )
if quiet :
return False
else :
if prefix in critical_status or severity . upper ( ) == ... |
def send ( self , * fields ) :
"""Serialize and send the given fields using the IB socket protocol .""" | if not self . isConnected ( ) :
raise ConnectionError ( 'Not connected' )
msg = io . StringIO ( )
for field in fields :
typ = type ( field )
if field in ( None , UNSET_INTEGER , UNSET_DOUBLE ) :
s = ''
elif typ in ( str , int , float ) :
s = str ( field )
elif typ is bool :
s... |
async def _read_packet ( self , packet_type = MysqlPacket ) :
"""Read an entire " mysql packet " in its entirety from the network
and return a MysqlPacket type that represents the results .""" | buff = b''
while True :
try :
packet_header = await self . _read_bytes ( 4 )
except asyncio . CancelledError :
self . _close_on_cancel ( )
raise
btrl , btrh , packet_number = struct . unpack ( '<HBB' , packet_header )
bytes_to_read = btrl + ( btrh << 16 )
# Outbound and inbou... |
def ast_from_class ( self , klass , modname = None ) :
"""get astroid for the given class""" | if modname is None :
try :
modname = klass . __module__
except AttributeError as exc :
raise exceptions . AstroidBuildingError ( "Unable to get module for class {class_name}." , cls = klass , class_repr = safe_repr ( klass ) , modname = modname , ) from exc
modastroid = self . ast_from_module_na... |
def dumps ( self ) :
"""Represent the section as a string in LaTeX syntax .
Returns
str""" | if not self . numbering :
num = '*'
else :
num = ''
string = Command ( self . latex_name + num , self . title ) . dumps ( )
if self . label is not None :
string += '%\n' + self . label . dumps ( )
string += '%\n' + self . dumps_content ( )
return string |
def FillDeviceCapabilities ( device , descriptor ) :
"""Fill out device capabilities .
Fills the HidCapabilitites of the device into descriptor .
Args :
device : A handle to the open device
descriptor : DeviceDescriptor to populate with the
capabilities
Returns :
none
Raises :
WindowsError when un... | preparsed_data = PHIDP_PREPARSED_DATA ( 0 )
ret = hid . HidD_GetPreparsedData ( device , ctypes . byref ( preparsed_data ) )
if not ret :
raise ctypes . WinError ( )
try :
caps = HidCapabilities ( )
ret = hid . HidP_GetCaps ( preparsed_data , ctypes . byref ( caps ) )
if ret != HIDP_STATUS_SUCCESS :
... |
def get_all_interface_details ( devId , auth , url ) :
"""function takes the devId of a specific device and the ifindex value assigned to a specific interface
and issues a RESTFUL call to get the interface details
file as known by the HP IMC Base Platform ICC module for the target device .
: param devId : int... | get_all_interface_details_url = "/imcrs/plat/res/device/" + str ( devId ) + "/interface/?start=0&size=1000&desc=false&total=false"
f_url = url + get_all_interface_details_url
payload = None
# creates the URL using the payload variable as the contents
r = requests . get ( f_url , auth = auth , headers = HEADERS )
# r . ... |
def find_resistance ( record ) :
"""Infer the antibiotics resistance of the given record .
Arguments :
record ( ` ~ Bio . SeqRecord . SeqRecord ` ) : an annotated sequence .
Raises :
RuntimeError : when there ' s not exactly one resistance cassette .""" | for feature in record . features :
labels = set ( feature . qualifiers . get ( "label" , [ ] ) )
cassettes = labels . intersection ( _ANTIBIOTICS )
if len ( cassettes ) > 1 :
raise RuntimeError ( "multiple resistance cassettes detected" )
elif len ( cassettes ) == 1 :
return _ANTIBIOTICS... |
def iterate_schema ( fields , schema , path_prefix = '' ) :
"""Iterate over all schema sub - fields .
This will iterate over all field definitions in the schema . Some field v
alues might be None .
: param fields : field values to iterate over
: type fields : dict
: param schema : schema to iterate over
... | if path_prefix and path_prefix [ - 1 ] != '.' :
path_prefix += '.'
for field_schema in schema :
name = field_schema [ 'name' ]
if 'group' in field_schema :
for rvals in iterate_schema ( fields [ name ] if name in fields else { } , field_schema [ 'group' ] , '{}{}' . format ( path_prefix , name ) ) :... |
def result ( filetype = "PNG" , saveas = None , host = cytoscape_host , port = cytoscape_port ) :
"""Checks the current network .
Note : works only on localhost
: param filetype : file type , default = " PNG "
: param saveas : / path / to / non / tmp / file . prefix
: param host : cytoscape host address , d... | sleep ( 1 )
def MAKETMP ( ) :
( fd , tmp_file ) = tempfile . mkstemp ( )
tmp_file = "/tmp/" + tmp_file . split ( "/" ) [ - 1 ]
return tmp_file
outfile = MAKETMP ( )
extensions = { "PNG" : ".png" , "PDF" : ".pdf" , "CYS" : ".cys" , "CYJS" : ".cyjs" }
ext = extensions [ filetype ]
response = cytoscape ( "view... |
def load_stl ( file_obj , file_type = None , ** kwargs ) :
"""Load an STL file from a file object .
Parameters
file _ obj : open file - like object
file _ type : not used
Returns
loaded : kwargs for a Trimesh constructor with keys :
vertices : ( n , 3 ) float , vertices
faces : ( m , 3 ) int , indexes... | # save start of file obj
file_pos = file_obj . tell ( )
try : # check the file for a header which matches the file length
# if that is true , it is almost certainly a binary STL file
# if the header doesn ' t match the file length a HeaderError will be
# raised
return load_stl_binary ( file_obj )
except HeaderError... |
def CheckDependencies ( self , verbose_output = True ) :
"""Checks the availability of the dependencies .
Args :
verbose _ output ( Optional [ bool ] ) : True if output should be verbose .
Returns :
bool : True if the dependencies are available , False otherwise .""" | print ( 'Checking availability and versions of dependencies.' )
check_result = True
for module_name , dependency in sorted ( self . dependencies . items ( ) ) :
if module_name == 'sqlite3' :
result , status_message = self . _CheckSQLite3 ( )
else :
result , status_message = self . _CheckPythonMo... |
def _read_pnm_header ( self , data ) :
"""Read PNM header and initialize instance .""" | bpm = data [ 1 : 2 ] in b"14"
regroups = re . search ( b"" . join ( ( b"(^(P[123456]|P7 332)\s+(?:#.*[\r\n])*" , b"\s*(\d+)\s+(?:#.*[\r\n])*" , b"\s*(\d+)\s+(?:#.*[\r\n])*" * ( not bpm ) , b"\s*(\d+)\s(?:\s*#.*[\r\n]\s)*)" ) ) , data ) . groups ( ) + ( 1 , ) * bpm
self . header = regroups [ 0 ]
self . magicnum = regrou... |
def filter_by ( self , ** filters ) :
'''Filter for the names in ` ` filters ` ` being equal to the associated
values . Cannot be used for sub - objects since keys must be strings''' | for name , value in filters . items ( ) :
self . filter ( resolve_name ( self . type , name ) == value )
return self |
def clear_rtag ( opts ) :
'''Remove the rtag file''' | try :
os . remove ( rtag ( opts ) )
except OSError as exc :
if exc . errno != errno . ENOENT : # Using _ _ str _ _ ( ) here to get the fully - formatted error message
# ( error number , error message , path )
log . warning ( 'Encountered error removing rtag: %s' , exc . __str__ ( ) ) |
def segmenttable_get_by_name ( xmldoc , name ) :
"""Retrieve the segmentlists whose name equals name . The result is a
segmentlistdict indexed by instrument .
The output of this function is not coalesced , each segmentlist
contains the segments as found in the segment table .
NOTE : this is a light - weight... | # find required tables
def_table = lsctables . SegmentDefTable . get_table ( xmldoc )
seg_table = lsctables . SegmentTable . get_table ( xmldoc )
# segment _ def _ id - - > instrument names mapping but only for
# segment _ definer entries bearing the requested name
instrument_index = dict ( ( row . segment_def_id , row... |
def hydrate_duration ( months , days , seconds , nanoseconds ) :
"""Hydrator for ` Duration ` values .
: param months :
: param days :
: param seconds :
: param nanoseconds :
: return : ` duration ` namedtuple""" | return Duration ( months = months , days = days , seconds = seconds , nanoseconds = nanoseconds ) |
def get_locus ( sequences , kir = False , verbose = False , refdata = None , evalue = 10 ) :
"""Gets the locus of the sequence by running blastn
: param sequences : sequenences to blast
: param kir : bool whether the sequences are KIR or not
: rtype : ` ` str ` `
Example usage :
> > > from Bio . Seq impor... | if not refdata :
refdata = ReferenceData ( )
file_id = str ( randomid ( ) )
input_fasta = file_id + ".fasta"
output_xml = file_id + ".xml"
SeqIO . write ( sequences , input_fasta , "fasta" )
blastn_cline = NcbiblastnCommandline ( query = input_fasta , db = refdata . blastdb , evalue = evalue , outfmt = 5 , reward =... |
def _write ( self , text , x , y , colour = Screen . COLOUR_WHITE , attr = Screen . A_NORMAL , bg = Screen . COLOUR_BLACK ) :
"""Write some text to the specified location in the current image .
: param text : The text to be added .
: param x : The X coordinate in the image .
: param y : The Y coordinate in th... | # Limit checks to ensure that we don ' t try to draw off the end of the arrays
if y >= self . _height or x >= self . _width :
return
# Limit text to draw to visible line
if len ( text ) + x > self . _width :
text = text [ : self . _width - x ]
# Now draw it !
self . _plain_image [ y ] = text . join ( [ self . _... |
def connectionLost ( self , reason ) :
"""Called when the body is complete or the connection was lost .
@ note : As the body length is usually not known at the beginning of the
response we expect a L { PotentialDataLoss } when Twitter closes the
stream , instead of L { ResponseDone } . Other exceptions are tr... | self . setTimeout ( None )
if reason . check ( ResponseDone , PotentialDataLoss ) :
self . deferred . callback ( None )
else :
self . deferred . errback ( reason ) |
def create_gzip_cache ( pelican ) :
'''Create a gzip cache file for every file that a webserver would
reasonably want to cache ( e . g . , text type files ) .
: param pelican : The Pelican instance''' | for dirpath , _ , filenames in os . walk ( pelican . settings [ 'OUTPUT_PATH' ] ) :
for name in filenames :
if should_compress ( name ) :
filepath = os . path . join ( dirpath , name )
create_gzip_file ( filepath , should_overwrite ( pelican . settings ) ) |
def tag ( ctx , input , output ) :
"""Output POS - tagged tokens .""" | log . info ( 'chemdataextractor.pos.tag' )
log . info ( 'Reading %s' % input . name )
doc = Document . from_file ( input )
for element in doc . elements :
if isinstance ( element , Text ) :
for sentence in element . sentences :
output . write ( u' ' . join ( u'/' . join ( [ token , tag ] ) for t... |
def update ( self ) :
'''Updates LaserData .''' | if self . hasproxy ( ) :
sonarD = SonarData ( )
range = 0
data = self . proxy . getSonarData ( )
sonarD . range = data . range
sonarD . maxAngle = data . maxAngle
sonarD . minAngle = data . minAngle
sonarD . maxRange = data . maxRange
sonarD . minRange = data . minRange
self . lock .... |
def as_slug_expression ( attr ) :
"""Converts the given instrumented string attribute into an SQL expression
that can be used as a slug .
Slugs are identifiers for members in a collection that can be used in an
URL . We create slug columns by replacing non - URL characters with dashes
and lower casing the r... | slug_expr = sa_func . replace ( attr , ' ' , '-' )
slug_expr = sa_func . replace ( slug_expr , '_' , '-' )
slug_expr = sa_func . lower ( slug_expr )
return slug_expr |
def parts ( path ) : # type : ( Text ) - > List [ Text ]
"""Split a path in to its component parts .
Arguments :
path ( str ) : Path to split in to parts .
Returns :
list : List of components
Example :
> > > parts ( ' / foo / bar / baz ' )
[ ' / ' , ' foo ' , ' bar ' , ' baz ' ]""" | _path = normpath ( path )
components = _path . strip ( "/" )
_parts = [ "/" if _path . startswith ( "/" ) else "./" ]
if components :
_parts += components . split ( "/" )
return _parts |
def block ( self , warn_only = False ) :
"""blocked executation .""" | self . _state = "not finished"
if self . _return_code is None :
proc = subprocess . Popen ( self . cmd , cwd = self . cwd , env = self . env , stdout = subprocess . PIPE , stderr = subprocess . PIPE )
self . _stdout , self . _stderr = proc . communicate ( timeout = self . timeout )
self . _return_code = pro... |
def _get_ordered_access_keys ( self ) :
"Return ordered access keys for inspection . Used for testing ." | self . access_log_lock . acquire ( )
r = [ e . key for e in self . access_log if e . is_valid ]
self . access_log_lock . release ( )
return r |
def compute_all_metrics_statistics ( all_results ) :
"""Computes statistics of metrics across multiple decodings .
Args :
all _ results : dict of 3 - D numpy arrays .
Each array has shape = ( num _ decodes , num _ samples , num _ frames ) .
Returns :
statistics : dict of 1 - D numpy arrays , shape = ( num... | statistics = { }
decode_inds = { }
all_metrics = all_results . keys ( )
for key in all_metrics :
values = all_results [ key ]
statistics [ key + "_MEAN" ] = np . mean ( values , axis = 0 )
statistics [ key + "_STD" ] = np . std ( values , axis = 0 )
min_stats , min_decode_ind = reduce_to_best_decode ( v... |
def get_saved_rules ( conf_file = None ) :
'''Return a data structure of the rules in the conf file
CLI Example :
. . code - block : : bash
salt ' * ' nftables . get _ saved _ rules''' | if _conf ( ) and not conf_file :
conf_file = _conf ( )
with salt . utils . files . fopen ( conf_file ) as fp_ :
lines = salt . utils . data . decode ( fp_ . readlines ( ) )
rules = [ ]
for line in lines :
tmpline = line . strip ( )
if not tmpline :
continue
if tmpline . startswith ( '#' ) :
... |
def _set_src_host_any_sip ( self , v , load = False ) :
"""Setter method for src _ host _ any _ sip , mapped from YANG variable / ipv6 _ acl / ipv6 / access _ list / extended / seq / src _ host _ any _ sip ( union )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ src _ ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = [ RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'host' : { 'value' : 2 } , u'any' : { 'value' : 1 } } , ) , RestrictedClassType ( base_type = unicode , restriction_dict = { '... |
def to_array ( self ) :
"""Serializes this InputMediaDocument to a dictionary .
: return : dictionary representation of this object .
: rtype : dict""" | array = super ( InputMediaDocument , self ) . to_array ( )
array [ 'type' ] = u ( self . type )
# py2 : type unicode , py3 : type str
array [ 'media' ] = u ( self . media )
# py2 : type unicode , py3 : type str
if self . thumb is not None :
if isinstance ( self . thumb , InputFile ) :
array [ 'thumb' ] = se... |
def dataframe ( df , ** kwargs ) :
"""Print table with data from the given pandas DataFrame
Parameters
df : DataFrame
A pandas DataFrame with the table to print""" | table ( df . values , list ( df . columns ) , ** kwargs ) |
def get_word_from_data ( self , data , offset ) :
"""Convert two bytes of data to a word ( little endian )
' offset ' is assumed to index into a word array . So setting it to
N will return a dword out of the data starting at offset N * 2.
Returns None if the data can ' t be turned into a word .""" | if ( offset + 1 ) * 2 > len ( data ) :
return None
return struct . unpack ( '<H' , data [ offset * 2 : ( offset + 1 ) * 2 ] ) [ 0 ] |
def DbGetDeviceClassList ( self , argin ) :
"""Get Tango classes / device list embedded in a specific device server
: param argin : Device server process name
: type : tango . DevString
: return : Str [ 0 ] = Device name
Str [ 1 ] = Tango class
Str [ n ] = Device name
Str [ n + 1 ] = Tango class
: rty... | self . _log . debug ( "In DbGetDeviceClassList()" )
return self . db . get_device_class_list ( argin ) |
def detect_vcs ( ) :
"""Detect the version control system used for the current directory .""" | location = os . path . abspath ( '.' )
while True :
for vcs in Git , Mercurial , Bazaar , Subversion :
if vcs . detect ( location ) :
return vcs
parent = os . path . dirname ( location )
if parent == location :
raise Failure ( "Couldn't find version control data" " (git/hg/bzr/sv... |
def get_success_url ( self ) :
"""By default we use the referer that was stuffed in our
form when it was created""" | if self . success_url : # if our smart url references an object , pass that in
if self . success_url . find ( '@' ) > 0 :
return smart_url ( self . success_url , self . object )
else :
return smart_url ( self . success_url , None )
elif 'loc' in self . form . cleaned_data :
return self . for... |
def ground_height ( self ) :
'''return height above ground in feet''' | lat = self . pkt [ 'I105' ] [ 'Lat' ] [ 'val' ]
lon = self . pkt [ 'I105' ] [ 'Lon' ] [ 'val' ]
global ElevationMap
ret = ElevationMap . GetElevation ( lat , lon )
ret -= gen_settings . wgs84_to_AMSL
return ret * 3.2807 |
def get_marks ( self ) :
"""Get a list of the names of all currently set marks .
: rtype : list""" | data = self . message ( MessageType . GET_MARKS , '' )
return json . loads ( data ) |
def update_collection ( self , collection ) :
"""Update a mongodb collection .""" | node = self . node
flow = node if node . is_flow else node . flow
# Build the key used to store the entry in the document .
key = node . name
if node . is_task :
key = "w" + str ( node . pos [ 0 ] ) + "_t" + str ( node . pos [ 1 ] )
elif node . is_work :
key = "w" + str ( node . pos )
db = collection . database... |
def from_httplib ( ResponseCls , r , ** response_kw ) :
"""Given an : class : ` httplib . HTTPResponse ` instance ` ` r ` ` , return a
corresponding : class : ` urllib3 . response . HTTPResponse ` object .
Remaining parameters are passed to the HTTPResponse constructor , along
with ` ` original _ response = r... | headers = HTTPHeaderDict ( )
for k , v in r . getheaders ( ) :
headers . add ( k , v )
# HTTPResponse objects in Python 3 don ' t have a . strict attribute
strict = getattr ( r , 'strict' , 0 )
return ResponseCls ( body = r , headers = headers , status = r . status , version = r . version , reason = r . reason , st... |
def before_scenario ( context , scenario ) :
"""Scenario initialization
: param context : behave context
: param scenario : running scenario""" | # Configure reset properties from behave tags
if 'no_reset_app' in scenario . tags :
os . environ [ "AppiumCapabilities_noReset" ] = 'true'
os . environ [ "AppiumCapabilities_fullReset" ] = 'false'
elif 'reset_app' in scenario . tags :
os . environ [ "AppiumCapabilities_noReset" ] = 'false'
os . environ... |
def to_jsons ( graph : BELGraph , ** kwargs ) -> str :
"""Dump this graph as a Node - Link JSON object to a string .""" | graph_json_str = to_json ( graph )
return json . dumps ( graph_json_str , ensure_ascii = False , ** kwargs ) |
def remove_all_network_profiles ( self , obj ) :
"""Remove all the AP profiles .""" | profile_name_list = self . network_profile_name_list ( obj )
for profile_name in profile_name_list :
self . _logger . debug ( "delete profile: %s" , profile_name )
str_buf = create_unicode_buffer ( profile_name )
ret = self . _wlan_delete_profile ( self . _handle , obj [ 'guid' ] , str_buf )
self . _log... |
def _skip_to_nonblank ( f , spacegroup , setting ) :
"""Read lines from f until a nonblank line not starting with a
hash ( # ) is encountered and returns this and the next line .""" | while True :
line1 = f . readline ( )
if not line1 :
raise SpacegroupNotFoundError ( 'invalid spacegroup %s, setting %i not found in data base' % ( spacegroup , setting ) )
line1 . strip ( )
if line1 and not line1 . startswith ( '#' ) :
line2 = f . readline ( )
break
return line1... |
def get_all_last_24h_kline ( self ) :
"""获取所有ticker
: param _ async :
: return :""" | params = { }
url = u . MARKET_URL + '/market/tickers'
def _wrapper ( _func ) :
@ wraps ( _func )
def handle ( ) :
_func ( http_get_request ( url , params ) )
return handle
return _wrapper |
def save_config ( self , volume , channel , theme , netease ) :
"""存储历史记录和登陆信息""" | self . login_data [ 'cookies' ] = self . cookies
self . login_data [ 'volume' ] = volume
self . login_data [ 'channel' ] = channel
self . login_data [ 'theme_id' ] = theme
self . login_data [ 'netease' ] = netease
self . login_data [ 'run_times' ] = self . run_times + 1
self . login_data [ 'last_time' ] = self . last_t... |
def show ( self , y : Image = None , ax : plt . Axes = None , figsize : tuple = ( 3 , 3 ) , title : Optional [ str ] = None , hide_axis : bool = True , color : str = 'white' , ** kwargs ) :
"Show the ` ImageBBox ` on ` ax ` ." | if ax is None :
_ , ax = plt . subplots ( figsize = figsize )
bboxes , lbls = self . _compute_boxes ( )
h , w = self . flow . size
bboxes . add_ ( 1 ) . mul_ ( torch . tensor ( [ h / 2 , w / 2 , h / 2 , w / 2 ] ) ) . long ( )
for i , bbox in enumerate ( bboxes ) :
if lbls is not None :
text = str ( lbls... |
def split_sentences ( s , pad = 0 ) :
"""Split sentences for formatting .""" | sentences = [ ]
for index , sentence in enumerate ( s . split ( '. ' ) ) :
padding = ''
if index > 0 :
padding = ' ' * ( pad + 1 )
if sentence . endswith ( '.' ) :
sentence = sentence [ : - 1 ]
sentences . append ( '%s %s.' % ( padding , sentence . strip ( ) ) )
return "\n" . join ( sent... |
def refresh ( ctx , opts , owner_repo_identifier , show_tokens , yes ) :
"""Refresh an entitlement in a repository .
Note that this changes the token associated with the entitlement .
- OWNER / REPO / IDENTIFIER : Specify the OWNER namespace ( i . e . user or org ) ,
and the REPO name that has an entitlement ... | owner , repo , identifier = owner_repo_identifier
refresh_args = { "identifier" : click . style ( identifier , bold = True ) , "repository" : click . style ( repo , bold = True ) , }
# Use stderr for messages if the output is something else ( e . g . # JSON )
use_stderr = opts . output != "pretty"
prompt = ( "refresh t... |
def get_account_entitlements_batch ( self , user_ids ) :
"""GetAccountEntitlementsBatch .
[ Preview API ] Returns AccountEntitlements that are currently assigned to the given list of users in the account
: param [ str ] user _ ids : List of user Ids .
: rtype : [ AccountEntitlement ]""" | route_values = { }
route_values [ 'action' ] = 'GetUsersEntitlements'
content = self . _serialize . body ( user_ids , '[str]' )
response = self . _send ( http_method = 'POST' , location_id = 'cc3a0130-78ad-4a00-b1ca-49bef42f4656' , version = '5.0-preview.1' , route_values = route_values , content = content )
return sel... |
def lock ( self , * args ) :
"""Lock table ( s ) .
Locks the object model table so that atomic update is possible .
Simulatenous database access request pend until the lock is unlock ( ) ' ed .
See http : / / dev . mysql . com / doc / refman / 5.0 / en / lock - tables . html
@ param * args : Models to be lo... | if not args :
args = [ self . model ]
cursor = connection . cursor ( )
tables = ", " . join ( [ '%s WRITE' % connection . ops . quote_name ( model . _meta . db_table ) for model in args ] )
logger . debug ( 'LOCK TABLES %s' % tables )
cursor . execute ( "LOCK TABLES %s" % tables )
row = cursor . fetchone ( )
return... |
def delete ( names , yes ) :
"""Delete a training job .""" | failures = False
for name in names :
try :
experiment = ExperimentClient ( ) . get ( normalize_job_name ( name ) )
except FloydException :
experiment = ExperimentClient ( ) . get ( name )
if not experiment :
failures = True
continue
if not yes and not click . confirm ( "D... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.