signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def calc_checksum ( sentence ) :
"""Calculate a NMEA 0183 checksum for the given sentence .
NMEA checksums are a simple XOR of all the characters in the sentence
between the leading " $ " symbol , and the " * " checksum separator .
Args :
sentence ( str ) : NMEA 0183 formatted sentence""" | if sentence . startswith ( '$' ) :
sentence = sentence [ 1 : ]
sentence = sentence . split ( '*' ) [ 0 ]
return reduce ( xor , map ( ord , sentence ) ) |
def template_get ( name = None , host = None , templateids = None , ** kwargs ) :
'''Retrieve templates according to the given parameters .
Args :
host : technical name of the template
name : visible name of the template
hostids : ids of the templates
optional kwargs :
_ connection _ user : zabbix user ... | conn_args = _login ( ** kwargs )
ret = { }
try :
if conn_args :
method = 'template.get'
params = { "output" : "extend" , "filter" : { } }
if name :
params [ 'filter' ] . setdefault ( 'name' , name )
if host :
params [ 'filter' ] . setdefault ( 'host' , host )
... |
def background_knowledge ( self ) :
'''Emits the background knowledge in prolog form for Aleph .''' | modeslist , getters = [ self . mode ( self . __target_predicate ( ) , [ ( '+' , self . db . target_table ) ] , head = True ) ] , [ ]
determinations , types = [ ] , [ ]
for ( table , ref_table ) in self . db . connected . keys ( ) :
if ref_table == self . db . target_table :
continue
# Skip backward ... |
def before_add_field ( self , field ) :
"""If extract _ fields is set to True , then ' * ' fields will be removed and each
individual field will read from the model meta data and added .""" | if self . extract_fields and field . name == '*' :
field . ignore = True
fields = [ model_field . column for model_field in self . model . _meta . fields ]
self . add_fields ( fields ) |
def pexpireat ( self , name , when ) :
"""Set an expire flag on key ` ` name ` ` . ` ` when ` ` can be represented
as an integer representing unix time in milliseconds ( unix time * 1000)
or a Python datetime object .""" | if isinstance ( when , datetime . datetime ) :
ms = int ( when . microsecond / 1000 )
when = int ( mod_time . mktime ( when . timetuple ( ) ) ) * 1000 + ms
return self . execute_command ( 'PEXPIREAT' , name , when ) |
def insert ( self , index , p_object ) :
"""Insert an element to a list""" | validated_value = self . get_validated_object ( p_object )
if validated_value is not None :
self . __modified_data__ . insert ( index , validated_value ) |
def Initialize ( self ) :
"""Try to load the data from the store .""" | super ( AFF4MemoryStreamBase , self ) . Initialize ( )
contents = b""
if "r" in self . mode :
contents = self . Get ( self . Schema . CONTENT ) . AsBytes ( )
try :
if contents is not None :
contents = zlib . decompress ( contents )
except zlib . error :
pass
self . fd = io . Byte... |
def clean ( self , critical = False ) :
"""Clean the logs list by deleting finished items .
By default , only delete WARNING message .
If critical = True , also delete CRITICAL message .""" | # Create a new clean list
clean_events_list = [ ]
while self . len ( ) > 0 :
item = self . events_list . pop ( )
if item [ 1 ] < 0 or ( not critical and item [ 2 ] . startswith ( "CRITICAL" ) ) :
clean_events_list . insert ( 0 , item )
# The list is now the clean one
self . events_list = clean_events_li... |
def fit ( self , X , vocab = None , initial_embedding_dict = None , fixed_initialization = None ) :
"""Run GloVe and return the new matrix .
Parameters
X : array - like of shape = [ n _ words , n _ words ]
The square count matrix .
vocab : iterable or None ( default : None )
Rownames for ` X ` .
initial... | if fixed_initialization is not None :
assert self . test_mode , "Fixed initialization parameters can only be provided" " in test mode. Initialize {} with `test_mode=True`." . format ( self . __class__ . split ( "." ) [ - 1 ] )
self . _check_dimensions ( X , vocab , initial_embedding_dict )
weights , log_coincidence... |
def validate ( self , scope : ValidationScope = ValidationScope . all , ctype : ContentType = ContentType . config ) -> None :
"""Validate the receiver ' s value .
Args :
scope : Scope of the validation ( syntax , semantics or all ) .
ctype : Receiver ' s content type .
Raises :
SchemaError : If the value... | self . schema_node . _validate ( self , scope , ctype ) |
def validate_ok_for_update ( update ) :
"""Validate an update document .""" | validate_is_mapping ( "update" , update )
# Update can not be { }
if not update :
raise ValueError ( 'update only works with $ operators' )
first = next ( iter ( update ) )
if not first . startswith ( '$' ) :
raise ValueError ( 'update only works with $ operators' ) |
def run ( self ) :
"""Kill any open Redshift sessions for the given database .""" | connection = self . output ( ) . connect ( )
# kill any sessions other than ours and
# internal Redshift sessions ( rdsdb )
query = ( "select pg_terminate_backend(process) " "from STV_SESSIONS " "where db_name=%s " "and user_name != 'rdsdb' " "and process != pg_backend_pid()" )
cursor = connection . cursor ( )
logger .... |
def _scale_to_dtype ( self , data , dtype ) :
"""Scale provided data to dtype range assuming a 0-1 range .
Float input data is assumed to be normalized to a 0 to 1 range .
Integer input data is not scaled , only clipped . A float output
type is not scaled since both outputs and inputs are assumed to
be in t... | if np . issubdtype ( dtype , np . integer ) :
if np . issubdtype ( data , np . integer ) : # preserve integer data type
data = data . clip ( np . iinfo ( dtype ) . min , np . iinfo ( dtype ) . max )
else : # scale float data ( assumed to be 0 to 1 ) to full integer space
dinfo = np . iinfo ( dty... |
def add_boundary ( self , p1 , p2 , btype ) :
"""Add a boundary line""" | index = self . add_line ( p1 , p2 , self . char_lengths [ 'boundary' ] )
# self . Boundaries . append ( ( p1 _ id , p2 _ id , btype ) )
self . BoundaryIndices . append ( index )
self . Boundaries . append ( ( p1 , p2 , btype ) ) |
def _get_child_from_path ( self , path ) :
"""Return a children below this level , starting from a path of the kind " this _ level . something . something . name "
: param path : the key
: return : the child""" | keys = path . split ( "." )
this_child = self
for key in keys :
try :
this_child = this_child . _get_child ( key )
except KeyError :
raise KeyError ( "Child %s not found" % path )
return this_child |
def getitem ( lst , indices ) :
"""Definition for multidimensional slicing and indexing on arbitrarily
shaped nested lists .""" | if not indices :
return lst
i , indices = indices [ 0 ] , indices [ 1 : ]
item = list . __getitem__ ( lst , i )
if isinstance ( i , int ) :
return getitem ( item , indices )
# Empty slice : check if all subsequent indices are in range for the
# full slice , raise IndexError otherwise . This is NumPy ' s behavio... |
def create_dir ( path ) :
"""Creates a directory . Warns , if the directory can ' t be accessed . Passes ,
if the directory already exists .
modified from http : / / stackoverflow . com / a / 600612
Parameters
path : str
path to the directory to be created""" | import sys
import errno
try :
os . makedirs ( path )
except OSError as exc : # Python > 2.5
if exc . errno == errno . EEXIST :
if os . path . isdir ( path ) :
pass
else : # if something exists at the path , but it ' s not a dir
raise
elif exc . errno == errno . EACCES... |
def load_dwg ( file_obj , ** kwargs ) :
"""Load DWG files by converting them to DXF files using
TeighaFileConverter .
Parameters
file _ obj : file - like object
Returns
loaded : dict
kwargs for a Path2D constructor""" | # read the DWG data into a bytes object
data = file_obj . read ( )
# convert data into R14 ASCII DXF
converted = _teigha_convert ( data )
# load into kwargs for Path2D constructor
result = load_dxf ( util . wrap_as_stream ( converted ) )
return result |
def do_bestfit ( self ) :
"""Do bestfit""" | self . check_important_variables ( )
x = np . array ( self . args [ "x" ] )
y = np . array ( self . args [ "y" ] )
p = self . args . get ( "params" , np . ones ( self . args [ "num_vars" ] ) )
self . fit_args , self . cov = opt . curve_fit ( self . args [ "func" ] , x , y , p )
return self . fit_args |
def fetch ( elastic , backend , limit = None , search_after_value = None , scroll = True ) :
"""Fetch the items from raw or enriched index""" | logging . debug ( "Creating a elastic items generator." )
elastic_scroll_id = None
search_after = search_after_value
while True :
if scroll :
rjson = get_elastic_items ( elastic , elastic_scroll_id , limit )
else :
rjson = get_elastic_items_search ( elastic , search_after , limit )
if rjson ... |
def boot ( self , name , flavor_id = 0 , image_id = 0 , timeout = 300 , ** kwargs ) :
'''Boot a cloud server .''' | nt_ks = self . compute_conn
kwargs [ 'name' ] = name
kwargs [ 'flavor' ] = flavor_id
kwargs [ 'image' ] = image_id or None
ephemeral = kwargs . pop ( 'ephemeral' , [ ] )
block_device = kwargs . pop ( 'block_device' , [ ] )
boot_volume = kwargs . pop ( 'boot_volume' , None )
snapshot = kwargs . pop ( 'snapshot' , None )... |
def attention_bias_prepend_inputs_full_attention ( padding ) :
"""Create a bias tensor for prepend _ mode = " prepend _ inputs _ full _ attention " .
See prepend _ inputs in common _ hparams . py .
Produces a bias tensor to be used in self - attention .
This bias tensor allows for full connectivity in the " i... | # Everything past the first padding position is part of the target .
# This Tensor has zeros for the source portion and separator ,
# and ones for the target portion .
in_target = tf . cumsum ( padding , axis = 1 , exclusive = True )
# The position within the target , or 0 if part of the source .
target_pos = tf . cums... |
def _rename_objects_fast ( self ) :
"""Rename all objects quickly to guaranteed - unique names using the
id ( ) of each object .
This produces mostly unreadable GLSL , but is about 10x faster to
compile .""" | for shader_name , deps in self . _shader_deps . items ( ) :
for dep in deps :
name = dep . name
if name != 'main' :
ext = '_%x' % id ( dep )
name = name [ : 32 - len ( ext ) ] + ext
self . _object_names [ dep ] = name |
def print_genome_matrix ( hits , fastas , id2desc , file_name ) :
"""optimize later ? slow . . .
should combine with calculate _ threshold module""" | out = open ( file_name , 'w' )
fastas = sorted ( fastas )
print ( '## percent identity between genomes' , file = out )
print ( '# - \t %s' % ( '\t' . join ( fastas ) ) , file = out )
for fasta in fastas :
line = [ fasta ]
for other in fastas :
if other == fasta :
average = '-'
else :... |
def count ( self , files = False ) :
"""Returns a count of unique values or files .
Args :
files ( bool ) : When True , counts all files mapped to the Entity .
When False , counts all unique values .
Returns : an int .""" | return len ( self . files ) if files else len ( self . unique ( ) ) |
def actions ( self ) :
"""Returns a list of actions that are associated with this shortcut edit .
: return [ < QAction > , . . ]""" | output = [ ]
for i in range ( self . uiActionTREE . topLevelItemCount ( ) ) :
output . append ( self . uiActionTREE . topLevelItem ( i ) . action ( ) )
return output |
def p_field_optional2_6 ( self , p ) :
"""field : alias name arguments""" | p [ 0 ] = Field ( name = p [ 2 ] , alias = p [ 1 ] , arguments = p [ 3 ] ) |
def equals ( self , other ) :
"""Returns True if categorical arrays are equal .
Parameters
other : ` Categorical `
Returns
bool""" | if self . is_dtype_equal ( other ) :
if self . categories . equals ( other . categories ) : # fastpath to avoid re - coding
other_codes = other . _codes
else :
other_codes = _recode_for_categories ( other . codes , other . categories , self . categories )
return np . array_equal ( self . _co... |
def _can_send_eth ( irs ) :
"""Detect if the node can send eth""" | for ir in irs :
if isinstance ( ir , ( HighLevelCall , LowLevelCall , Transfer , Send ) ) :
if ir . call_value :
return True
return False |
def areBackupsDegraded ( self ) :
"""Return slow instance .""" | slow_instances = [ ]
if self . acc_monitor :
for instance in self . instances . backupIds :
if self . acc_monitor . is_instance_degraded ( instance ) :
slow_instances . append ( instance )
else :
for instance in self . instances . backupIds :
if self . is_instance_throughput_too_low ... |
def user_field_option_delete ( self , field_id , id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / user _ fields # delete - user - field - option" | api_path = "/api/v2/user_fields/{field_id}/options/{id}.json"
api_path = api_path . format ( field_id = field_id , id = id )
return self . call ( api_path , method = "DELETE" , ** kwargs ) |
def to_python ( self , value ) :
'''Handle data from serialization and form clean ( ) methods .''' | if isinstance ( value , Seconds ) :
return value
if value in self . empty_values :
return None
return self . parse_seconds ( value ) |
def from_json ( cls , json_graph ) :
"""Reconstruct the graph from a graph exported to JSON .""" | obj = json . loads ( json_graph )
vertices = [ AnnotatedVertex ( id = vertex [ "id" ] , annotation = vertex [ "annotation" ] , ) for vertex in obj [ "vertices" ] ]
edges = [ AnnotatedEdge ( id = edge [ "id" ] , annotation = edge [ "annotation" ] , head = edge [ "head" ] , tail = edge [ "tail" ] , ) for edge in obj [ "e... |
def _proc_cyclic ( self ) :
"""Handles cyclic group molecules .""" | main_axis , rot = max ( self . rot_sym , key = lambda v : v [ 1 ] )
self . sch_symbol = "C{}" . format ( rot )
mirror_type = self . _find_mirror ( main_axis )
if mirror_type == "h" :
self . sch_symbol += "h"
elif mirror_type == "v" :
self . sch_symbol += "v"
elif mirror_type == "" :
if self . is_valid_op ( ... |
def partial_transform ( self , traj ) :
"""Slice a single input array along to select a subset of features .
Parameters
traj : np . ndarray , shape = ( n _ samples , n _ features )
A sample to slice .
Returns
sliced _ traj : np . ndarray shape = ( n _ samples , n _ feature _ subset )
Slice of traj""" | if self . index is not None :
return traj [ : , self . index ]
else :
return traj [ : , : self . first ] |
def b64_from ( val ) :
"""Returns base64 encoded bytes for a given int / long / bytes value .
: param int | long | bytes val :
: rtype : bytes | str""" | if isinstance ( val , integer_types ) :
val = int_to_bytes ( val )
return b64encode ( val ) . decode ( 'ascii' ) |
def search ( self , query , delegate , args = None , extra_args = None ) :
"""Perform a search query .
Results are given one at a time to the delegate . An example delegate
may look like this :
def exampleDelegate ( entry ) :
print entry . title""" | if args is None :
args = { }
args [ 'q' ] = query
return self . __doDownloadPage ( self . search_url + '?' + self . _urlencode ( args ) , txml . Feed ( delegate , extra_args ) , agent = self . agent ) |
def shutdown ( self ) :
"""Shutdown ZAP .""" | if not self . is_running ( ) :
self . logger . warn ( 'ZAP is not running.' )
return
self . logger . debug ( 'Shutting down ZAP.' )
self . zap . core . shutdown ( )
timeout_time = time . time ( ) + self . timeout
while self . is_running ( ) :
if time . time ( ) > timeout_time :
raise ZAPError ( 'Tim... |
def delete ( self ) :
"""Delete the pivot model record from the database .
: rtype : int""" | query = self . _get_delete_query ( )
query . where ( self . _morph_type , self . _morph_class )
return query . delete ( ) |
def list ( self , count = 30 , order = 'user_ptime' , asc = False , show_dir = True , natsort = True ) :
"""List directory contents
: param int count : number of entries to be listed
: param str order : order of entries , originally named ` o ` . This value
may be one of ` user _ ptime ` ( default ) , ` file ... | if self . cid is None :
return False
self . reload ( )
kwargs = { }
# ` cid ` is the only required argument
kwargs [ 'cid' ] = self . cid
kwargs [ 'asc' ] = 1 if asc is True else 0
kwargs [ 'show_dir' ] = 1 if show_dir is True else 0
kwargs [ 'natsort' ] = 1 if natsort is True else 0
kwargs [ 'o' ] = order
# When t... |
def build ( cls , schema : GraphQLSchema , document : DocumentNode , root_value : Any = None , context_value : Any = None , raw_variable_values : Dict [ str , Any ] = None , operation_name : str = None , field_resolver : GraphQLFieldResolver = None , type_resolver : GraphQLTypeResolver = None , middleware : Middleware ... | errors : List [ GraphQLError ] = [ ]
operation : Optional [ OperationDefinitionNode ] = None
has_multiple_assumed_operations = False
fragments : Dict [ str , FragmentDefinitionNode ] = { }
middleware_manager : Optional [ MiddlewareManager ] = None
if middleware is not None :
if isinstance ( middleware , ( list , tu... |
def on_response ( self , msg ) :
"""setup response if correlation id is the good one""" | LOGGER . debug ( "natsd.Requester.on_response: " + str ( sys . getsizeof ( msg ) ) + " bytes received" )
working_response = json . loads ( msg . data . decode ( ) )
working_properties = DriverTools . json2properties ( working_response [ 'properties' ] )
working_body = b'' + bytes ( working_response [ 'body' ] , 'utf8' ... |
def get_titles ( ) :
'''returns titles of all open windows''' | if os . name == 'posix' :
for proc in get_processes ( ) :
cmd = [ 'xdotool' , 'search' , '--name' , proc ]
proc = subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . PIPE )
window_ids = proc . communicate ( ) [ 0 ] . decode ( 'utf-8' )
if window_ids :
... |
def _convert_internal ( cls , record ) :
"""Converts a single dictionary into converted dictionary or list of dictionaries into converted
list of dictionaries . Used while passing dictionaries to another converter .""" | if isinstance ( record , list ) :
return [ cls . _convert ( r ) for r in record ]
else :
return cls . _convert ( record ) |
def return_values ( self ) :
"""Guess what api we are using and return as public api does .
Private has { ' id ' : ' key ' , ' value ' : ' keyvalue ' } format , public has { ' key ' : ' keyvalue ' }""" | j = self . json ( )
# TODO : FIXME : get rid of old API when its support will be removed
public_api_value = j . get ( 'returnValues' )
old_private_value = j . get ( 'endpoints' )
new_private_value = self . __collect_interfaces_return ( j . get ( 'interfaces' , { } ) )
retvals = new_private_value or old_private_value or... |
def compiled_hash_func ( self ) :
"""Returns compiled hash function based on hash of stringified primary _ keys .
This isn ' t the most efficient way""" | def get_primary_key_str ( pkey_name ) :
return "str(self.{})" . format ( pkey_name )
hash_str = "+ " . join ( [ get_primary_key_str ( n ) for n in self . primary_keys ] )
return ALCHEMY_TEMPLATES . hash_function . safe_substitute ( concated_primary_key_strs = hash_str ) |
def get_child_books ( self , book_id ) :
"""Gets the child books of the given ` ` id ` ` .
arg : book _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Book ` ` to
query
return : ( osid . commenting . BookList ) - the child books of the
` ` id ` `
raise : NotFound - a ` ` Book ` ` identified by ` ` Id i... | # Implemented from template for
# osid . resource . BinHierarchySession . get _ child _ bins
if self . _catalog_session is not None :
return self . _catalog_session . get_child_catalogs ( catalog_id = book_id )
return BookLookupSession ( self . _proxy , self . _runtime ) . get_books_by_ids ( list ( self . get_child... |
def uniform_crossover ( random , mom , dad , args ) :
"""Return the offspring of uniform crossover on the candidates .
This function performs uniform crossover ( UX ) . For each element
of the parents , a biased coin is flipped to determine whether
the first offspring gets the ' mom ' or the ' dad ' element .... | ux_bias = args . setdefault ( 'ux_bias' , 0.5 )
crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 )
children = [ ]
if random . random ( ) < crossover_rate :
bro = copy . copy ( dad )
sis = copy . copy ( mom )
for i , ( m , d ) in enumerate ( zip ( mom , dad ) ) :
if random . random ( ) < u... |
def apic_driver ( self ) :
"""Get APIC driver
There are different drivers for the GBP workflow
and Neutron workflow for APIC . First see if the GBP
workflow is active , and if so get the APIC driver for it .
If the GBP service isn ' t installed , try to get the driver
from the Neutron ( APIC ML2 ) workflo... | if not self . _apic_driver :
try :
self . _apic_driver = ( bc . get_plugin ( 'GROUP_POLICY' ) . policy_driver_manager . policy_drivers [ 'apic' ] . obj )
self . _get_ext_net_name = self . _get_ext_net_name_gbp
self . _get_vrf_context = self . _get_vrf_context_gbp
except AttributeError :
... |
def put ( self , transport , robj , w = None , dw = None , pw = None , return_body = None , if_none_match = None , timeout = None ) :
"""put ( robj , w = None , dw = None , pw = None , return _ body = None , if _ none _ match = None , timeout = None )
Stores an object in the Riak cluster .
. . note : : This req... | _validate_timeout ( timeout )
return transport . put ( robj , w = w , dw = dw , pw = pw , return_body = return_body , if_none_match = if_none_match , timeout = timeout ) |
def mask_xdata ( self ) -> DataAndMetadata . DataAndMetadata :
"""Return the mask by combining any mask graphics on this data item as extended data .
. . versionadded : : 1.0
Scriptable : Yes""" | display_data_channel = self . __display_item . display_data_channel
shape = display_data_channel . display_data_shape
mask = numpy . zeros ( shape )
for graphic in self . __display_item . graphics :
if isinstance ( graphic , ( Graphics . SpotGraphic , Graphics . WedgeGraphic , Graphics . RingGraphic , Graphics . La... |
def default_validity_start ( ) :
"""Sets validity _ start field to 1 day before the current date
( avoids " certificate not valid yet " edge case ) .
In some cases , because of timezone differences , when certificates
were just created they were considered valid in a timezone ( eg : Europe )
but not yet val... | start = datetime . now ( ) - timedelta ( days = 1 )
return start . replace ( hour = 0 , minute = 0 , second = 0 , microsecond = 0 ) |
def pin ( value ) :
'''A small pin that represents the result of the build process''' | if value is False :
return draw_pin ( 'Build Failed' , 'red' )
elif value is True :
return draw_pin ( 'Build Passed' )
elif value is NOT_FOUND :
return draw_pin ( 'Build N / A' , 'lightGray' , 'black' )
return draw_pin ( 'In progress ...' , 'lightGray' , 'black' ) |
def _set_untagged ( self , v , load = False ) :
"""Setter method for untagged , mapped from YANG variable / interface / port _ channel / logical _ interface / port _ channel / pc _ cmd _ container _ dummy / service _ instance _ vlan _ cmds _ dummy _ container / get _ untagged _ vlan _ dummy / untagged ( container )... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = untagged . untagged , is_container = 'container' , presence = False , yang_name = "untagged" , rest_name = "untagged" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = Tr... |
def group_comments_by_round ( comments , ranking = 0 ) :
"""Group comments by the round to which they belong""" | comment_rounds = { }
ordered_comment_round_names = [ ]
for comment in comments :
comment_round_name = ranking and comment [ 11 ] or comment [ 7 ]
if comment_round_name not in comment_rounds :
comment_rounds [ comment_round_name ] = [ ]
ordered_comment_round_names . append ( comment_round_name )
... |
def L2 ( layer = "input" , constant = 0 , epsilon = 1e-6 , batch = None ) :
"""L2 norm of layer . Generally used as penalty .""" | if batch is None :
return lambda T : tf . sqrt ( epsilon + tf . reduce_sum ( ( T ( layer ) - constant ) ** 2 ) )
else :
return lambda T : tf . sqrt ( epsilon + tf . reduce_sum ( ( T ( layer ) [ batch ] - constant ) ** 2 ) ) |
def scatter_nb ( self , xdata , ydata = [ ] , trendline = False ) :
'''Graphs a scatter plot and embeds it in a Jupyter notebook . See ' help ( figure . scatter ) ' for more info .''' | self . scatter ( xdata , ydata , trendline ) |
def _Bern_to_JMS_I ( C , qq ) :
"""From Bern to JMS basis for $ \ Delta F = 2 $ operators .
` qq ` should be ' sb ' , ' db ' , ' ds ' or ' cu '""" | if qq in [ 'sb' , 'db' , 'ds' ] :
dd = 'dd'
ij = '{}{}' . format ( dflav [ qq [ 0 ] ] + 1 , dflav [ qq [ 1 ] ] + 1 )
elif qq == 'cu' :
dd = 'uu'
ij = '{}{}' . format ( uflav [ qq [ 0 ] ] + 1 , uflav [ qq [ 1 ] ] + 1 )
else :
raise ValueError ( "not in Bern_I: " . format ( qq ) )
ji = ij [ 1 ] + ij [... |
def _read_json_file ( self , json_file ) :
"""Helper function to read JSON file as OrderedDict""" | self . log . debug ( "Reading '%s' JSON file..." % json_file )
with open ( json_file , 'r' ) as f :
return json . load ( f , object_pairs_hook = OrderedDict ) |
def cancel_withdraw ( self , address_id , _async = False ) :
"""申请取消提现虚拟币
: param address _ id :
: return : {
" status " : " ok " ,
" data " : 700""" | params = { }
path = f'/v1/dw/withdraw-virtual/{address_id}/cancel'
return api_key_post ( params , path , _async = _async ) |
def setup_cluster ( self , cluster , extra_args = tuple ( ) ) :
"""Configure the cluster by running an Ansible playbook .
The ElastiCluster configuration attribute ` < kind > _ groups `
determines , for each node kind , what Ansible groups nodes of
that kind are assigned to .
: param cluster : cluster to co... | inventory_path = self . _build_inventory ( cluster )
if inventory_path is None : # No inventory file has been created , maybe an
# invalid class has been specified in config file ? Or none ?
# assume it is fine .
elasticluster . log . info ( "No setup required for this cluster." )
return True
assert os . path .... |
def _process_loop ( self ) :
'''Fetch URL including redirects .
Coroutine .''' | while not self . _web_client_session . done ( ) :
self . _item_session . request = self . _web_client_session . next_request ( )
verdict , reason = self . _should_fetch_reason ( )
_logger . debug ( 'Filter verdict {} reason {}' , verdict , reason )
if not verdict :
self . _item_session . skip ( ... |
def zDDEClose ( self ) :
"""Close the DDE link with Zemax server""" | if _PyZDDE . server and not _PyZDDE . liveCh :
_PyZDDE . server . Shutdown ( self . conversation )
_PyZDDE . server = 0
elif _PyZDDE . server and self . connection and _PyZDDE . liveCh == 1 :
_PyZDDE . server . Shutdown ( self . conversation )
self . connection = False
self . appName = ''
_PyZDD... |
def get_collection_moderators ( collection ) :
"""Return the list of comment moderators for the given collection .""" | from invenio_access . engine import acc_get_authorized_emails
res = list ( acc_get_authorized_emails ( 'moderatecomments' , collection = collection ) )
if not res :
return [ CFG_WEBCOMMENT_DEFAULT_MODERATOR , ]
return res |
def scalars_for_mapping_ion_drifts ( glats , glons , alts , dates , step_size = None , max_steps = None , e_field_scaling_only = False ) :
"""Calculates scalars for translating ion motions at position
glat , glon , and alt , for date , to the footpoints of the field line
as well as at the magnetic equator .
A... | if step_size is None :
step_size = 100.
if max_steps is None :
max_steps = 1000
steps = np . arange ( max_steps )
# use spacecraft location to get ECEF
ecef_xs , ecef_ys , ecef_zs = geodetic_to_ecef ( glats , glons , alts )
# prepare output
eq_zon_drifts_scalar = [ ]
eq_mer_drifts_scalar = [ ]
# magnetic field ... |
def get_parameter ( self , parameter ) :
"Return a dict for given parameter" | parameter = self . _get_parameter_name ( parameter )
return self . _parameters [ parameter ] |
def tcex_json ( self ) :
"""Return tcex . json file contents .""" | file_fqpn = os . path . join ( self . app_path , 'tcex.json' )
if self . _tcex_json is None :
if os . path . isfile ( file_fqpn ) :
try :
with open ( file_fqpn , 'r' ) as fh :
self . _tcex_json = json . load ( fh )
except ValueError as e :
self . handle_error ... |
def add_udev_info ( self , device , attrs = False ) :
"""Collect udevadm info output for a given device
: param device : A string or list of strings of device names or sysfs
paths . E . G . either ' / sys / class / scsi _ host / host0 ' or
' / dev / sda ' is valid .
: param attrs : If True , run udevadm wit... | udev_cmd = 'udevadm info'
if attrs :
udev_cmd += ' -a'
if isinstance ( device , six . string_types ) :
device = [ device ]
for dev in device :
self . _log_debug ( "collecting udev info for: %s" % dev )
self . _add_cmd_output ( '%s %s' % ( udev_cmd , dev ) ) |
def get_real ( _bytearray , byte_index ) :
"""Get real value . create float from 4 bytes""" | x = _bytearray [ byte_index : byte_index + 4 ]
real = struct . unpack ( '>f' , struct . pack ( '4B' , * x ) ) [ 0 ]
return real |
def guess_server_name ( ) :
"""We often use the same servers , which one are we running on now ?""" | if os . environ . get ( 'CSCSERVICE' ) == 'sisu' :
return "sisu"
elif os . environ . get ( 'SLURM_JOB_PARTITION' ) == 'halvan' :
return "halvan"
elif os . environ . get ( 'SNIC_RESOURCE' ) == 'milou' :
return "milou"
elif os . environ . get ( 'LAPTOP' ) == 'macbook_air' :
return "macbook_air"
else :
... |
def safe_series_resistor_index_read ( f , self , channel , resistor_index = None ) :
'''This decorator checks the resistor - index from the current context _ ( i . e . ,
the result of ` self . series _ resistor _ index ` ) _ . If the resistor - index
specified by the ` resistor _ index ` keyword argument is dif... | if resistor_index is not None :
original_resistor_index = self . series_resistor_index ( channel )
# Save state of resistor - index
if resistor_index != original_resistor_index :
self . set_series_resistor_index ( channel , resistor_index )
value = f ( self , channel )
if ( resistor_index is not Non... |
def handle ( self , request , buffer_size ) :
"""Handle a message
: param request : the request socket .
: param buffer _ size : the buffer size .
: return : True if success , False otherwise""" | if self . component_type == StreamComponent . SOURCE :
msg = self . handler_function ( )
return self . __send ( request , msg )
logger = self . logger
data = self . __receive ( request , buffer_size )
if data is None :
return False
else :
logger . debug ( data . split ( self . TERMINATOR ) )
for mes... |
def ts_to_dt_str ( ts , dt_format = '%Y-%m-%d %H:%M:%S' ) :
"""时间戳转换为日期字符串
Args :
ts : 待转换的时间戳
dt _ format : 目标日期字符串格式
Returns : 日期字符串""" | return datetime . datetime . fromtimestamp ( int ( ts ) ) . strftime ( dt_format ) |
def server_info_cb ( self , context , server_info_p , userdata ) :
"""Retrieves the default sink and calls request _ update""" | server_info = server_info_p . contents
self . request_update ( context ) |
def _is_this_a_collision ( ArgList ) :
"""Detects if a particular point is during collision after effect ( i . e . a phase shift ) or not .
Parameters
ArgList : array _ like
Contains the following elements :
value : float
value of the FM discriminator
mean _ fmd : float
the mean value of the FM discri... | value , mean_fmd , tolerance = ArgList
if not _approx_equal ( mean_fmd , value , tolerance ) :
return True
else :
return False |
def translate_text ( self , contents , target_language_code , mime_type = None , source_language_code = None , parent = None , model = None , glossary_config = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Transl... | # Wrap the transport method to add retry and timeout logic .
if "translate_text" not in self . _inner_api_calls :
self . _inner_api_calls [ "translate_text" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . translate_text , default_retry = self . _method_configs [ "TranslateText" ] . retr... |
def _find_user_channel ( self , username ) :
"""Use slacker to resolve the username to an opened IM channel""" | user_id = self . slacker . users . get_user_id ( username )
im = user_id and self . slacker . im . open ( user_id ) . body [ 'channel' ] [ 'id' ]
return im and self . slack . server . channels . find ( im ) |
def inject ( * args , ** kwargs ) :
"""Mark a class or function for injection , meaning that a DI container knows
that it should inject dependencies into it .
Normally you won ' t need this as the injector will inject the required
arguments anyway , but it can be used to inject properties into a class
witho... | def wrapper ( obj ) :
if inspect . isclass ( obj ) or callable ( obj ) :
_inject_object ( obj , * args , ** kwargs )
return obj
raise DiayException ( "Don't know how to inject into %r" % obj )
return wrapper |
def update_field ( self , element_or_ip_address = None , start_port = None , end_port = None , ** kw ) :
"""Update the source NAT translation on this rule .
You must call ` save ` or ` update ` on the rule to make this
modification . To update the source target for this NAT rule , update
the source field dire... | updated = False
src = _resolve_nat_element ( element_or_ip_address ) if element_or_ip_address else { }
automatic_proxy = kw . pop ( 'automatic_proxy' , None )
# Original value is only used when creating a rule for static src NAT .
# This should be the href of the source field to properly create
# TODO : The SMC API sho... |
def _iterOutFiles ( self ) :
"""Yields path , data , mimetype for each file involved on or produced by
profiling .""" | out = StringIO ( )
self . callgrind ( out , relative_path = True )
yield ( 'cachegrind.out.pprofile' , out . getvalue ( ) , 'application/x-kcachegrind' , )
for name , lines in self . iterSource ( ) :
lines = '' . join ( lines )
if lines :
if isinstance ( lines , unicode ) :
lines = lines . e... |
def convert_exchange_to_compounds ( model ) :
"""Convert exchange reactions in model to exchange compounds .
Only exchange reactions in the extracellular compartment are converted .
The extracelluar compartment must be defined for the model .
Args :
model : : class : ` NativeModel ` .""" | # Build set of exchange reactions
exchanges = set ( )
for reaction in model . reactions :
equation = reaction . properties . get ( 'equation' )
if equation is None :
continue
if len ( equation . compounds ) != 1 : # Provide warning for exchange reactions with more than
# one compound , they won ... |
def _step_begin ( self , label , log = True ) :
"""Log begin of a step""" | if log :
self . step_label = label
self . step_begin_time = self . log ( u"STEP %d BEGIN (%s)" % ( self . step_index , label ) ) |
def get_any_entity ( self , id = None , uri = None , match = None ) :
"""get a generic entity with given ID or via other methods . . .""" | if not id and not uri and not match :
return None
if type ( id ) == type ( "string" ) :
uri = id
id = None
if not is_http ( uri ) :
match = uri
uri = None
if match :
if type ( match ) != type ( "string" ) :
return [ ]
res = [ ]
if ":" in match : # qname
for x ... |
def _is_modified_property ( self , prop ) :
"""True , if the given property is in the modifed members
: param prop :
: return :""" | if type ( prop ) is str :
return prop in self . _modified_members
return False |
def handle_connection_exec ( client ) :
"""Alternate connection handler . No output redirection .""" | class ExitExecLoop ( Exception ) :
pass
def exit ( ) :
raise ExitExecLoop ( )
client . settimeout ( None )
fh = os . fdopen ( client . detach ( ) if hasattr ( client , 'detach' ) else client . fileno ( ) )
with closing ( client ) :
with closing ( fh ) :
try :
payload = fh . readline ( )
... |
def get_account_funds ( self , wallet = None ) :
"""Get available to bet amount .
: param Wallet wallet : Name of the wallet in question""" | return self . make_api_request ( 'Account' , 'getAccountFunds' , utils . get_kwargs ( locals ( ) ) , model = models . AccountFundsResponse , ) |
def do_build ( self , argv ) :
"""build [ TARGETS ] Build the specified TARGETS and their
dependencies . ' b ' is a synonym .""" | import SCons . Node
import SCons . SConsign
import SCons . Script . Main
options = copy . deepcopy ( self . options )
options , targets = self . parser . parse_args ( argv [ 1 : ] , values = options )
SCons . Script . COMMAND_LINE_TARGETS = targets
if targets :
SCons . Script . BUILD_TARGETS = targets
else : # If t... |
def getchild ( self , name , parent ) :
"""get a child by name""" | # log . debug ( ' searching parent ( % s ) for ( % s ) ' , Repr ( parent ) , name )
if name . startswith ( '@' ) :
return parent . get_attribute ( name [ 1 : ] )
else :
return parent . get_child ( name ) |
def deploy_template_uri_param_uri ( access_token , subscription_id , resource_group , deployment_name , template_uri , parameters_uri ) :
'''Deploy a template with both template and parameters referenced by URIs .
Args :
access _ token ( str ) : A valid Azure authentication token .
subscription _ id ( str ) :... | endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourcegroups/' , resource_group , '/providers/Microsoft.Resources/deployments/' , deployment_name , '?api-version=' , DEPLOYMENTS_API ] )
properties = { 'templateLink' : { 'uri' : template_uri } }
properties [ 'mode' ] = 'Increment... |
def reformat_meta ( self ) :
"""Collect the meta data information in a more user friendly format .
Function looks through the meta data , collecting the channel related information into a
dataframe and moving it into the _ channels _ key .""" | meta = self . annotation
# For shorthand ( passed by reference )
channel_properties = [ ]
for key , value in meta . items ( ) :
if key [ : 3 ] == '$P1' :
if key [ 3 ] not in string . digits :
channel_properties . append ( key [ 3 : ] )
# Capture all the channel information in a list of lists - -... |
def group_copy ( name , copyname , ** kwargs ) :
"""Copy routing group .""" | ctx = Context ( ** kwargs )
ctx . execute_action ( 'group:copy' , ** { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , 'copyname' : copyname , } ) |
def bg_color_native_ansi ( kernel32 , stderr , stdout ) :
"""Get background color and if console supports ANSI colors natively for both streams .
: param ctypes . windll . kernel32 kernel32 : Loaded kernel32 instance .
: param int stderr : stderr handle .
: param int stdout : stdout handle .
: return : Back... | try :
if stderr == INVALID_HANDLE_VALUE :
raise OSError
bg_color , native_ansi = get_console_info ( kernel32 , stderr ) [ 1 : ]
except OSError :
try :
if stdout == INVALID_HANDLE_VALUE :
raise OSError
bg_color , native_ansi = get_console_info ( kernel32 , stdout ) [ 1 : ]... |
def copy_and_sum_families ( family_source , family_target ) :
"""methods iterates thru source family and copies its entries to target family
in case key already exists in both families - then the values are added""" | for every in family_source :
if every not in family_target :
family_target [ every ] = family_source [ every ]
else :
family_target [ every ] += family_source [ every ] |
def _max_retries_for_error ( self , error ) :
"""Handles Datastore response errors according to their documentation .
Parameters :
error ( dict )
Returns :
int or None : The max number of times this error should be
retried or None if it shouldn ' t .
See also :
https : / / cloud . google . com / datas... | status = error . get ( "status" )
if status == "ABORTED" and get_transactions ( ) > 0 : # Avoids retrying Conflicts when inside a transaction .
return None
return self . _MAX_RETRIES . get ( status ) |
def stroke ( self ) :
"""使用stroke方法将图形绘制在窗口里 , 仅对基本的几何图形有效""" | self . update_all ( )
length = len ( self . points )
# thick lines
if self . line_width <= 3 :
if length == 4 :
self . vertex_list . draw ( pyglet . gl . GL_LINES )
elif length > 4 :
self . vertex_list . draw ( pyglet . gl . GL_LINE_LOOP )
return
color = color_to_tuple ( self . color , self ... |
def construct ( self , sp_entity_id , attrconvs , policy , issuer , farg , authn_class = None , authn_auth = None , authn_decl = None , encrypt = None , sec_context = None , authn_decl_ref = None , authn_instant = "" , subject_locality = "" , authn_statem = None , name_id = None , session_not_on_or_after = None ) :
... | if policy :
_name_format = policy . get_name_form ( sp_entity_id )
else :
_name_format = NAME_FORMAT_URI
attr_statement = saml . AttributeStatement ( attribute = from_local ( attrconvs , self , _name_format ) )
if encrypt == "attributes" :
for attr in attr_statement . attribute :
enc = sec_context .... |
def _download_helper ( url ) :
"""Handle the download of an URL , using the proxy currently set in : mod : ` socks ` .
: param url : The URL to download .
: returns : A tuple of the raw content of the downloaded data and its associated content - type . Returns None if it was unable to download the document .""" | # Try to fetch the URL using the current proxy
try :
request = urllib . request . urlopen ( url )
try :
size = int ( dict ( request . info ( ) ) [ 'content-length' ] . strip ( ) )
except KeyError :
try :
size = int ( dict ( request . info ( ) ) [ 'Content-Length' ] . strip ( ) )
... |
def _extract ( cls , compressed_file , videofile , exts ) :
"""解压字幕文件 , 如果无法解压 , 则直接返回 compressed _ file 。
exts 参数用于过滤掉非字幕文件 , 只有文件的扩展名在 exts 中 , 才解压该文件 。""" | if not CompressedFile . is_compressed_file ( compressed_file ) :
return [ compressed_file ]
root = os . path . dirname ( compressed_file )
subs = [ ]
cf = CompressedFile ( compressed_file )
for name in cf . namelist ( ) :
if cf . isdir ( name ) :
continue
# make ` name ` to unicode string
orig_n... |
def route ( method , pattern , handler = None ) :
"""register a routing rule
Example :
route ( ' GET ' , ' / path / < param > ' , handler )""" | if handler is None :
return partial ( route , method , pattern )
return routes . append ( method , pattern , handler ) |
def completion_acd ( edm , X0 , W = None , tol = 1e-6 , sweeps = 3 ) :
"""Complete an denoise EDM using alternating decent .
The idea here is to simply run reconstruct _ acd for a few iterations ,
yieding a position estimate , which can in turn be used
to get a completed and denoised edm .
: param edm : noi... | from . algorithms import reconstruct_acd
Xhat , costs = reconstruct_acd ( edm , X0 , W , tol = tol , sweeps = sweeps )
return get_edm ( Xhat ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.