signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def add_continuous_regressors_to_design_matrix ( self , regressors ) :
"""add _ continuous _ regressors _ to _ design _ matrix appends continuously sampled regressors to the existing design matrix . One uses this addition to the design matrix when one expects the data to contain nuisance factors that aren ' t tied ... | previous_design_matrix_shape = self . design_matrix . shape
if len ( regressors . shape ) == 1 :
regressors = regressors [ np . newaxis , : ]
if regressors . shape [ 1 ] != self . resampled_signal . shape [ 1 ] :
self . logger . warning ( 'additional regressor shape %s does not conform to designmatrix shape %s'... |
def disableGyro ( self ) :
"""Specifies the device should NOT write gyro values to the FIFO , is not applied until enableFIFO is called .
: return :""" | logger . debug ( "Disabling gyro sensor" )
self . fifoSensorMask &= ~ self . enableGyroMask
self . _gyroEnabled = False
self . _setSampleSizeBytes ( ) |
def pivot_query_as_matrix ( facet = None , facet_pivot_fields = None , ** kwargs ) :
"""Pivot query""" | if facet_pivot_fields is None :
facet_pivot_fields = [ ]
logging . info ( "Additional args: {}" . format ( kwargs ) )
fp = search_associations ( rows = 0 , facet_fields = [ facet ] , facet_pivot_fields = facet_pivot_fields , ** kwargs ) [ 'facet_pivot' ]
# we assume only one
results = list ( fp . items ( ) ) [ 0 ] ... |
def erase ( self , partition , timeout_ms = None ) :
"""Erases the given partition .""" | self . _simple_command ( 'erase' , arg = partition , timeout_ms = timeout_ms ) |
def _gser ( a , x ) :
"Series representation of Gamma . NumRec sect 6.1." | ITMAX = 100
EPS = 3.e-7
gln = lgamma ( a )
assert ( x >= 0 ) , 'x < 0 in gser'
if x == 0 :
return 0 , gln
ap = a
delt = sum = 1. / a
for i in range ( ITMAX ) :
ap = ap + 1.
delt = delt * x / ap
sum = sum + delt
if abs ( delt ) < abs ( sum ) * EPS :
break
else :
print ( 'a too large, ITMA... |
def verify_item_signature ( signature_attribute , encrypted_item , verification_key , crypto_config ) : # type : ( dynamodb _ types . BINARY _ ATTRIBUTE , dynamodb _ types . ITEM , DelegatedKey , CryptoConfig ) - > None
"""Verify the item signature .
: param dict signature _ attribute : Item signature DynamoDB at... | signature = signature_attribute [ Tag . BINARY . dynamodb_tag ]
verification_key . verify ( algorithm = verification_key . algorithm , signature = signature , data = _string_to_sign ( item = encrypted_item , table_name = crypto_config . encryption_context . table_name , attribute_actions = crypto_config . attribute_act... |
def get_object_collection ( self , object_name = '' ) :
"""If the remote end exposes a collection of objects under the supplied object name ( empty
for top level ) , this method returns a dictionary of these objects stored under their
names on the server .
This function performs n + 1 calls to the server , wh... | object_names = self . get_object ( object_name ) . get_objects ( )
return { obj : self . get_object ( obj ) for obj in object_names } |
def get_coordinates_pdb ( filename ) :
"""Get coordinates from the first chain in a pdb file
and return a vectorset with all the coordinates .
Parameters
filename : string
Filename to read
Returns
atoms : list
List of atomic types
V : array
( N , 3 ) where N is number of atoms""" | # PDB files tend to be a bit of a mess . The x , y and z coordinates
# are supposed to be in column 31-38 , 39-46 and 47-54 , but this is
# not always the case .
# Because of this the three first columns containing a decimal is used .
# Since the format doesn ' t require a space between columns , we use the
# above col... |
def publish ( self , titles ) :
"""Publish a set of episodes to the Podcast ' s RSS feed .
: param titles :
Either a single episode title or a sequence of episode titles to
publish .""" | if isinstance ( titles , Sequence ) and not isinstance ( titles , six . string_types ) :
for title in titles :
self . episodes [ title ] . publish ( )
elif isinstance ( titles , six . string_types ) :
self . episodes [ titles ] . publish ( )
else :
raise TypeError ( 'titles must be a string or a seq... |
def _JModule ( spec , javaname ) :
"""( internal ) Front end for creating a java module dynamically""" | cls = _JImportFactory ( spec , javaname )
out = cls ( spec . name )
return out |
def columns ( self , ** kw ) :
"""Creates a results set of column names in specified tables by
executing the ODBC SQLColumns function . Each row fetched has the
following columns .
: param table : the table tname
: param catalog : the catalog name
: param schema : the schmea name
: param column : string... | fut = self . _run_operation ( self . _impl . columns , ** kw )
return fut |
def _make_info ( shape_list , num_classes ) :
"""Create an info - like tuple for feature given some shapes and vocab size .""" | feature_info = collections . namedtuple ( "FeatureInfo" , [ "shape" , "num_classes" ] )
cur_shape = list ( shape_list [ 0 ] )
# We need to merge the provided shapes , put None where they disagree .
for shape in shape_list :
if len ( shape ) != len ( cur_shape ) :
raise ValueError ( "Shapes need to have the ... |
def build_table_schema ( data , index = True , primary_key = None , version = True ) :
"""Create a Table schema from ` ` data ` ` .
Parameters
data : Series , DataFrame
index : bool , default True
Whether to include ` ` data . index ` ` in the schema .
primary _ key : bool or None , default True
column ... | if index is True :
data = set_default_names ( data )
schema = { }
fields = [ ]
if index :
if data . index . nlevels > 1 :
for level in data . index . levels :
fields . append ( convert_pandas_type_to_json_field ( level ) )
else :
fields . append ( convert_pandas_type_to_json_fiel... |
def c_array ( ctype , values ) :
"""Convert a python string to c array .""" | if isinstance ( values , np . ndarray ) and values . dtype . itemsize == ctypes . sizeof ( ctype ) :
return ( ctype * len ( values ) ) . from_buffer_copy ( values )
return ( ctype * len ( values ) ) ( * values ) |
def update_empty_fields ( self , ** kwargs ) :
"""Updates the field of info about an OTU that might not be filled in by a match _ names or taxon call .""" | if self . _is_deprecated is None :
self . _is_deprecated = kwargs . get ( 'is_deprecated' )
if self . _is_dubious is None :
self . _is_dubious = kwargs . get ( 'is_dubious' )
if self . _is_synonym is None :
self . _is_synonym = kwargs . get ( 'is_synonym' )
if self . _synonyms is _EMPTY_TUPLE :
self . _... |
def _set_enhanced_voq_discard_pkts ( self , v , load = False ) :
"""Setter method for enhanced _ voq _ discard _ pkts , mapped from YANG variable / telemetry / profile / enhanced _ voq _ discard _ pkts ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ enhanced _ ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "name" , enhanced_voq_discard_pkts . enhanced_voq_discard_pkts , yang_name = "enhanced-voq-discard-pkts" , rest_name = "enhanced-voq-discard-pkts" , parent = self , is_container = 'list' , user_ordered = False ... |
def parse_args ( args = None ) :
"""Parse command line arguments and return a dictionary of options
for ttfautohint . ttfautohint function .
` args ` can be either None , a list of strings , or a single string ,
that is split into individual options with ` shlex . split ` .
When ` args ` is None , the conso... | import argparse
from ttfautohint import __version__ , libttfautohint
from ttfautohint . cli import USAGE , DESCRIPTION , EPILOG
version_string = "ttfautohint-py %s (libttfautohint %s)" % ( __version__ , libttfautohint . version_string )
if args is None :
capture_sys_exit = False
else :
capture_sys_exit = True
... |
def get_ec_index ( self , ec_handle ) :
'''Get the index of the execution context with the given handle .
@ param ec _ handle The handle of the execution context to look for .
@ type ec _ handle str
@ return The index into the owned + participated arrays , suitable for
use in methods such as @ ref activate ... | with self . _mutex :
for ii , ec in enumerate ( self . owned_ecs ) :
if ec . handle == ec_handle :
return ii
for ii , ec in enumerate ( self . participating_ecs ) :
if ec . handle == ec_handle :
return ii + len ( self . owned_ecs )
raise exceptions . NoECWithHandleErr... |
def _set_all_lims ( self , which , lim , d , scale , fontsize = None ) :
"""Set limits and ticks for an axis for whole figure .
This will set axis limits and tick marks for the entire figure .
It can be overridden in the SinglePlot class .
Args :
which ( str ) : The indicator of which part of the plots
to... | setattr ( self . general , which + 'lims' , lim )
setattr ( self . general , 'd' + which , d )
setattr ( self . general , which + 'scale' , scale )
if fontsize is not None :
setattr ( self . general , which + '_tick_label_fontsize' , fontsize )
return |
def text_height ( text ) :
"""Return the total height of the < text > and the length from the
base point to the top of the text box .""" | ( d1 , d2 , ymin , ymax ) = get_dimension ( text )
return ( ymax - ymin , ymax ) |
def set_remote_host_environment_variable ( host , variable_name , variable_value , env_file = '/etc/bashrc' ) :
"""Sets an environment variable on the remote host in the
specified environment file
: param host : ( str ) host to set environment variable on
: param variable _ name : ( str ) name of the variable... | log = logging . getLogger ( mod_logger + '.set_remote_host_environment_variable' )
if not isinstance ( host , basestring ) :
msg = 'host argument must be a string'
log . error ( msg )
raise TypeError ( msg )
if not isinstance ( variable_name , basestring ) :
msg = 'variable_name argument must be a strin... |
def read ( self , filename ) :
"""Reads config file""" | try :
conf_file = open ( filename , 'r' )
config = conf_file . read ( )
config_keys = re . findall ( r'\[.*\]' , config )
self . section_keys = [ key [ 1 : - 1 ] for key in config_keys ]
except IOError as e : # Pass if file not found
if e . errno != 2 :
raise
return self . config_parser . re... |
def distance_correlation_sqr ( x , y , ** kwargs ) :
"""distance _ correlation _ sqr ( x , y , * , exponent = 1)
Computes the usual ( biased ) estimator for the squared distance correlation
between two random vectors .
Parameters
x : array _ like
First random vector . The columns correspond with the indiv... | if _can_use_fast_algorithm ( x , y , ** kwargs ) :
return _distance_correlation_sqr_fast ( x , y )
else :
return _distance_correlation_sqr_naive ( x , y , ** kwargs ) |
def forward ( node , analysis ) :
"""Perform a given analysis on all functions within an AST .""" | if not isinstance ( analysis , Forward ) :
raise TypeError ( 'not a valid forward analysis object' )
for succ in gast . walk ( node ) :
if isinstance ( succ , gast . FunctionDef ) :
cfg_obj = CFG . build_cfg ( succ )
analysis . visit ( cfg_obj . entry )
return node |
def scrnaseq_concatenate_metadata ( samples ) :
"""Create file same dimension than mtx . colnames
with metadata and sample name to help in the
creation of the SC object .""" | barcodes = { }
counts = ""
metadata = { }
has_sample_barcodes = False
for sample in dd . sample_data_iterator ( samples ) :
if dd . get_sample_barcodes ( sample ) :
has_sample_barcodes = True
with open ( dd . get_sample_barcodes ( sample ) ) as inh :
for line in inh :
col... |
def _set_axis_limits ( self , axis , view , subplots , ranges ) :
"""Compute extents for current view and apply as axis limits""" | # Extents
extents = self . get_extents ( view , ranges )
if not extents or self . overlaid :
axis . autoscale_view ( scalex = True , scaley = True )
return
valid_lim = lambda c : util . isnumeric ( c ) and not np . isnan ( c )
coords = [ coord if np . isreal ( coord ) or isinstance ( coord , np . datetime64 ) e... |
def json ( self ) :
"""str : the ontology serialized in json format .""" | return json . dumps ( self . terms , indent = 4 , sort_keys = True , default = operator . attrgetter ( "__deref__" ) ) |
def load_from_rho_file ( self , filename ) :
"""Convenience function that loads two parameter sets from a rho . dat
file , as used by CRMod for forward resistivity / phase models .
Parameters
filename : string , file path
filename of rho . dat file
Returns
cid _ mag : int
ID of magnitude parameter set... | data = np . loadtxt ( filename , skiprows = 1 )
cid_mag = self . add_data ( data [ : , 0 ] )
cid_pha = self . add_data ( data [ : , 1 ] )
return cid_mag , cid_pha |
def match_sequence ( self , tokens , item ) :
"""Matches a sequence .""" | tail = None
if len ( tokens ) == 2 :
series_type , matches = tokens
else :
series_type , matches , tail = tokens
self . add_check ( "_coconut.isinstance(" + item + ", _coconut.abc.Sequence)" )
if tail is None :
self . add_check ( "_coconut.len(" + item + ") == " + str ( len ( matches ) ) )
else :
self .... |
def update ( name ) :
'''Install a named update .
: param str name : The name of the of the update to install .
: return : True if successfully updated , otherwise False
: rtype : bool
CLI Example :
. . code - block : : bash
salt ' * ' softwareupdate . update < update - name >''' | if not update_available ( name ) :
raise SaltInvocationError ( 'Update not available: {0}' . format ( name ) )
cmd = [ 'softwareupdate' , '--install' , name ]
salt . utils . mac_utils . execute_return_success ( cmd )
return not update_available ( name ) |
def OnCellFontSize ( self , event ) :
"""Cell font size event handler""" | with undo . group ( _ ( "Font size" ) ) :
self . grid . actions . set_attr ( "pointsize" , event . size )
self . grid . ForceRefresh ( )
self . grid . update_attribute_toolbar ( )
event . Skip ( ) |
def call_fget ( self , obj ) -> Any :
"""Return the predefined custom value when available , otherwise ,
the value defined by the getter function .""" | custom = vars ( obj ) . get ( self . name )
if custom is None :
return self . fget ( obj )
return custom |
def _upload_folder_in_background ( self , folder_path , container , ignore , upload_key , ttl = None ) :
"""Runs the folder upload in the background .""" | uploader = FolderUploader ( folder_path , container , ignore , upload_key , self , ttl = ttl )
uploader . start ( ) |
def prepareDatasetMigrationList ( self , conn , request ) :
"""Prepare the ordered lists of blocks based on input DATASET ( note Block is different )
1 . Get list of blocks from source
2 . Check and see if these blocks are already at DST
3 . Check if dataset has parents
4 . Check if parent blocks are alread... | ordered_dict = { }
order_counter = 0
srcdataset = request [ "migration_input" ]
url = request [ "migration_url" ]
try :
tmp_ordered_dict = self . processDatasetBlocks ( url , conn , srcdataset , order_counter )
if tmp_ordered_dict != { } :
ordered_dict . update ( tmp_ordered_dict )
self . logger... |
def price_dataframe ( symbols = 'sp5002012' , start = datetime . datetime ( 2008 , 1 , 1 ) , end = datetime . datetime ( 2009 , 12 , 31 ) , price_type = 'actual_close' , cleaner = clean_dataframe , ) :
"""Retrieve the prices of a list of equities as a DataFrame ( columns = symbols )
Arguments :
symbols ( list o... | if isinstance ( price_type , basestring ) :
price_type = [ price_type ]
start = util . normalize_date ( start or datetime . date ( 2008 , 1 , 1 ) )
end = util . normalize_date ( end or datetime . date ( 2009 , 12 , 31 ) )
symbols = normalize_symbols ( symbols )
t = du . getNYSEdays ( start , end , datetime . timede... |
def _decreaseIndent ( self , indent ) :
"""Remove 1 indentation level""" | if indent . endswith ( self . _qpartIndent ( ) ) :
return indent [ : - len ( self . _qpartIndent ( ) ) ]
else : # oops , strange indentation , just return previous indent
return indent |
def start ( self ) :
"""Starts the uBridge hypervisor process .""" | env = os . environ . copy ( )
if sys . platform . startswith ( "win" ) : # add the Npcap directory to $ PATH to force uBridge to use npcap DLL instead of Winpcap ( if installed )
system_root = os . path . join ( os . path . expandvars ( "%SystemRoot%" ) , "System32" , "Npcap" )
if os . path . isdir ( system_roo... |
def _get_vcap_services ( vcap_services = None ) :
"""Retrieves the VCAP Services information from the ` ConfigParams . VCAP _ SERVICES ` field in the config object . If
` vcap _ services ` is not specified , it takes the information from VCAP _ SERVICES environment variable .
Args :
vcap _ services ( str ) : ... | vcap_services = vcap_services or os . environ . get ( 'VCAP_SERVICES' )
if not vcap_services :
raise ValueError ( "VCAP_SERVICES information must be supplied as a parameter or as environment variable 'VCAP_SERVICES'" )
# If it was passed to config as a dict , simply return it
if isinstance ( vcap_services , dict ) ... |
def plot ( self , save_path = None , close = False , bbox_inches = "tight" , pad_inches = 1 ) :
"""Plot figure .
Parameters
save _ path : string ( optional )
Save path . Default is None .
close : boolean ( optional )
Toggle automatic figure closure after plotting .
Default is False .
bbox _ inches : n... | # final manipulations
for plot in self . subplots . flatten ( ) : # set limits
plot . set_xlim ( - 0.1 , 1.1 )
plot . set_ylim ( - 0.1 , 1.1 )
# remove guff
plot . axis ( "off" )
# save
if save_path :
plt . savefig ( save_path , transparent = True , dpi = 300 , bbox_inches = bbox_inches , pad_inches... |
def new_eventtype ( self , test_type_str = None ) :
"""Action : create dialog to add new event type .""" | if self . annot is None : # remove if buttons are disabled
self . parent . statusBar ( ) . showMessage ( 'No score file loaded' )
return
if test_type_str :
answer = test_type_str , True
else :
answer = QInputDialog . getText ( self , 'New Event Type' , 'Enter new event\'s name' )
if answer [ 1 ] :
s... |
def prepare ( self , data_batch , sparse_row_id_fn = None ) :
'''Prepares the module for processing a data batch .
Usually involves switching bucket and reshaping .
For modules that contain ` row _ sparse ` parameters in KVStore ,
it prepares the ` row _ sparse ` parameters based on the sparse _ row _ id _ fn... | assert self . binded
if sparse_row_id_fn is not None :
if not self . _kvstore or not self . _update_on_kvstore :
warnings . warn ( UserWarning ( "Parameters are not updated in the KVStore. " "No need to call sparse_row_id_fn." ) )
else :
row_ids = sparse_row_id_fn ( data_batch )
assert (... |
def log_url ( self , url_data ) :
"""Send new url to all configured loggers .""" | self . check_active_loggers ( )
do_print = self . do_print ( url_data )
# Only send a transport object to the loggers , not the complete
# object instance .
for log in self . loggers :
log . log_filter_url ( url_data , do_print ) |
def _check_permission ( self , request ) :
"""Check user permissions .
: raises : Forbidden , if user doesn ' t have access to the resource .""" | if self . access_controller :
self . access_controller . check_perm ( request , self ) |
def validate_value ( self , value ) :
"""Validate new user / group value against any User / Group restrictions
Attempts to resolve generic UserGroup instances if necessary to respect special " Everyone " group , and
" All Users " + " All Groups " options""" | super ( UserGroupField , self ) . validate_value ( value )
if value is not None : # Ignore validation if all users + groups are allowed
if self . _show_all_groups and self . _show_all_users :
return
# Try to directly check allowed ids against user / group id first to avoid having to resolve generic
... |
async def get_action_context_and_template ( chain , parent_link , decision_link ) :
"""Get the appropriate json - e context and template for an action task .
Args :
chain ( ChainOfTrust ) : the chain of trust .
parent _ link ( LinkOfTrust ) : the parent link to test .
decision _ link ( LinkOfTrust ) : the p... | actions_path = decision_link . get_artifact_full_path ( 'public/actions.json' )
all_actions = load_json_or_yaml ( actions_path , is_path = True ) [ 'actions' ]
action_name = get_action_callback_name ( parent_link . task )
action_defn = _get_action_from_actions_json ( all_actions , action_name )
jsone_context = await po... |
def runtime ( self ) :
"""Return ellapsed time and reset start .""" | t = time . time ( ) - self . start
self . start = time . time ( )
return t |
def follow_user ( self , user , delegate ) :
"""Follow the given user .
Returns the user info back to the given delegate""" | parser = txml . Users ( delegate )
return self . __postPage ( '/friendships/create/%s.xml' % ( user ) , parser ) |
def p_statement_for ( p ) :
'statement : FOR LPAREN for _ expr SEMI for _ expr SEMI for _ expr RPAREN for _ statement' | p [ 0 ] = ast . For ( p [ 3 ] , p [ 5 ] , p [ 7 ] , p [ 9 ] , lineno = p . lineno ( 1 ) ) |
def _to_patches ( self , X ) :
"""Reshapes input to patches of the size of classifier ' s receptive field .
For example :
input X shape : [ n _ samples , n _ pixels _ y , n _ pixels _ x , n _ bands ]
output : [ n _ samples * n _ pixels _ y / receptive _ field _ y * n _ pixels _ x / receptive _ field _ x ,
r... | window = self . receptive_field
asteps = self . receptive_field
if len ( X . shape ) == 4 :
window += ( 0 , )
asteps += ( 1 , )
image_view = rolling_window ( X , window , asteps )
new_shape = image_view . shape
# this makes a copy of the array ? can we do without reshaping ?
image_view = image_view . reshape ( ... |
def global_closeness_centrality ( g , node = None , normalize = True ) :
"""Calculates global closeness centrality for one or all nodes in the network .
See : func : ` . node _ global _ closeness _ centrality ` for more information .
Parameters
g : networkx . Graph
normalize : boolean
If True , normalizes... | if not node :
C = { }
for node in g . nodes ( ) :
C [ node ] = global_closeness_centrality ( g , node , normalize = normalize )
return C
values = nx . shortest_path_length ( g , node ) . values ( )
c = sum ( [ 1. / pl for pl in values if pl != 0. ] ) / len ( g )
if normalize :
ac = 0
for sg ... |
def vm_created ( name , vm_name , cpu , memory , image , version , interfaces , disks , scsi_devices , serial_ports , datacenter , datastore , placement , ide_controllers = None , sata_controllers = None , cd_dvd_drives = None , advanced_configs = None , power_on = False ) :
'''Creates a virtual machine with the gi... | result = { 'name' : name , 'result' : None , 'changes' : { } , 'comment' : '' }
if __opts__ [ 'test' ] :
result [ 'comment' ] = 'Virtual machine {0} will be created' . format ( vm_name )
return result
service_instance = __salt__ [ 'vsphere.get_service_instance_via_proxy' ] ( )
try :
info = __salt__ [ 'vsphe... |
def _ParseInformationalOptions ( self , options ) :
"""Parses the informational options .
Args :
options ( argparse . Namespace ) : command line arguments .""" | self . _debug_mode = getattr ( options , 'debug' , False )
self . _quiet_mode = getattr ( options , 'quiet' , False )
if self . _debug_mode and self . _quiet_mode :
logger . warning ( 'Cannot use debug and quiet mode at the same time, defaulting to ' 'debug output.' ) |
def username ( self , username ) :
"""Set username .
. . note : : The username will be converted to lowercase . The display name
will contain the original version .""" | validate_username ( username )
self . _username = username . lower ( )
self . _displayname = username |
def on_property_change ( self , name , old_value , new_value ) : # pylint : disable = W0613
"""A component property has been updated
: param name : Name of the property
: param old _ value : Previous value of the property
: param new _ value : New value of the property""" | if name in self . _keys :
try :
if self . update_filter ( ) : # This is a key for the filter and the filter has changed
# = > Force the handler to update its dependency
self . _reset ( )
except ValueError : # Invalid filter : clear all references , this will invalidate
# the comp... |
def scaffold ( args ) :
"""% prog scaffold contigs . fasta MP * . fastq
Run SSPACE scaffolding .""" | p = OptionParser ( scaffold . __doc__ )
p . set_aligner ( aligner = "bwa" )
p . set_home ( "sspace" )
p . set_cpus ( )
opts , args = p . parse_args ( args )
if len ( args ) < 1 :
sys . exit ( not p . print_help ( ) )
contigs = args [ 0 ]
libtxt = write_libraries ( args [ 1 : ] , aligner = opts . aligner )
# Require... |
def get_connection_ip_list ( as_wmi_format = False , server = _DEFAULT_SERVER ) :
'''Get the IPGrant list for the SMTP virtual server .
: param bool as _ wmi _ format : Returns the connection IPs as a list in the format WMI expects .
: param str server : The SMTP server name .
: return : A dictionary of the I... | ret = dict ( )
setting = 'IPGrant'
reg_separator = r',\s*'
if as_wmi_format :
ret = list ( )
addresses = _get_wmi_setting ( 'IIsIPSecuritySetting' , setting , server )
# WMI returns the addresses as a tuple of unicode strings , each representing
# an address / subnet pair . Remove extra spaces that may be present .... |
def in6_addrtovendor ( addr ) :
"""Extract the MAC address from a modified EUI - 64 constructed IPv6
address provided and use the IANA oui . txt file to get the vendor .
The database used for the conversion is the one loaded by Scapy
from a Wireshark installation if discovered in a well - known
location . N... | mac = in6_addrtomac ( addr )
if mac is None or conf . manufdb is None :
return None
res = conf . manufdb . _get_manuf ( mac )
if len ( res ) == 17 and res . count ( ':' ) != 5 : # Mac address , i . e . unknown
res = "UNKNOWN"
return res |
def writetb_parts ( path , kvs , num_per_file , ** kw ) :
"""Write typedbytes sequence files to HDFS given an iterator of KeyValue pairs
This is useful when a task is CPU bound and wish to break up its inputs
into pieces smaller than the HDFS block size . This causes Hadoop to launch
one Map task per file . A... | out = [ ]
part_num = 0
def _flush ( out , part_num ) :
hadoopy . writetb ( '%s/part-%.5d' % ( path , part_num ) , out , ** kw )
return [ ] , part_num + 1
for kv in kvs :
out . append ( kv )
if len ( out ) >= num_per_file :
out , part_num = _flush ( out , part_num )
if out :
out , part_num = ... |
def touch ( fpath , times = None , verbose = True ) :
r"""Creates file if it doesnt exist
Args :
fpath ( str ) : file path
times ( None ) :
verbose ( bool ) :
Example :
> > > # DISABLE _ DOCTEST
> > > from utool . util _ path import * # NOQA
> > > fpath = ' ? '
> > > times = None
> > > verbose =... | try :
if verbose :
print ( '[util_path] touching %r' % fpath )
with open ( fpath , 'a' ) :
os . utime ( fpath , times )
except Exception as ex :
import utool
utool . printex ( ex , 'touch %s' % fpath )
raise
return fpath |
def search_orbit ( ** kwargs ) :
'''Query based on orbital elements :
http : / / asterank . com / api / skymorph / search _ orbit ? < params >
epochEpoch ( [ M ] JD or ISO )
ecceccentricity
perPerihelion distance ( AU )
per _ datePerihelion date ( [ M ] JD or ISO )
omLongitude of ascending node ( deg ) ... | base_url = "http://asterank.com/api/skymorph/search_orbit?"
for key in kwargs :
base_url += str ( key ) + "=" + kwargs [ key ] + "&"
# remove the unnecessary & at the end
base_url = base_url [ : - 1 ]
return dispatch_http_get ( base_url ) |
def set_integrity_location ( self , integrity_extent ) : # type : ( int ) - > None
'''A method to set the location of the UDF Integrity sequence that this descriptor references .
Parameters :
integrity _ extent - The new extent that the UDF Integrity sequence should start at .
Returns :
Nothing .''' | if not self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'UDF Logical Volume Descriptor not initialized' )
self . integrity_sequence_extent = integrity_extent |
def update_handler_result ( self , ddoc_id , handler_name , doc_id = None , data = None , ** params ) :
"""Creates or updates a document from the specified database based on the
update handler function provided . Update handlers are used , for
example , to provide server - side modification timestamps , and doc... | ddoc = DesignDocument ( self , ddoc_id )
if doc_id :
resp = self . r_session . put ( '/' . join ( [ ddoc . document_url , '_update' , handler_name , doc_id ] ) , params = params , data = data )
else :
resp = self . r_session . post ( '/' . join ( [ ddoc . document_url , '_update' , handler_name ] ) , params = p... |
def most_recent_submission ( project , group ) :
"""Return the most recent submission for the user and project id .""" | return ( Submission . query_by ( project = project , group = group ) . order_by ( Submission . created_at . desc ( ) ) . first ( ) ) |
def getStore ( self ) :
"""return the store in a dict format""" | store = self . _store . getStore ( )
for priv in self . privates :
v = getattr ( self , priv )
if v :
store [ priv ] = v
return store |
def API520_F2 ( k , P1 , P2 ) :
r'''Calculates coefficient F2 for subcritical flow for use in API 520
subcritical flow relief valve sizing .
. . math : :
F _ 2 = \ sqrt { \ left ( \ frac { k } { k - 1 } \ right ) r ^ \ frac { 2 } { k }
\ left [ \ frac { 1 - r ^ \ frac { k - 1 } { k } } { 1 - r } \ right ] }... | r = P2 / P1
return ( k / ( k - 1 ) * r ** ( 2. / k ) * ( ( 1 - r ** ( ( k - 1. ) / k ) ) / ( 1. - r ) ) ) ** 0.5 |
def fetch_cached ( task_id , wait = 0 , broker = None ) :
"""Return the processed task from the cache backend""" | if not broker :
broker = get_broker ( )
start = time ( )
while True :
r = broker . cache . get ( '{}:{}' . format ( broker . list_key , task_id ) )
if r :
task = SignedPackage . loads ( r )
t = Task ( id = task [ 'id' ] , name = task [ 'name' ] , func = task [ 'func' ] , hook = task . get ( ... |
def dataset_status ( self , dataset ) :
"""call to get the status of a dataset from the API
Parameters
dataset : the string identified of the dataset
should be in format [ owner ] / [ dataset - name ]""" | if dataset is None :
raise ValueError ( 'A dataset must be specified' )
if '/' in dataset :
self . validate_dataset_string ( dataset )
dataset_urls = dataset . split ( '/' )
owner_slug = dataset_urls [ 0 ]
dataset_slug = dataset_urls [ 1 ]
else :
owner_slug = self . get_config_value ( self . CON... |
def _inputcooker_store ( self , char ) :
"""Put the cooked data in the correct queue""" | if self . sb :
self . sbdataq = self . sbdataq + char
else :
self . inputcooker_store_queue ( char ) |
def contains ( self , x , ctrs , kdtree = None ) :
"""Check if the set of balls contains ` x ` . Uses a K - D Tree to
perform the search if provided .""" | return self . overlap ( x , ctrs , kdtree = kdtree ) > 0 |
def sporco_cupy_patch_module ( name , attrib = None ) :
"""Create a copy of the named sporco module , patch it to replace
numpy with cupy , and register it in ` ` sys . modules ` ` .
Parameters
name : string
Name of source module
attrib : dict or None , optional ( default None )
Dict of attribute names ... | # Patched module name is constructed from source module name
# by replacing ' sporco . ' with ' sporco . cupy . '
pname = re . sub ( '^sporco.' , 'sporco.cupy.' , name )
# Attribute dict always maps cupy module to ' np ' attribute in
# patched module
if attrib is None :
attrib = { }
attrib . update ( { 'np' : cp } ... |
def pluck ( obj , selector , default = None , skipmissing = True ) :
"""Alternative implementation of ` plucks ` that accepts more complex
selectors . It ' s a wrapper around ` pluckable ` , so a ` selector ` can be any
valid Python expression comprising attribute getters ( ` ` . attr ` ` ) and item
getters (... | if not selector :
return obj
if selector [ 0 ] != '[' :
selector = '.%s' % selector
wrapped_obj = pluckable ( obj , default = default , skipmissing = skipmissing , inplace = True )
return eval ( "wrapped_obj%s.value" % selector ) |
def get_symop ( self ) :
"""Returns all symmetry operations ( including inversions and
subtranslations ) as a sequence of ( rotation , translation )
tuples .""" | symop = [ ]
parities = [ 1 ]
if self . centrosymmetric :
parities . append ( - 1 )
for parity in parities :
for subtrans in self . subtrans :
for rot , trans in zip ( self . rotations , self . translations ) :
newtrans = np . mod ( trans + subtrans , 1 )
symop . append ( ( parity... |
def init ( options = None , ini_paths = None , argv = None , strict = False , ** parser_kwargs ) :
"""Initialize singleton config and read / parse configuration .
: keyword bool strict : when true , will error out on invalid arguments
( default behavior is to ignore them )
: returns : the loaded configuration... | global SINGLETON
SINGLETON = Config ( options = options , ini_paths = ini_paths , argv = argv , ** parser_kwargs )
SINGLETON . parse ( argv , strict = strict )
return SINGLETON |
def get_state_actions ( self , state , ** kwargs ) :
"""Restarts instance containers .
: param state : Configuration state .
: type state : dockermap . map . state . ConfigState
: param kwargs : Additional keyword arguments .
: return : Actions on the client , map , and configurations .
: rtype : list [ d... | if ( state . config_id . config_type == ItemType . CONTAINER and state . base_state != State . ABSENT and not state . state_flags & StateFlags . INITIAL ) :
actions = [ ItemAction ( state , DerivedAction . RESTART_CONTAINER , extra_data = kwargs ) ]
if self . restart_exec_commands :
actions . append ( I... |
def excepthook ( self , etype , evalue , etb ) :
"""Handle an uncaught exception . We always forward the exception on to
whatever ` sys . excepthook ` was present upon setup . However , if the
exception is a KeyboardInterrupt , we additionally kill ourselves with
an uncaught SIGINT , so that invoking programs... | self . inner_excepthook ( etype , evalue , etb )
if issubclass ( etype , KeyboardInterrupt ) : # Don ' t try this at home , kids . On some systems os . kill ( 0 , . . . )
# signals our entire progress group , which is not what we want ,
# so we use os . getpid ( ) .
signal . signal ( signal . SIGINT , signal . SIG_... |
def lyr_proj ( lyr , t_srs , preserve_fields = True ) :
"""Reproject an OGR layer""" | # Need to check t _ srs
s_srs = lyr . GetSpatialRef ( )
cT = osr . CoordinateTransformation ( s_srs , t_srs )
# Do everything in memory
drv = ogr . GetDriverByName ( 'Memory' )
# Might want to save clipped , warped shp to disk ?
# create the output layer
# drv = ogr . GetDriverByName ( ' ESRI Shapefile ' )
# out _ fn =... |
def reset_training_state ( self , dones , batch_info ) :
"""A hook for a model to react when during training episode is finished""" | for idx , done in enumerate ( dones ) :
if done > 0.5 :
self . processes [ idx ] . reset ( ) |
async def forward ( self , chat_id , disable_notification = None ) -> Message :
"""Forward this message
: param chat _ id :
: param disable _ notification :
: return :""" | return await self . bot . forward_message ( chat_id , self . chat . id , self . message_id , disable_notification ) |
def next_frame_l2 ( ) :
"""Basic conv model with L2 modality .""" | hparams = next_frame_basic_deterministic ( )
hparams . loss [ "targets" ] = modalities . video_l2_loss
hparams . top [ "targets" ] = modalities . video_l1_top
hparams . video_modality_loss_cutoff = 2.4
return hparams |
def getLimit ( self , alpha , upper = True ) :
"""Evaluate the limits corresponding to a C . L . of ( 1 - alpha ) % .
Parameters
alpha : limit confidence level .
upper : upper or lower limits .""" | dlnl = onesided_cl_to_dlnl ( 1.0 - alpha )
return self . getDeltaLogLike ( dlnl , upper = upper ) |
def _set_tunnel_map ( self , v , load = False ) :
"""Setter method for tunnel _ map , mapped from YANG variable / interface / tunnel / tunnel _ map ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ tunnel _ map is considered as a private
method . Backends ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = tunnel_map . tunnel_map , is_container = 'container' , presence = False , yang_name = "tunnel-map" , rest_name = "map" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = T... |
def statistic_record ( self , desc = True , timeout = 3 , is_async = False , only_read = True , * keys ) :
"""Returns a list that each element is a dictionary of the statistic info of the cache item .""" | if len ( keys ) == 0 :
records = self . _generate_statistic_records ( )
else :
records = self . _generate_statistic_records_by_keys ( keys )
return sorted ( records , key = lambda t : t [ 'hit_counts' ] , reverse = desc ) |
def post_message ( self , message , duration = None , pause = True , style = "info" ) :
"""Post a message on the screen with Messenger .
Arguments :
message : The message to display .
duration : The time until the message vanishes . ( Default : 2.55s )
pause : If True , the program waits until the message c... | if not duration :
if not self . message_duration :
duration = settings . DEFAULT_MESSAGE_DURATION
else :
duration = self . message_duration
js_utils . post_message ( self . driver , message , duration , style = style )
if pause :
duration = float ( duration ) + 0.15
time . sleep ( float ... |
def sonTraceRootPath ( ) :
"""function for finding external location""" | import sonLib . bioio
i = os . path . abspath ( sonLib . bioio . __file__ )
return os . path . split ( os . path . split ( os . path . split ( i ) [ 0 ] ) [ 0 ] ) [ 0 ] |
def get_state ( self ) :
"""Create state from sensors and battery""" | # Include battery level in state
battery = self . player . stats [ 'battery' ] / 100
# Create observation from sensor proximities
# TODO : Have state persist , then update columns by ` sensed _ type `
# Multi - channel ; detecting ` items `
if len ( self . mode [ 'items' ] ) > 0 :
observation = [ ]
for sensor i... |
def get_ldap ( cls , global_options = None ) :
"""Returns the ldap module . The unit test harness will assign a mock object
to _ LDAPConfig . ldap . It is imperative that the ldap module not be
imported anywhere else so that the unit tests will pass in the absence
of python - ldap .""" | if cls . ldap is None :
import ldap . filter
# Support for python - ldap < 2.0.6
try :
import ldap . dn
except ImportError :
from django_auth_ldap import dn
ldap . dn = dn
cls . ldap = ldap
# Apply global LDAP options once
if ( not cls . _ldap_configured ) and ( global_option... |
def get ( self , key , default = None ) :
"""Get an item - return default ( None ) if not present""" | if key not in self . table :
return default
return self [ key ] |
def cell_to_text ( self ) :
"""Return the text representation of a cell""" | if self . cell_type == 'markdown' : # Is an explicit region required ?
if self . metadata or self . cell_reader ( self . fmt ) . read ( self . source ) [ 1 ] < len ( self . source ) :
if self . metadata :
region_start = [ '<!-- #region' ]
if 'title' in self . metadata and '{' not in ... |
def transformToNative ( obj ) :
"""Convert comma separated periods into tuples .""" | if obj . isNative :
return obj
obj . isNative = True
if obj . value == '' :
obj . value = [ ]
return obj
tzinfo = getTzid ( getattr ( obj , 'tzid_param' , None ) )
obj . value = [ stringToPeriod ( x , tzinfo ) for x in obj . value . split ( "," ) ]
return obj |
async def track_event ( event , state , service_name ) :
"""Store state of events in memory
: param event : Event object
: param state : EventState object
: param service _ name : Name of service name""" | redis = await aioredis . create_redis ( ( EVENT_TRACKING_HOST , 6379 ) , loop = loop )
now = datetime . utcnow ( )
event_id = event . event_id
tracking_data = json . dumps ( { "event_id" : event_id , "timestamp" : str ( now ) , "state" : state } )
await redis . rpush ( service_name , tracking_data )
redis . close ( )
a... |
def Pipe ( self , * sequence , ** kwargs ) :
"""` Pipe ` runs any ` phi . dsl . Expression ` . Its highly inspired by Elixir ' s [ | > ( pipe ) ] ( https : / / hexdocs . pm / elixir / Kernel . html # % 7C % 3E / 2 ) operator .
* * Arguments * *
* * * * sequence * * : any variable amount of expressions . All exp... | state = kwargs . pop ( "refs" , { } )
return self . Seq ( * sequence , ** kwargs ) ( None , ** state ) |
def compute_pscale ( self , cd11 , cd21 ) :
"""Compute the pixel scale based on active WCS values .""" | return N . sqrt ( N . power ( cd11 , 2 ) + N . power ( cd21 , 2 ) ) * 3600. |
def list_firmware_manifests ( self , ** kwargs ) :
"""List all manifests .
: param int limit : number of manifests to retrieve
: param str order : sort direction of manifests when ordered by time . ' desc ' or ' asc '
: param str after : get manifests after given ` image _ id `
: param dict filters : Dictio... | kwargs = self . _verify_sort_options ( kwargs )
kwargs = self . _verify_filters ( kwargs , FirmwareManifest , True )
api = self . _get_api ( update_service . DefaultApi )
return PaginatedResponse ( api . firmware_manifest_list , lwrap_type = FirmwareManifest , ** kwargs ) |
def calcRandW ( self , aLvlNow , pLvlNow ) :
'''Calculates the interest factor and wage rate this period using each agent ' s
capital stock to get the aggregate capital ratio .
Parameters
aLvlNow : [ np . array ]
Agents ' current end - of - period assets . Elements of the list correspond
to types in the e... | # Calculate aggregate savings
AaggPrev = np . mean ( np . array ( aLvlNow ) ) / np . mean ( pLvlNow )
# End - of - period savings from last period
# Calculate aggregate capital this period
AggregateK = np . mean ( np . array ( aLvlNow ) )
# . . . becomes capital today
# This version uses end - of - period assets and
# ... |
def filter ( self , exclude ) :
"""Return a HeaderSet excluding the headers in the exclude list .""" | filtered_headers = HeaderDict ( )
lowercased_ignore_list = [ x . lower ( ) for x in exclude ]
for header , value in iteritems ( self ) :
if header . lower ( ) not in lowercased_ignore_list :
filtered_headers [ header ] = value
return filtered_headers |
def display ( fig = None , closefig = True , ** kwargs ) :
"""Convert a Matplotlib Figure to a Leaflet map . Embed in IPython notebook .
Parameters
fig : figure , default gcf ( )
Figure used to convert to map
closefig : boolean , default True
Close the current Figure""" | from IPython . display import HTML
if fig is None :
fig = plt . gcf ( )
if closefig :
plt . close ( fig )
html = fig_to_html ( fig , ** kwargs )
# We embed everything in an iframe .
iframe_html = '<iframe src="data:text/html;base64,{html}" width="{width}" height="{height}"></iframe>' . format ( html = base64 . ... |
def QA_fetch_get_tdxtraderecord ( file ) :
"""QUANTAXIS 读取历史交易记录 通达信 历史成交 - 输出 - xlsfile - - 转换csvfile""" | try :
with open ( './20180606.csv' , 'r' ) as f :
l = csv . reader ( f )
data = [ item for item in l ]
res = pd . DataFrame ( data [ 1 : ] , columns = data [ 0 ] )
return res
except :
raise IOError ( 'QA CANNOT READ THIS RECORD' ) |
def parse ( document , clean_html = True , unix_timestamp = False , encoding = None ) :
"""Parse a document and return a feedparser dictionary with attr key access .
If clean _ html is False , the html in the feed will not be cleaned . If
clean _ html is True , a sane version of lxml . html . clean . Cleaner wi... | if isinstance ( clean_html , bool ) :
cleaner = default_cleaner if clean_html else fake_cleaner
else :
cleaner = clean_html
result = feedparser . FeedParserDict ( )
result [ 'feed' ] = feedparser . FeedParserDict ( )
result [ 'entries' ] = [ ]
result [ 'bozo' ] = 0
try :
parser = SpeedParser ( document , cl... |
def bots_update ( self , bot ) :
"""Update Bot
: param bot : bot object to update
: type bot : Bot""" | self . client . bots . __getattr__ ( bot . name ) . __call__ ( _method = "PUT" , _json = bot . to_json ( ) , _params = dict ( botName = bot . name ) ) |
def _run__http ( self , action , replace ) :
"""More complex HTTP query .""" | query = action [ 'query' ]
# self . _ debug = True
url = '{type}://{host}{path}' . format ( path = query [ 'path' ] , ** action )
content = None
method = query . get ( 'method' , "get" ) . lower ( )
self . debug ( "{} {} url={}\n" , action [ 'type' ] , method , url )
if method == "post" :
content = query [ 'content... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.