signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def wncomd ( left , right , window ) :
"""Determine the complement of a double precision window with
respect to a specified interval .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / wncomd _ c . html
: param left : left endpoints of complement interval .
: type left : float ... | assert isinstance ( window , stypes . SpiceCell )
assert window . dtype == 1
left = ctypes . c_double ( left )
right = ctypes . c_double ( right )
result = stypes . SpiceCell . double ( window . size )
libspice . wncomd_c ( left , right , ctypes . byref ( window ) , result )
return result |
def range_window ( preceding = None , following = None , group_by = None , order_by = None ) :
"""Create a range - based window clause for use with window functions .
This RANGE window clause aggregates rows based upon differences in the
value of the order - by expression .
All window frames / ranges are incl... | return Window ( preceding = preceding , following = following , group_by = group_by , order_by = order_by , how = 'range' , ) |
def _git_diff ( self ) :
"""Run ` git diff ` and returns a dict in which the keys
are changed file paths and the values are lists of
line numbers .
Guarantees that each line number within a file
is unique ( no repeats ) and in ascending order .
Returns a cached result if called multiple times .
Raises a... | # If we do not have a cached result , execute ` git diff `
if self . _diff_dict is None :
result_dict = dict ( )
for diff_str in self . _get_included_diff_results ( ) : # Parse the output of the diff string
diff_dict = self . _parse_diff_str ( diff_str )
for src_path in diff_dict . keys ( ) :
... |
def correct ( self , temp , we_t ) :
"""Compute weC from weT""" | if not PIDTempComp . in_range ( temp ) :
return None
n_t = self . cf_t ( temp )
if n_t is None :
return None
we_c = we_t * n_t
return we_c |
def remove_custom_binding ( self , key_name , needs_prefix = False ) :
"""Remove custom key binding for a key .
: param key _ name : Pymux key name , for instance " C - A " .""" | k = ( needs_prefix , key_name )
if k in self . custom_bindings :
self . custom_key_bindings . remove ( self . custom_bindings [ k ] . handler )
del self . custom_bindings [ k ] |
def delete_action ( action_id ) :
"""Delete action .""" | action = get_data_or_404 ( 'action' , action_id )
project = get_data_or_404 ( 'project' , action [ 'project_id' ] )
if project [ 'owner_id' ] != get_current_user_id ( ) :
return jsonify ( message = 'forbidden' ) , 403
delete_instance ( 'sender' , action [ 'id' ] )
return jsonify ( { } ) |
def get_imported_repo ( self , import_path ) :
"""Looks for a go - import meta tag for the provided import _ path .
Returns an ImportedRepo instance with the information in the meta tag ,
or None if no go - import meta tag is found .""" | try :
session = requests . session ( )
# TODO : Support https with ( optional ) fallback to http , as Go does .
# See https : / / github . com / pantsbuild / pants / issues / 3503.
session . mount ( "http://" , requests . adapters . HTTPAdapter ( max_retries = self . get_options ( ) . retries ) )
pa... |
def stop ( self , timeout_s = None ) :
"""Stops the interval .
If a timeout is provided and stop returns False then the thread is
effectively abandoned in whatever state it was in ( presumably dead - locked ) .
Args :
timeout _ s : The time in seconds to wait on the thread to finish . By
default it ' s fo... | self . stopped . set ( )
if self . thread :
self . thread . join ( timeout_s )
return not self . thread . isAlive ( )
else :
return True |
async def async_open ( self ) -> None :
"""Opens connection to the LifeSOS ethernet interface .""" | await self . _loop . create_connection ( lambda : self , self . _host , self . _port ) |
def get_eargs ( ) :
"""Look for options in environment vars""" | settings = { }
zmq = os . environ . get ( "ZMQ_PREFIX" , None )
if zmq is not None :
debug ( "Found environ var ZMQ_PREFIX=%s" % zmq )
settings [ 'zmq_prefix' ] = zmq
return settings |
def _remove_redundancy ( self , log ) :
"""Removes duplicate data from ' data ' inside log dict and brings it
out .
> > > lc = LogCollector ( ' file = / path / to / log _ file . log : formatter = logagg . formatters . basescript ' , 30)
> > > log = { ' id ' : 46846876 , ' type ' : ' log ' ,
. . . ' data ' :... | for key in log :
if key in log and key in log [ 'data' ] :
log [ key ] = log [ 'data' ] . pop ( key )
return log |
def merge_subreturn ( original_return , sub_return , subkey = None ) :
'''Update an existing state return ( ` original _ return ` ) in place
with another state return ( ` sub _ return ` ) , i . e . for a subresource .
Returns :
dict : The updated state return .
The existing state return does not need to hav... | if not subkey :
subkey = sub_return [ 'name' ]
if sub_return [ 'result' ] is False : # True or None stay the same
original_return [ 'result' ] = sub_return [ 'result' ]
sub_comment = sub_return [ 'comment' ]
if not isinstance ( sub_comment , list ) :
sub_comment = [ sub_comment ]
original_return . setdefaul... |
def add_version_tracking ( self , info_id , version , date , command_line = '' ) :
"""Add a line with information about which software that was run and when
to the header .
Arguments :
info _ id ( str ) : The id of the info line
version ( str ) : The version of the software used
date ( str ) : Date when s... | other_line = '##Software=<ID={0},Version={1},Date="{2}",CommandLineOptions="{3}">' . format ( info_id , version , date , command_line )
self . other_dict [ info_id ] = other_line
return |
def wait ( self , delay ) :
"""Wait at the current location for the specified number of iterations .
: param delay : The time to wait ( in animation frames ) .""" | for _ in range ( 0 , delay ) :
self . _add_step ( ( self . _rec_x , self . _rec_y ) ) |
def load_filter_plugins ( entrypoint_group : str ) -> Iterable [ Filter ] :
"""Load all blacklist plugins that are registered with pkg _ resources
Parameters
entrypoint _ group : str
The entrypoint group name to load plugins from
Returns
List of Blacklist :
A list of objects derived from the Blacklist c... | global loaded_filter_plugins
enabled_plugins : List [ str ] = [ ]
config = BandersnatchConfig ( ) . config
try :
config_blacklist_plugins = config [ "blacklist" ] [ "plugins" ]
split_plugins = config_blacklist_plugins . split ( "\n" )
if "all" in split_plugins :
enabled_plugins = [ "all" ]
else ... |
def request ( self , method , suffix , data ) :
""": param method : str , http method [ " GET " , " POST " , " PUT " ]
: param suffix : the url suffix
: param data :
: return :""" | url = self . site_url + suffix
response = self . session . request ( method , url , data = data )
if response . status_code == 200 :
json_obj = response . json ( )
if isinstance ( json_obj , dict ) and json_obj . get ( "error_code" ) :
raise WeiboOauth2Error ( json_obj . get ( "error_code" ) , json_obj ... |
def to_foreign ( self , obj , name , value ) : # pylint : disable = unused - argument
"""Transform to a MongoDB - safe value .""" | namespace = self . namespace
try :
explicit = self . explicit
except AttributeError :
explicit = not namespace
if not isinstance ( value , ( str , unicode ) ) :
value = canon ( value )
if namespace and ':' in value : # Try to reduce to a known plugin short name .
for point in iter_entry_points ( namespa... |
def _compile_files ( self ) :
"""Compiles python plugin files in order to be processed by the loader .
It compiles the plugins if they have been updated or haven ' t yet been
compiled .""" | for f in glob . glob ( os . path . join ( self . dir_path , '*.py' ) ) : # Check for compiled Python files that aren ' t in the _ _ pycache _ _ .
if not os . path . isfile ( os . path . join ( self . dir_path , f + 'c' ) ) :
compileall . compile_dir ( self . dir_path , quiet = True )
logging . debug... |
def get ( context , request , resource = None , uid = None ) :
"""GET""" | # We have a UID , return the record
if uid and not resource :
return api . get_record ( uid )
# we have a UID as resource , return the record
if api . is_uid ( resource ) :
return api . get_record ( resource )
portal_type = api . resource_to_portal_type ( resource )
if portal_type is None :
raise APIError (... |
def floor_nearest ( x , dx = 1 ) :
"""floor a number to within a given rounding accuracy""" | precision = get_sig_digits ( dx )
return round ( math . floor ( float ( x ) / dx ) * dx , precision ) |
def _unquote_or_none ( s : Optional [ str ] ) -> Optional [ bytes ] : # noqa : F811
"""None - safe wrapper around url _ unescape to handle unmatched optional
groups correctly .
Note that args are passed as bytes so the handler can decide what
encoding to use .""" | if s is None :
return s
return url_unescape ( s , encoding = None , plus = False ) |
def result ( self , result ) :
"""Sets the result of this ResponseStatus .
: param result : The result of this ResponseStatus . # noqa : E501
: type : str""" | if result is None :
raise ValueError ( "Invalid value for `result`, must not be `None`" )
# noqa : E501
allowed_values = [ "OK" , "ERROR" ]
# noqa : E501
if result not in allowed_values :
raise ValueError ( "Invalid value for `result` ({0}), must be one of {1}" # noqa : E501
. format ( result , allowed_... |
def render ( self ) :
'''Render a matplotlib figure from the analyzer result
Return the figure , use fig . show ( ) to display if neeeded''' | fig , ax = plt . subplots ( )
self . data_object . _render_plot ( ax )
return fig |
def default ( self , obj ) :
"""Serialize obj into JSON .""" | # pylint : disable = method - hidden , protected - access , arguments - differ
if isinstance ( obj , Sensor ) :
return { 'sensor_id' : obj . sensor_id , 'children' : obj . children , 'type' : obj . type , 'sketch_name' : obj . sketch_name , 'sketch_version' : obj . sketch_version , 'battery_level' : obj . battery_l... |
def createEditor ( self , parent , column , operator , value ) :
"""Creates a new editor for the given parent and operator .
: param parent | < QWidget >
operator | < str >
value | < variant >""" | if type ( value ) == datetime . timedelta :
editor = XTimeDeltaEdit ( parent )
editor . setAttribute ( Qt . WA_DeleteOnClose )
editor . setDelta ( value )
return editor
else :
editor = super ( DateTimePlugin , self ) . createEditor ( parent , column , operator , value )
if isinstance ( editor , ... |
def profile_execution ( self , status ) :
"""Return run total value .""" | self . selected_profile . data [ 'execution_success' ] = status
if status :
self . report [ 'results' ] [ 'executions' ] [ 'pass' ] += 1
else :
self . report [ 'results' ] [ 'executions' ] [ 'fail' ] += 1
if self . selected_profile . name not in self . report [ 'results' ] [ 'failed_profiles' ] :
se... |
def add_offsets ( self , offset_ns = None ) :
"""adds the onset and offset to each token in the document graph , i . e .
the character position where each token starts and ends .""" | if offset_ns is None :
offset_ns = self . ns
onset = 0
offset = 0
for token_id , token_str in self . get_tokens ( ) :
offset = onset + len ( token_str )
self . node [ token_id ] [ '{0}:{1}' . format ( offset_ns , 'onset' ) ] = onset
self . node [ token_id ] [ '{0}:{1}' . format ( offset_ns , 'offset' ) ... |
def split_ext ( path , basename = True ) :
"""Wrap them to make life easier .""" | if basename :
path = os . path . basename ( path )
return os . path . splitext ( path ) |
def vm_netstats ( vm_ = None ) :
'''Return combined network counters used by the vms on this hyper in a
list of dicts :
. . code - block : : python
' your - vm ' : {
' io _ read _ kbs ' : 0,
' io _ total _ read _ kbs ' : 0,
' io _ total _ write _ kbs ' : 0,
' io _ write _ kbs ' : 0
If you pass a VM ... | with _get_xapi_session ( ) as xapi :
def _info ( vm_ ) :
ret = { }
vm_rec = _get_record_by_label ( xapi , 'VM' , vm_ )
if vm_rec is False :
return False
for vif in vm_rec [ 'VIFs' ] :
vif_rec = _get_record ( xapi , 'VIF' , vif )
ret [ vif_rec [ 'de... |
def _translate_space ( self , space ) :
"""Translates a list of dictionaries into internal list of variables""" | self . space = [ ]
self . dimensionality = 0
self . has_types = d = { t : False for t in self . supported_types }
for i , d in enumerate ( space ) :
descriptor = deepcopy ( d )
descriptor [ 'name' ] = descriptor . get ( 'name' , 'var_' + str ( i ) )
descriptor [ 'type' ] = descriptor . get ( 'type' , 'conti... |
def new_result ( self , job , update_model = True ) :
"""registers finished runs
Every time a run has finished , this function should be called
to register it with the result logger . If overwritten , make
sure to call this method from the base class to ensure proper
logging .
Parameters
job : instance ... | if not job . exception is None :
self . logger . warning ( "job {} failed with exception\n{}" . format ( job . id , job . exception ) ) |
def dict_to_numpy_dict ( obj_dict ) :
"""Convert a dictionary of lists into a dictionary of numpy arrays""" | return { key : np . asarray ( value ) if value is not None else None for key , value in obj_dict . items ( ) } |
def update_room_from_obj ( settings , vc_room , room_obj ) :
"""Updates a VCRoom DB object using a SOAP room object returned by the API""" | vc_room . name = room_obj . name
if room_obj . ownerName != vc_room . data [ 'owner_identity' ] :
owner = get_user_from_identifier ( settings , room_obj . ownerName ) or User . get_system_user ( )
vc_room . vidyo_extension . owned_by_user = owner
vc_room . data . update ( { 'description' : room_obj . descriptio... |
def update_dtype ( self , resvar = None ) :
"""Updates the dtype attribute of the function . This is required because
fortran functions can have their types declared either as a modifier on
the function * or * as a member inside the function .
: arg resvar : the name of the variable declared using the result ... | if self . dtype is None : # search the members of this function for one that has the same name
# as the function . If it gets found , overwrite the dtype , kind and
# modifiers attributes so the rest of the code works .
for m in self . members :
if m == self . name . lower ( ) or m == resvar :
m... |
def nfa_dot_importer ( input_file : str ) -> dict :
"""Imports a NFA from a DOT file .
Of . dot files are recognized the following attributes
• nodeX shape = doublecircle - > accepting node ;
• nodeX root = true - > initial node ;
• edgeX label = " a " - > action in alphabet ;
• fakeX style = invisible - ... | # pyDot Object
g = pydot . graph_from_dot_file ( input_file ) [ 0 ]
states = set ( )
initial_states = set ( )
accepting_states = set ( )
replacements = { '"' : '' , "'" : '' , '(' : '' , ')' : '' , ' ' : '' }
for node in g . get_nodes ( ) :
attributes = node . get_attributes ( )
if node . get_name ( ) == 'fake'... |
def generate_git_version_info ( ) :
"""Query the git repository information to generate a version module .""" | info = GitInfo ( )
git_path = call ( ( 'which' , 'git' ) )
# get build info
info . builder = get_build_name ( )
info . build_date = get_build_date ( )
# parse git ID
info . hash , info . date , info . author , info . committer = ( get_last_commit ( git_path ) )
# determine branch
info . branch = get_git_branch ( git_pa... |
def set_pixel ( self , x , y , color ) :
"""Color may be : value , tuple , list etc .
If the image is set to contain more color - channels than len ( color ) , the
remaining channels will be filled automatically .
Example ( channels = 4 , i . e . RGBA output ) :
color = 17 - > color = [ 17,17,17,255]
colo... | try : # these checks are for convenience , not for safety
if len ( color ) < self . channels : # color is a a tuple ( length > = 1)
if len ( color ) == 1 :
if self . channels == 2 :
color = [ color [ 0 ] , 255 ]
elif self . channels == 3 :
color = [ co... |
def pyvolvePartitions ( model , divselection = None ) :
"""Get list of ` pyvolve ` partitions for ` model ` .
Args :
` model ` ( ` phydmslib . models . Models ` object )
The model used for the simulations . Currently only
certain ` Models ` are supported ( e . g . , ` YNGKP ` ,
` ExpCM ` )
` divselectio... | codons = pyvolve . genetics . Genetics ( ) . codons
codon_dict = pyvolve . genetics . Genetics ( ) . codon_dict
pyrims = pyvolve . genetics . Genetics ( ) . pyrims
purines = pyvolve . genetics . Genetics ( ) . purines
if divselection :
( divomega , divsites ) = divselection
else :
divsites = [ ]
assert all ( [ ... |
def export ( self , nidm_version , export_dir ) :
"""Create prov graph .""" | # Contrast Map entity
atts = ( ( PROV [ 'type' ] , NIDM_CONTRAST_MAP ) , ( NIDM_CONTRAST_NAME , self . name ) )
if not self . isderfrommap :
atts = atts + ( ( NIDM_IN_COORDINATE_SPACE , self . coord_space . id ) , )
if self . label is not None :
atts = atts + ( ( PROV [ 'label' ] , self . label ) , )
if self . ... |
def on_click ( self , event ) :
"""Volume up / down and toggle mute .""" | button = event [ "button" ]
# volume up
if button == self . button_up :
self . backend . volume_up ( self . volume_delta )
# volume down
elif button == self . button_down :
self . backend . volume_down ( self . volume_delta )
# toggle mute
elif button == self . button_mute :
self . backend . toggle_mute ( ) |
def get_credentials ( username : str = None , ** kwargs ) -> dict :
"""Calculate credentials for Axes to use internally from given username and kwargs .
Axes will set the username value into the key defined with ` ` settings . AXES _ USERNAME _ FORM _ FIELD ` `
and update the credentials dictionary with the kwa... | credentials = { settings . AXES_USERNAME_FORM_FIELD : username }
credentials . update ( kwargs )
return credentials |
def register ( self ) :
"""Register this resource for later retrieval via lookup ( ) , possibly in a child process .""" | os . environ [ self . resourceEnvNamePrefix + self . pathHash ] = self . pickle ( ) |
def as_dict ( self ) :
"""Return a ditionary mapping time slide IDs to offset
dictionaries .""" | d = { }
for row in self :
if row . time_slide_id not in d :
d [ row . time_slide_id ] = offsetvector . offsetvector ( )
if row . instrument in d [ row . time_slide_id ] :
raise KeyError ( "'%s': duplicate instrument '%s'" % ( row . time_slide_id , row . instrument ) )
d [ row . time_slide_id... |
def to_forward_slashes ( data ) :
"""Converts backward slashes to forward slashes .
Usage : :
> > > to _ forward _ slashes ( " To \ Forward \ Slashes " )
u ' To / Forward / Slashes '
: param data : Data to convert .
: type data : unicode
: return : Converted path .
: rtype : unicode""" | data = data . replace ( "\\" , "/" )
LOGGER . debug ( "> Data: '{0}' to forward slashes." . format ( data ) )
return data |
def _simplify ( cls , operands : List [ Expression ] ) -> bool :
"""Flatten / sort the operands of associative / commutative operations .
Returns :
True iff * one _ identity * is True and the operation contains a single
argument that is not a sequence wildcard .""" | if cls . associative :
new_operands = [ ]
# type : List [ Expression ]
for operand in operands :
if isinstance ( operand , cls ) :
new_operands . extend ( operand . operands )
# type : ignore
else :
new_operands . append ( operand )
operands . clear ( ... |
def mmi_to_raster ( self , force_flag = False , algorithm = USE_ASCII ) :
"""Convert the grid . xml ' s mmi column to a raster using gdal _ grid .
A geotiff file will be created .
Unfortunately no python bindings exist for doing this so we are
going to do it using a shell call .
. . see also : : http : / / ... | LOGGER . debug ( 'mmi_to_raster requested.' )
if algorithm is None :
algorithm = USE_ASCII
if self . algorithm_name :
tif_path = os . path . join ( self . output_dir , '%s-%s.tif' % ( self . output_basename , algorithm ) )
else :
tif_path = os . path . join ( self . output_dir , '%s.tif' % self . output_bas... |
def change_crypto_domain_config ( self , crypto_domain_index , access_mode ) :
"""Change the access mode for a crypto domain that is currently included
in the crypto configuration of this partition .
The access mode will be changed for the specified crypto domain on all
crypto adapters currently included in t... | body = { 'domain-index' : crypto_domain_index , 'access-mode' : access_mode }
self . manager . session . post ( self . uri + '/operations/change-crypto-domain-configuration' , body ) |
def zinb_ll ( data , P , R , Z ) :
"""Returns the zero - inflated negative binomial log - likelihood of the data .""" | lls = nb_ll ( data , P , R )
clusters = P . shape [ 1 ]
for c in range ( clusters ) :
pass
return lls |
def bake ( self ) :
"""Bake an ` ansible - lint ` command so it ' s ready to execute and returns
None .
: return : None""" | options = self . options
default_exclude_list = options . pop ( 'default_exclude' )
options_exclude_list = options . pop ( 'exclude' )
excludes = default_exclude_list + options_exclude_list
x_list = options . pop ( 'x' )
exclude_args = [ '--exclude={}' . format ( exclude ) for exclude in excludes ]
x_args = tuple ( ( '... |
def delete_channel_cb ( self , gshell , chinfo ) :
"""Called when a channel is deleted from the main interface .
Parameter is chinfo ( a bunch ) .""" | chname = chinfo . name
if chname not in self . name_dict :
return
del self . name_dict [ chname ]
self . logger . debug ( '{0} removed from ChangeHistory' . format ( chname ) )
if not self . gui_up :
return False
self . clear_selected_history ( )
self . recreate_toc ( ) |
def visualize ( ctx , meta_model_file , model_file , ignore_case , output_format ) :
"""Generate . dot file ( s ) from meta - model and optionally model .""" | debug = ctx . obj [ 'debug' ]
meta_model , model = check_model ( meta_model_file , model_file , debug , ignore_case )
if output_format == 'plantuml' :
pu_file = "{}.pu" . format ( meta_model_file )
click . echo ( "Generating '{}' file for meta-model." . format ( pu_file ) )
click . echo ( "To convert to png... |
def map_keys ( pvs , keys ) :
"""Add human readable key names to dictionary while leaving any existing key names .""" | rs = [ ]
for pv in pvs :
r = dict ( ( v , None ) for k , v in keys . items ( ) )
for k , v in pv . items ( ) :
if k in keys :
r [ keys [ k ] ] = v
r [ k ] = v
rs . append ( r )
return rs |
def _tffunc ( * argtypes ) :
'''Helper that transforms TF - graph generating function into a regular one .
See ` _ resize ` function below .''' | placeholders = list ( map ( tf . placeholder , argtypes ) )
def wrap ( f ) :
out = f ( * placeholders )
def wrapper ( * args , ** kw ) :
return out . eval ( dict ( zip ( placeholders , args ) ) , session = kw . get ( 'session' ) )
return wrapper
return wrap |
def assign_messagetypes ( self , messages , clusters ) :
"""Assign message types based on the clusters . Following rules :
1 ) Messages from different clusters will get different message types
2 ) Messages from same clusters will get same message type
3 ) The new message type will copy over the existing label... | for clustername , clustercontent in clusters . items ( ) :
if clustername == "default" : # Do not force the default message type
continue
for msg_i in clustercontent :
msg = messages [ msg_i ]
if msg . message_type == self . messagetypes [ 0 ] : # Message has default message type
... |
def update_fw_local_cache ( self , net , direc , start ) :
"""Update the fw dict with Net ID and service IP .""" | fw_dict = self . get_fw_dict ( )
if direc == 'in' :
fw_dict . update ( { 'in_network_id' : net , 'in_service_ip' : start } )
else :
fw_dict . update ( { 'out_network_id' : net , 'out_service_ip' : start } )
self . update_fw_dict ( fw_dict ) |
def __load_settings ( self ) :
"""Load settings from . json file""" | # file _ path = path . relpath ( settings _ file _ path )
# file _ path = path . abspath ( settings _ file _ path )
file_path = self . file_path
try :
self . data = json . load ( open ( file_path ) )
except FileNotFoundError :
print ( "Could not load" , file_path ) |
def run_main ( ) :
"""run _ main
Search Splunk""" | parser = argparse . ArgumentParser ( description = ( 'Search Splunk' ) )
parser . add_argument ( '-u' , help = 'username' , required = False , dest = 'user' )
parser . add_argument ( '-p' , help = 'user password' , required = False , dest = 'password' )
parser . add_argument ( '-f' , help = 'splunk-ready request in a j... |
def print_str ( self , value , justify_right = True ) :
"""Print a 4 character long string of values to the display . Characters
in the string should be any ASCII value 32 to 127 ( printable ASCII ) .""" | # Calculcate starting position of digits based on justification .
pos = ( 4 - len ( value ) ) if justify_right else 0
# Go through each character and print it on the display .
for i , ch in enumerate ( value ) :
self . set_digit ( i + pos , ch ) |
def cls_sets ( cls , wanted_cls , registered = True ) :
"""Return a list of all ` wanted _ cls ` attributes in this
class , where ` wanted _ cls ` is the desired attribute type .""" | sets = [ ]
for attr in dir ( cls ) :
if attr . startswith ( '_' ) :
continue
val = getattr ( cls , attr , None )
if not isinstance ( val , wanted_cls ) :
continue
if ( not registered ) and getattr ( val , '_registered' , False ) :
continue
sets . append ( val )
return sets |
def lm_freqs_taus ( ** kwargs ) :
"""Take input _ params and return dictionaries with frequencies and damping
times of each overtone of a specific lm mode , checking that all of them
are given .""" | lmns = kwargs [ 'lmns' ]
freqs , taus = { } , { }
for lmn in lmns :
l , m , nmodes = int ( lmn [ 0 ] ) , int ( lmn [ 1 ] ) , int ( lmn [ 2 ] )
for n in range ( nmodes ) :
try :
freqs [ '%d%d%d' % ( l , m , n ) ] = kwargs [ 'f_%d%d%d' % ( l , m , n ) ]
except KeyError :
ra... |
def _add_observation ( self , x_to_add , y_to_add ) :
"""Add observation to window , updating means / variance efficiently .""" | self . _add_observation_to_means ( x_to_add , y_to_add )
self . _add_observation_to_variances ( x_to_add , y_to_add )
self . window_size += 1 |
def store_password_in_keyring ( credential_id , username , password = None ) :
'''Interactively prompts user for a password and stores it in system keyring''' | try : # pylint : disable = import - error
import keyring
import keyring . errors
# pylint : enable = import - error
if password is None :
prompt = 'Please enter password for {0}: ' . format ( credential_id )
try :
password = getpass . getpass ( prompt )
except EOFErro... |
def parse_rawprofile_blocks ( text ) :
"""Split the file into blocks along delimters and and put delimeters back in
the list""" | # The total time reported in the raw output is from pystone not kernprof
# The pystone total time is actually the average time spent in the function
delim = 'Total time: '
delim2 = 'Pystone time: '
# delim = ' File : '
profile_block_list = ut . regex_split ( '^' + delim , text )
for ix in range ( 1 , len ( profile_bloc... |
def stop ( ) :
'''Stop KodeDrive daemon .''' | output , err = cli_syncthing_adapter . sys ( exit = True )
click . echo ( "%s" % output , err = err ) |
def hscan ( self , name , cursor = '0' , match = None , count = 10 ) :
"""Emulate hscan .""" | def value_function ( ) :
values = self . hgetall ( name )
values = list ( values . items ( ) )
# list of tuples for sorting and matching
values . sort ( key = lambda x : x [ 0 ] )
# sort for consistent order
return values
scanned = self . _common_scan ( value_function , cursor = cursor , match =... |
def fit ( self , struct1 , struct2 ) :
"""Fit two structures .
Args :
struct1 ( Structure ) : 1st structure
struct2 ( Structure ) : 2nd structure
Returns :
True or False .""" | struct1 , struct2 = self . _process_species ( [ struct1 , struct2 ] )
if not self . _subset and self . _comparator . get_hash ( struct1 . composition ) != self . _comparator . get_hash ( struct2 . composition ) :
return None
struct1 , struct2 , fu , s1_supercell = self . _preprocess ( struct1 , struct2 )
match = se... |
def add_compliance_header ( self ) :
"""Add IIIF Compliance level header to response .""" | if ( self . manipulator . compliance_uri is not None ) :
self . headers [ 'Link' ] = '<' + self . manipulator . compliance_uri + '>;rel="profile"' |
def user_loc_value_to_instance_string ( axis_tag , user_loc ) :
"""Return the Glyphs UI string ( from the instance dropdown ) that is
closest to the provided user location .
> > > user _ loc _ value _ to _ instance _ string ( ' wght ' , 430)
' Normal '
> > > user _ loc _ value _ to _ instance _ string ( ' w... | codes = { }
if axis_tag == "wght" :
codes = WEIGHT_CODES
elif axis_tag == "wdth" :
codes = WIDTH_CODES
else :
raise NotImplementedError
class_ = user_loc_value_to_class ( axis_tag , user_loc )
return min ( sorted ( ( code , class_ ) for code , class_ in codes . items ( ) if code is not None ) , key = lambda... |
def _attr_data_ ( self , slots ) :
"""Does not work as expected , makes an empty object with a new _ _ slots _ _
definition .""" | self . __attr_data = type ( '' . join ( [ type ( self ) . __name__ , 'Data' ] ) , ( ) , { '__module__' : type ( self ) . __module__ , '__slots__' : tuple ( set ( slots ) ) } ) ( ) |
def demultiplex_samples ( data ) :
"""demultiplex a fastqtransformed FASTQ file into separate sample barcode files""" | work_dir = os . path . join ( dd . get_work_dir ( data ) , "umis" )
sample_dir = os . path . join ( work_dir , dd . get_sample_name ( data ) )
demulti_dir = os . path . join ( sample_dir , "demultiplexed" )
files = data [ "files" ]
if len ( files ) == 2 :
logger . error ( "Sample demultiplexing doesn't handle paire... |
def __get_action_graph_pairs_from_query ( self , query ) :
"""Splits the query into command / argument pairs , for example [ ( " MATCH " , " { } ( _ a ) ) " , ( " RETURN " , " _ a " ) ]
: param query : The string with the list of commands
: return : the command / argument pairs""" | import re
query = convert_special_characters_to_spaces ( query )
graph_list = re . split ( '|' . join ( self . action_list ) , query )
query_list_positions = [ query . find ( graph ) for graph in graph_list ]
query_list_positions = query_list_positions
query_list_positions = query_list_positions
action_list = [ query [... |
def save ( self , * args , ** kwargs ) :
"""* * uid * * : : code : ` { race . uid } _ election : { election _ day } - { party } `""" | if self . party :
self . uid = "{}_election:{}-{}" . format ( self . race . uid , self . election_day . date , slugify ( self . party . ap_code ) , )
else :
self . uid = "{}_election:{}" . format ( self . race . uid , self . election_day . date )
super ( Election , self ) . save ( * args , ** kwargs ) |
def nsx_controller_connection_addr_address ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
nsx_controller = ET . SubElement ( config , "nsx-controller" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" )
name_key = ET . SubElement ( nsx_controller , "name" )
name_key . text = kwargs . pop ( 'name' )
connection_addr = ET . SubElement ( nsx_controller , "connection-addr" )
add... |
def remove_template_from_network ( network_id , template_id , remove_attrs , ** kwargs ) :
"""Remove all resource types in a network relating to the specified
template .
remove _ attrs
Flag to indicate whether the attributes associated with the template
types should be removed from the resources in the netw... | try :
network = db . DBSession . query ( Network ) . filter ( Network . id == network_id ) . one ( )
except NoResultFound :
raise HydraError ( "Network %s not found" % network_id )
try :
template = db . DBSession . query ( Template ) . filter ( Template . id == template_id ) . one ( )
except NoResultFound :... |
def _connect ( self ) :
"""Connect to Memcached .""" | if self . _socketFile is not None :
if not os . path . exists ( self . _socketFile ) :
raise Exception ( "Socket file (%s) for Memcached Instance not found." % self . _socketFile )
try :
if self . _timeout is not None :
self . _conn = util . Telnet ( self . _host , self . _port , self . _socketF... |
def __create ( self ) :
"""Construct the email""" | self . __data = json . dumps ( { 'config_path' : self . encode ( self . config_path ) , 'subject' : self . encode ( self . __subject ) , 'text' : self . encode ( self . __text ) , 'html' : self . encode ( self . __html ) , 'files' : self . __files , 'send_as_one' : self . send_as_one , 'addresses' : self . __addresses ... |
def _parse ( self , command ) :
"""Parse a single command .""" | cmd , id_ , args = command [ 0 ] , command [ 1 ] , command [ 2 : ]
if cmd == 'CURRENT' : # This context is made current
self . env . clear ( )
self . _gl_initialize ( )
self . env [ 'fbo' ] = args [ 0 ]
gl . glBindFramebuffer ( gl . GL_FRAMEBUFFER , args [ 0 ] )
elif cmd == 'FUNC' : # GL function call
... |
def gen_str ( src , dst ) :
"""Return a STR instruction .""" | return ReilBuilder . build ( ReilMnemonic . STR , src , ReilEmptyOperand ( ) , dst ) |
def overlapping ( start1 , end1 , start2 , end2 ) :
"""> > > overlapping ( 0 , 5 , 6 , 7)
False
> > > overlapping ( 1 , 2 , 0 , 4)
True
> > > overlapping ( 5,6,0,5)
False""" | return not ( ( start1 <= start2 and start1 <= end2 and end1 <= end2 and end1 <= start2 ) or ( start1 >= start2 and start1 >= end2 and end1 >= end2 and end1 >= start2 ) ) |
def datetime_parser ( s ) :
"""Parse timestamp s in local time . First the arrow parser is used , if it fails , the parsedatetime parser is used .
: param s :
: return :""" | try :
ts = arrow . get ( s )
# Convert UTC to local , result of get is UTC unless it specifies timezone , bonfire assumes
# all time to be machine local
if ts . tzinfo == arrow . get ( ) . tzinfo :
ts = ts . replace ( tzinfo = 'local' )
except :
c = pdt . Calendar ( )
result , what = c .... |
def execute ( self ) :
"""Execute the actions necessary to perform a ` molecule init role ` and
returns None .
: return : None""" | role_name = self . _command_args [ 'role_name' ]
role_directory = os . getcwd ( )
msg = 'Initializing new role {}...' . format ( role_name )
LOG . info ( msg )
if os . path . isdir ( role_name ) :
msg = ( 'The directory {} exists. ' 'Cannot create new role.' ) . format ( role_name )
util . sysexit_with_message ... |
def start_worker_thread ( self , sleep_interval = 1.0 ) :
"""start _ worker _ thread
Start the helper worker thread to publish queued messages
to Splunk
: param sleep _ interval : sleep in seconds before reading from
the queue again""" | # Start a worker thread responsible for sending logs
if self . sleep_interval > 0 :
self . debug_log ( 'starting worker thread' )
self . timer = Timer ( sleep_interval , self . perform_work )
self . timer . daemon = True
# Auto - kill thread if main process exits
self . timer . start ( ) |
def maybe_convert_platform_interval ( values ) :
"""Try to do platform conversion , with special casing for IntervalArray .
Wrapper around maybe _ convert _ platform that alters the default return
dtype in certain cases to be compatible with IntervalArray . For example ,
empty lists return with integer dtype ... | if isinstance ( values , ( list , tuple ) ) and len ( values ) == 0 : # GH 19016
# empty lists / tuples get object dtype by default , but this is not
# prohibited for IntervalArray , so coerce to integer instead
return np . array ( [ ] , dtype = np . int64 )
elif is_categorical_dtype ( values ) :
values = np . ... |
def code_binary ( item ) :
"""Return a binary ' code ' suitable for hashing .""" | code_str = code ( item )
if isinstance ( code_str , six . string_types ) :
return code_str . encode ( 'utf-8' )
return code_str |
def clean_text_by_sentences ( text , language = "english" , additional_stopwords = None ) :
"""Tokenizes a given text into sentences , applying filters and lemmatizing them .
Returns a SyntacticUnit list .""" | init_textcleanner ( language , additional_stopwords )
original_sentences = split_sentences ( text )
filtered_sentences = filter_words ( original_sentences )
return merge_syntactic_units ( original_sentences , filtered_sentences ) |
def get ( self , thread = None , plugin = None ) :
"""Get one or more threads .
: param thread : Name of the thread
: type thread : str
: param plugin : Plugin object , under which the thread was registered
: type plugin : GwBasePattern""" | if plugin is not None :
if thread is None :
threads_list = { }
for key in self . threads . keys ( ) :
if self . threads [ key ] . plugin == plugin :
threads_list [ key ] = self . threads [ key ]
return threads_list
else :
if thread in self . threads . ... |
def replace ( self , old , new ) :
"""Replace an instruction""" | if old . type != new . type :
raise TypeError ( "new instruction has a different type" )
pos = self . instructions . index ( old )
self . instructions . remove ( old )
self . instructions . insert ( pos , new )
for bb in self . parent . basic_blocks :
for instr in bb . instructions :
instr . replace_usa... |
def _remove_unit_rule ( g , rule ) :
"""Removes ' rule ' from ' g ' without changing the langugage produced by ' g ' .""" | new_rules = [ x for x in g . rules if x != rule ]
refs = [ x for x in g . rules if x . lhs == rule . rhs [ 0 ] ]
new_rules += [ build_unit_skiprule ( rule , ref ) for ref in refs ]
return Grammar ( new_rules ) |
def validate_field ( self , field_name : str ) -> bool :
"""Complain if a field in not in the schema
Args :
field _ name :
Returns : True if the field is present .""" | if field_name in { "@id" , "@type" } :
return True
result = self . schema . has_field ( field_name )
if not result : # todo : how to comply with our error handling policies ?
raise UndefinedFieldError ( "'{}' should be present in the knowledge graph schema." . format ( field_name ) )
return result |
def getValuesForProperty ( self , aPropURIRef ) :
"""generic way to extract some prop value eg
In [ 11 ] : c . getValuesForProperty ( rdflib . RDF . type )
Out [ 11 ] :
[ rdflib . term . URIRef ( u ' http : / / www . w3 . org / 2002/07 / owl # Class ' ) ,
rdflib . term . URIRef ( u ' http : / / www . w3 . o... | if not type ( aPropURIRef ) == rdflib . URIRef :
aPropURIRef = rdflib . URIRef ( aPropURIRef )
return list ( self . rdflib_graph . objects ( None , aPropURIRef ) ) |
def lstm_unroll ( num_lstm_layer , seq_len , num_hidden , num_label , loss_type = None ) :
"""Creates an unrolled LSTM symbol for inference if loss _ type is not specified , and for training
if loss _ type is specified . loss _ type must be one of ' ctc ' or ' warpctc '
Parameters
num _ lstm _ layer : int
s... | # Create the base ( shared between training and inference ) and add loss to the end
pred = _lstm_unroll_base ( num_lstm_layer , seq_len , num_hidden )
if loss_type : # Training mode , add loss
return _add_ctc_loss ( pred , seq_len , num_label , loss_type )
else : # Inference mode , add softmax
return mx . sym .... |
def K ( self , X , X2 = None ) : # model : - a d ^ 2y / dx ^ 2 + b dy / dt + c * y = U
# kernel Kyy rbf spatiol temporal
# vyt Y temporal variance vyx Y spatiol variance lyt Y temporal lengthscale lyx Y spatiol lengthscale
# kernel Kuu doper ( doper ( Kyy ) )
# a b c lyt lyx vyx * vyt
"""Compute the covariance matr... | X , slices = X [ : , : - 1 ] , index_to_slices ( X [ : , - 1 ] )
if X2 is None :
X2 , slices2 = X , slices
K = np . zeros ( ( X . shape [ 0 ] , X . shape [ 0 ] ) )
else :
X2 , slices2 = X2 [ : , : - 1 ] , index_to_slices ( X2 [ : , - 1 ] )
K = np . zeros ( ( X . shape [ 0 ] , X2 . shape [ 0 ] ) )
tdist ... |
def add_worksheet ( self , title , rows , cols ) :
"""Adds a new worksheet to a spreadsheet .
: param title : A title of a new worksheet .
: type title : str
: param rows : Number of rows .
: type rows : int
: param cols : Number of columns .
: type cols : int
: returns : a newly created : class : ` w... | body = { 'requests' : [ { 'addSheet' : { 'properties' : { 'title' : title , 'sheetType' : 'GRID' , 'gridProperties' : { 'rowCount' : rows , 'columnCount' : cols } } } } ] }
data = self . batch_update ( body )
properties = data [ 'replies' ] [ 0 ] [ 'addSheet' ] [ 'properties' ]
worksheet = Worksheet ( self , properties... |
def createDocument_ ( self , initDict = None ) :
"create and returns a completely empty document or one populated with initDict" | if initDict is None :
initV = { }
else :
initV = initDict
return self . documentClass ( self , initV ) |
def begin ( self , close = True , expire_on_commit = False , session = None , commit = False , ** options ) :
"""Provide a transactional scope around a series of operations .
By default , ` ` expire _ on _ commit ` ` is set to False so that instances
can be used outside the session .""" | if not session :
commit = True
session = self . session ( expire_on_commit = expire_on_commit , ** options )
else :
close = False
try :
yield session
if commit :
session . commit ( )
except Exception :
session . rollback ( )
raise
finally :
if close :
session . close ( ) |
def reset_namespace ( self , warning = False , message = False ) :
"""Reset the namespace by removing all names defined by the user .""" | reset_str = _ ( "Remove all variables" )
warn_str = _ ( "All user-defined variables will be removed. " "Are you sure you want to proceed?" )
kernel_env = self . kernel_manager . _kernel_spec . env
if warning :
box = MessageCheckBox ( icon = QMessageBox . Warning , parent = self )
box . setWindowTitle ( reset_st... |
def ffill ( self , dim , limit = None ) :
'''Fill NaN values by propogating values forward
* Requires bottleneck . *
Parameters
dim : str
Specifies the dimension along which to propagate values when
filling .
limit : int , default None
The maximum number of consecutive NaN values to forward fill . In ... | from . missing import ffill , _apply_over_vars_with_dim
new = _apply_over_vars_with_dim ( ffill , self , dim = dim , limit = limit )
return new |
def compute_dprime ( n_Hit = None , n_Miss = None , n_FA = None , n_CR = None ) :
"""Computes the d ' , beta , aprime , b ' ' d and c parameters based on the signal detection theory ( SDT ) . * * Feel free to help me expand the documentation of this function with details and interpretation guides . * *
Parameters... | # Ratios
hit_rate = n_Hit / ( n_Hit + n_Miss )
fa_rate = n_FA / ( n_FA + n_CR )
# Adjusted ratios
hit_rate_adjusted = ( n_Hit + 0.5 ) / ( ( n_Hit + 0.5 ) + n_Miss + 1 )
fa_rate_adjusted = ( n_FA + 0.5 ) / ( ( n_FA + 0.5 ) + n_CR + 1 )
# dprime
dprime = scipy . stats . norm . ppf ( hit_rate_adjusted ) - scipy . stats . ... |
def on_rabbitmq_close ( self , reply_code , reply_text ) :
"""Called when RabbitMQ has been connected to .
: param int reply _ code : The code for the disconnect
: param str reply _ text : The disconnect reason""" | global rabbitmq_connection
LOGGER . warning ( 'RabbitMQ has disconnected (%s): %s' , reply_code , reply_text )
rabbitmq_connection = None
self . _set_rabbitmq_channel ( None )
self . _connect_to_rabbitmq ( ) |
def write_source_model ( dest , sources_or_groups , name = None , investigation_time = None ) :
"""Writes a source model to XML .
: param dest :
Destination path
: param sources _ or _ groups :
Source model in different formats
: param name :
Name of the source model ( if missing , extracted from the fi... | if isinstance ( sources_or_groups , nrml . SourceModel ) :
with open ( dest , 'wb' ) as f :
nrml . write ( [ obj_to_node ( sources_or_groups ) ] , f , '%s' )
return
if isinstance ( sources_or_groups [ 0 ] , sourceconverter . SourceGroup ) :
groups = sources_or_groups
else : # passed a list of source... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.