signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def auto_instantiate ( * classes ) :
"""Creates a decorator that will instantiate objects based on function
parameter annotations .
The decorator will check every argument passed into ` ` f ` ` . If ` ` f ` ` has an
annotation for the specified parameter and the annotation is found in
` ` classes ` ` , the ... | def decorator ( f ) : # collect our argspec
sig = signature ( f )
@ wraps ( f )
def _ ( * args , ** kwargs ) :
bvals = sig . bind ( * args , ** kwargs )
# replace with instance if desired
for varname , val in bvals . arguments . items ( ) :
anno = sig . parameters [ varna... |
def get_element_by_id ( self , ident ) :
"""Get a TocElement element identified by index number from the
container .""" | for group in list ( self . toc . keys ( ) ) :
for name in list ( self . toc [ group ] . keys ( ) ) :
if self . toc [ group ] [ name ] . ident == ident :
return self . toc [ group ] [ name ]
return None |
def plot_pseudosections ( self , column , filename = None , return_fig = False ) :
"""Create a multi - plot with one pseudosection for each frequency .
Parameters
column : string
which column to plot
filename : None | string
output filename . If set to None , do not write to file . Default :
None
retu... | assert column in self . data . columns
g = self . data . groupby ( 'frequency' )
fig , axes = plt . subplots ( 4 , 2 , figsize = ( 15 / 2.54 , 20 / 2.54 ) , sharex = True , sharey = True )
for ax , ( key , item ) in zip ( axes . flat , g ) :
fig , ax , cb = PS . plot_pseudosection_type2 ( item , ax = ax , column = ... |
def _plot_inversion ( f , rhs , r , k , imin , spacing , shift , cvar ) :
r"""QC the resulting filter .""" | # Check matplotlib ( soft dependency )
if not plt :
print ( plt_msg )
return
plt . figure ( "Inversion result " + f . name , figsize = ( 9.5 , 4 ) )
plt . subplots_adjust ( wspace = .3 , bottom = 0.2 )
plt . clf ( )
tk = np . logspace ( np . log10 ( k . min ( ) ) , np . log10 ( k . max ( ) ) , r . size )
plt . ... |
def set_branch ( self , commit , branch_name ) :
"""Sets a commit and its ancestors as a branch .
Params :
* commit : A tuple , string , or Commit object representing the commit .
* branch _ name : The name for the branch to set .""" | res = proto . SetBranchRequest ( commit = commit_from ( commit ) , branch = branch_name )
self . stub . SetBranch ( res , metadata = self . metadata ) |
def full_self_attention ( x , self_attention_bias , hparams , q_padding = "LEFT" , kv_padding = "LEFT" ) :
"""Full self - attention layer .""" | x , x_shape , is_4d = maybe_reshape_4d_to_3d ( x )
if self_attention_bias is not None :
self_attention_bias = get_self_attention_bias ( x )
with tf . variable_scope ( "self_att" ) :
y = common_attention . multihead_attention ( x , None , self_attention_bias , hparams . attention_key_channels or hparams . hidden... |
def supports_coordinate_type ( self , coordinate_type ) :
"""Tests if the given coordinate type is supported .
arg : coordinate _ type ( osid . type . Type ) : a coordinate Type
return : ( boolean ) - ` ` true ` ` if the type is supported , ` ` false ` `
otherwise
raise : IllegalState - syntax is not a ` ` ... | # Implemented from template for osid . Metadata . supports _ coordinate _ type
if self . _kwargs [ 'syntax' ] not in [ '``COORDINATE``' ] :
raise errors . IllegalState ( )
return coordinate_type in self . get_coordinate_types |
def DialectAddToEnv ( env , dialect , suffixes , ppsuffixes , support_module = 0 ) :
"""Add dialect specific construction variables .""" | ComputeFortranSuffixes ( suffixes , ppsuffixes )
fscan = SCons . Scanner . Fortran . FortranScan ( "%sPATH" % dialect )
for suffix in suffixes + ppsuffixes :
SCons . Tool . SourceFileScanner . add_scanner ( suffix , fscan )
env . AppendUnique ( FORTRANSUFFIXES = suffixes + ppsuffixes )
compaction , compppaction , s... |
def _handle_raw_packet ( self , raw_packet ) :
"""Parse incoming packet .""" | if raw_packet [ 1 : 2 ] == b'\x1f' :
self . _reset_timeout ( )
year = raw_packet [ 2 ]
month = raw_packet [ 3 ]
day = raw_packet [ 4 ]
hour = raw_packet [ 5 ]
minute = raw_packet [ 6 ]
sec = raw_packet [ 7 ]
week = raw_packet [ 8 ]
self . logger . debug ( 'received date: Year: %s, Mo... |
def encompasses ( self , span ) :
"""Returns true if the given span fits inside this one""" | if isinstance ( span , list ) :
return [ sp for sp in span if self . _encompasses ( sp ) ]
return self . _encompasses ( span ) |
def read ( self , n ) :
"""Read n bytes .""" | self . bitcount = self . bits = 0
return self . input . read ( n ) |
def format_item ( self , item ) :
"Construct result dictionary for the match item ." | result = { 'id' : self . get_item_id ( item ) , 'value' : self . get_item_value ( item ) , 'label' : self . get_item_label ( item ) , }
for key in settings . SELECTABLE_ESCAPED_KEYS :
if key in result :
result [ key ] = conditional_escape ( result [ key ] )
return result |
def check_delta ( fun , x , dxs , period = None ) :
"""Check the difference between two function values using the analytical gradient
Arguments :
| ` ` fun ` ` - - The function to be tested , more info below .
| ` ` x ` ` - - The argument vector .
| ` ` dxs ` ` - - A matrix where each row is a vector of sma... | dn1s = [ ]
dn2s = [ ]
dnds = [ ]
for dx in dxs :
f0 , grad0 = fun ( x , do_gradient = True )
f1 , grad1 = fun ( x + dx , do_gradient = True )
grad = 0.5 * ( grad0 + grad1 )
d1 = f1 - f0
if period is not None :
d1 -= np . floor ( d1 / period + 0.5 ) * period
if hasattr ( d1 , '__iter__' )... |
def render_honeypot_field ( field_name = None ) :
"""Renders honeypot field named field _ name ( defaults to HONEYPOT _ FIELD _ NAME ) .""" | if not field_name :
field_name = settings . HONEYPOT_FIELD_NAME
value = getattr ( settings , 'HONEYPOT_VALUE' , '' )
if callable ( value ) :
value = value ( )
return { 'fieldname' : field_name , 'value' : value } |
def TerrainAttribute ( dem , attrib , zscale = 1.0 ) :
"""Calculates terrain attributes . A variety of methods are available .
Args :
dem ( rdarray ) : An elevation model
attrib ( str ) : Terrain attribute to calculate . ( See below . )
zscale ( float ) : How much to scale the z - axis by prior to calculati... | if type ( dem ) is not rdarray :
raise Exception ( "A richdem.rdarray or numpy.ndarray is required!" )
terrain_attribs = { # " spi " : _ richdem . TA _ SPI ,
# " cti " : _ richdem . TA _ CTI ,
"slope_riserun" : _richdem . TA_slope_riserun , "slope_percentage" : _richdem . TA_slope_percentage , "slope_degrees" : _ri... |
def _table_cell ( args , cell_body ) :
"""Implements the BigQuery table magic subcommand used to operate on tables
The supported syntax is :
% % bq tables < command > < args >
Commands :
{ list , create , delete , describe , view }
Args :
args : the optional arguments following ' % % bq tables command '... | if args [ 'command' ] == 'list' :
filter_ = args [ 'filter' ] if args [ 'filter' ] else '*'
if args [ 'dataset' ] :
if args [ 'project' ] is None :
datasets = [ bigquery . Dataset ( args [ 'dataset' ] ) ]
else :
context = google . datalab . Context ( args [ 'project' ] , ... |
def render_serialization ( self , context , result ) :
"""Render serialized responses .""" | resp = context . response
serial = context . serialize
match = context . request . accept . best_match ( serial . types , default_match = self . default )
result = serial [ match ] ( result )
if isinstance ( result , str ) :
result = result . decode ( 'utf-8' )
resp . charset = 'utf-8'
resp . content_type = match
r... |
def get_resource_tag_map ( self , r_type , ids ) :
"""Returns a mapping of { resource _ id : { tagkey : tagvalue } }""" | manager = self . manager . get_resource_manager ( r_type )
r_id = manager . resource_type . id
# TODO only fetch resource with the given ids .
return { r [ r_id ] : { t [ 'Key' ] : t [ 'Value' ] for t in r . get ( 'Tags' , [ ] ) } for r in manager . resources ( ) if r [ r_id ] in ids } |
def write ( self , data ) :
"""Send * n * bytes to socket .
Args :
data ( bytes ) : The data to send .
Raises :
EOFError : If the socket was closed .""" | while data :
try :
n = self . _socket . send ( data )
except socket . error :
n = None
if not n :
raise EOFError ( 'Socket closed' )
data = data [ n : ] |
def drop_duplicates ( self , keep = 'first' , inplace = False ) :
"""Return Series with duplicate values removed .
Parameters
keep : { ' first ' , ' last ' , ` ` False ` ` } , default ' first '
- ' first ' : Drop duplicates except for the first occurrence .
- ' last ' : Drop duplicates except for the last o... | return super ( ) . drop_duplicates ( keep = keep , inplace = inplace ) |
def _remove_app_models ( all_apps , models_to_remove ) :
"""Remove the model specs in models _ to _ remove from the models specs in the
apps in all _ apps . If an app has no models left , don ' t include it in the
output .
This has the side - effect that the app view e . g . / admin / app / may not be
acces... | filtered_apps = [ ]
for app in all_apps :
models = [ x for x in app [ 'models' ] if x not in models_to_remove ]
if models :
app [ 'models' ] = models
filtered_apps . append ( app )
return filtered_apps |
def recover_cfg ( self , start = None , end = None , symbols = None , callback = None , arch_mode = None ) :
"""Recover CFG .
Args :
start ( int ) : Start address .
end ( int ) : End address .
symbols ( dict ) : Symbol table .
callback ( function ) : A callback function which is called after each successf... | # Set architecture in case it wasn ' t already set .
if arch_mode is None :
arch_mode = self . binary . architecture_mode
# Reload modules .
self . _load ( arch_mode = arch_mode )
# Check start address .
start = start if start else self . binary . entry_point
cfg , _ = self . _recover_cfg ( start = start , end = en... |
def path_for ( self , * args ) :
"""Path containing _ root _ path""" | if args and args [ 0 ] . startswith ( os . path . sep ) :
return os . path . join ( * args )
return os . path . join ( self . _root_path or os . getcwd ( ) , * args ) |
def from_sql ( cls , conn , sql_statement , params = None , type_inference_rows = 100 , dbapi_module = None , column_type_hints = None , cursor_arraysize = 128 ) :
"""Convert the result of a SQL database query to an SFrame .
Parameters
conn : dbapi2 . Connection
A DBAPI2 connection object . Any connection obj... | # Mapping types is always the trickiest part about reading from a
# database , so the main complexity of this function concerns types .
# Much of the heavy - lifting of this is done by the DBAPI2 module , which
# holds the burden of the actual mapping from the database - specific
# type to a suitable Python type . The ... |
def beacon ( config ) :
'''Return status for requested information''' | log . debug ( config )
ctime = datetime . datetime . utcnow ( ) . isoformat ( )
if not config :
config = [ { 'loadavg' : [ 'all' ] , 'cpustats' : [ 'all' ] , 'meminfo' : [ 'all' ] , 'vmstats' : [ 'all' ] , 'time' : [ 'all' ] , } ]
if not isinstance ( config , list ) : # To support the old dictionary config format
... |
def _ConvertDictToObject ( self , json_dict ) :
"""Converts a JSON dict into a path specification object .
The dictionary of the JSON serialized objects consists of :
' _ _ type _ _ ' : ' PathSpec '
' type _ indicator ' : ' OS '
' parent ' : { . . . }
Here ' _ _ type _ _ ' indicates the object base type i... | # Use _ _ type _ _ to indicate the object class type .
class_type = json_dict . get ( '__type__' , None )
if class_type not in self . _CLASS_TYPES :
raise TypeError ( 'Missing path specification object type.' )
# Remove the class type from the JSON dict since we cannot pass it .
del json_dict [ '__type__' ]
type_in... |
def toggle ( self , discord_token , discord_client_id ) :
"""Toggles Modis on or off""" | if self . state == 'off' :
self . start ( discord_token , discord_client_id )
elif self . state == 'on' :
self . stop ( ) |
def fetch ( dataset , annot , cat = ( 0 , 0 , 0 , 0 ) , evt_type = None , stage = None , cycle = None , chan_full = None , epoch = None , epoch_dur = 30 , epoch_overlap = 0 , epoch_step = None , reject_epoch = False , reject_artf = False , min_dur = 0 , buffer = 0 ) :
"""Create instance of Segments for analysis , c... | bundles = get_times ( annot , evt_type = evt_type , stage = stage , cycle = cycle , chan = chan_full , exclude = reject_epoch , buffer = buffer )
# Remove artefacts
if reject_artf and bundles :
for bund in bundles :
bund [ 'times' ] = remove_artf_evts ( bund [ 'times' ] , annot , bund [ 'chan' ] , min_dur =... |
def get_template_loader_for_path ( path , use_cache = True ) :
'''Convenience method that calls get _ template _ loader _ for _ path ( ) on the DMP
template engine instance .''' | dmp = apps . get_app_config ( 'django_mako_plus' )
return dmp . engine . get_template_loader_for_path ( path , use_cache ) |
def create_leads_list ( self , name , team_id = None ) :
"""Create a leads list .
: param name : Name of the list to create . Must be defined .
: param team _ id : The id of the list to share this list with .
: return : The created leads list as a dict .""" | params = self . base_params
payload = { 'name' : name }
if team_id :
payload [ 'team_id' ] = team_id
endpoint = self . base_endpoint . format ( 'leads_lists' )
return self . _query_hunter ( endpoint , params , 'post' , payload ) |
def regenerate_prefixes ( self , * args ) :
"""Regenerate the cache of command prefixes based on nick etc .""" | nick = self . controller . client . user . nick
self . prefixes = set ( [ nick + ": " , nick + ", " , nick + " - " , ] )
# Include lower - case versions as well , but not caps
self . prefixes . update ( [ p . lower ( ) for p in self . prefixes ] )
if self . sigil :
self . prefixes . add ( self . sigil ) |
def _get_log_model_class ( self ) :
"""Cache for fetching the actual log model object once django is loaded .
Otherwise , import conflict occur : WorkflowEnabled imports < log _ model >
which tries to import all models to retrieve the proper model class .""" | if self . log_model_class is not None :
return self . log_model_class
app_label , model_label = self . log_model . rsplit ( '.' , 1 )
self . log_model_class = apps . get_model ( app_label , model_label )
return self . log_model_class |
def order_derived_variables ( regime ) :
"""Finds ordering of derived _ variables .
@ param regime : Dynamics Regime containing derived variables .
@ type regime : lems . model . dynamics . regime
@ return : Returns ordered list of derived variables .
@ rtype : list ( string )
@ raise SimBuildError : Rais... | ordering = [ ]
dvs = [ ]
dvsnoexp = [ ]
maxcount = 5
for dv in regime . derived_variables :
if dv . expression_tree == None :
dvsnoexp . append ( dv . name )
else :
dvs . append ( dv . name )
for dv in regime . conditional_derived_variables :
if len ( dv . cases ) == 0 :
dvsnoexp . a... |
def rename_get_variable ( mapping ) :
"""Args :
mapping ( dict ) : an old - > new mapping for variable basename . e . g . { ' kernel ' : ' W ' }
Returns :
A context where the variables are renamed .""" | def custom_getter ( getter , name , * args , ** kwargs ) :
splits = name . split ( '/' )
basename = splits [ - 1 ]
if basename in mapping :
basename = mapping [ basename ]
splits [ - 1 ] = basename
name = '/' . join ( splits )
return getter ( name , * args , ** kwargs )
return cu... |
def content ( ) :
"""Helper method that returns just the content .
This method was added so that the text could be reused in the
other contexts .
. . versionadded : : 3.2.2
: returns : A message object without brand element .
: rtype : safe . messaging . message . Message""" | message = m . Message ( )
paragraph = m . Paragraph ( m . Image ( 'file:///%s/img/screenshots/' 'batch-calculator-screenshot.png' % resources_path ( ) ) , style_class = 'text-center' )
message . add ( paragraph )
message . add ( m . Paragraph ( tr ( 'With this tool you can set up numerous scenarios and run them all in ... |
def data ( self , table_name , metadata , persist_as = None , how = 'the_geom' ) :
"""Get an augmented CARTO dataset with ` Data Observatory
< https : / / carto . com / data - observatory > ` _ _ measures . Use
` CartoContext . data _ discovery
< # context . CartoContext . data _ discovery > ` _ _ to search f... | # if how ! = ' the _ geom ' :
# raise NotImplementedError ( ' Data gathering currently only works if '
# ' a geometry is present ' )
if isinstance ( metadata , pd . DataFrame ) :
_meta = metadata . copy ( ) . reset_index ( )
elif isinstance ( metadata , collections . Iterable ) :
query = utils . minify_sql ( ( ... |
def run_cmd_unit ( self , sentry_unit , cmd ) :
"""Run a command on a unit , return the output and exit code .""" | output , code = sentry_unit . run ( cmd )
if code == 0 :
self . log . debug ( '{} `{}` command returned {} ' '(OK)' . format ( sentry_unit . info [ 'unit_name' ] , cmd , code ) )
else :
msg = ( '{} `{}` command returned {} ' '{}' . format ( sentry_unit . info [ 'unit_name' ] , cmd , code , output ) )
amulet... |
def get_type ( type_ ) :
"""Gets the declaration for the corresponding custom type .
@ raise KeyError : Unknown type .
@ see : L { add _ type } and L { remove _ type }""" | if isinstance ( type_ , list ) :
type_ = tuple ( type_ )
for k , v in TYPE_MAP . iteritems ( ) :
if k == type_ :
return v
raise KeyError ( "Unknown type %r" % ( type_ , ) ) |
def W_min_HS_ratio ( self ) :
"""Calculate the minimum flocculator channel width , given the minimum
ratio between expansion height ( H ) and baffle spacing ( S ) .
: returns : Minimum channel width given H _ e / S
: rtype : float * centimeter""" | return ( ( self . HS_RATIO_MIN * self . Q / self . downstream_H ) * ( self . BAFFLE_K / ( 2 * self . downstream_H * pc . viscosity_kinematic ( self . temp ) * self . vel_grad_avg ** 2 ) ) ** ( 1 / 3 ) ) . to ( u . cm ) |
def help_center_user_segment_topics ( self , user_segment_id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / help _ center / user _ segments # list - topics - using - a - user - segment" | api_path = "/api/v2/help_center/user_segments/{user_segment_id}/topics.json"
api_path = api_path . format ( user_segment_id = user_segment_id )
return self . call ( api_path , ** kwargs ) |
def build_depenses_homogenisees ( temporary_store = None , year = None ) :
"""Build menage consumption by categorie fiscale dataframe""" | assert temporary_store is not None
assert year is not None
bdf_survey_collection = SurveyCollection . load ( collection = 'budget_des_familles' , config_files_directory = config_files_directory )
survey = bdf_survey_collection . get_survey ( 'budget_des_familles_{}' . format ( year ) )
# Homogénéisation des bases de ... |
def get_node ( self ) :
"""return etree Element representing this slide""" | # already added title , text frames
# add animation chunks
if self . animations :
anim_par = el ( "anim:par" , attrib = { "presentation:node-type" : "timing-root" } )
self . _page . append ( anim_par )
anim_seq = sub_el ( anim_par , "anim:seq" , attrib = { "presentation:node-type" : "main-sequence" } )
... |
def render ( self , context , instance , placeholder ) :
"""Update the context with plugin ' s data""" | entries = Entry . published . search ( instance . query )
if instance . number_of_entries :
entries = entries [ : instance . number_of_entries ]
context = super ( CMSQueryEntriesPlugin , self ) . render ( context , instance , placeholder )
context [ 'entries' ] = entries
return context |
def list_service ( ctx , name ) :
"""Retrieve accounts pertaining to named service .""" | swag = create_swag_from_ctx ( ctx )
accounts = swag . get_service_enabled ( name )
_table = [ [ result [ 'name' ] , result . get ( 'id' ) ] for result in accounts ]
click . echo ( tabulate ( _table , headers = [ "Account Name" , "Account Number" ] ) ) |
def split_six ( series = None ) :
"""Given a Pandas Series , get a domain of values from zero to the 90 % quantile
rounded to the nearest order - of - magnitude integer . For example , 2100 is
rounded to 2000 , 2790 to 3000.
Parameters
series : Pandas series , default None
Returns
list""" | if pd is None :
raise ImportError ( 'The Pandas package is required' ' for this functionality' )
if np is None :
raise ImportError ( 'The NumPy package is required' ' for this functionality' )
def base ( x ) :
if x > 0 :
base = pow ( 10 , math . floor ( math . log10 ( x ) ) )
return round ( ... |
def network ( ip , netmask , gateway ) :
'''Ensure the DRAC network settings are consistent''' | ret = { 'name' : ip , 'result' : True , 'changes' : { } , 'comment' : '' }
current_network = __salt__ [ 'drac.network_info' ] ( )
new_network = { }
if ip != current_network [ 'IPv4 settings' ] [ 'IP Address' ] :
ret [ 'changes' ] . update ( { 'IP Address' : { 'Old' : current_network [ 'IPv4 settings' ] [ 'IP Addres... |
def bullet_base_pose_to_world_pose ( self , pose_in_base ) :
"""Convert a pose in the base frame to a pose in the world frame .
Args :
pose _ in _ base : a ( pos , orn ) tuple .
Returns :
pose _ in world : a ( pos , orn ) tuple .""" | pose_in_base = T . pose2mat ( pose_in_base )
base_pos_in_world = np . array ( p . getBasePositionAndOrientation ( self . ik_robot ) [ 0 ] )
base_orn_in_world = np . array ( p . getBasePositionAndOrientation ( self . ik_robot ) [ 1 ] )
base_pose_in_world = T . pose2mat ( ( base_pos_in_world , base_orn_in_world ) )
pose_... |
def assign_address ( self , ip_address , instance_id ) :
'''a method to assign ( or reassign ) an elastic ip to an instance on AWS
: param ip _ address : string with elastic ipv4 address on ec2
: param instance _ id : string with aws id for running instance
: return : dictioanry with response metadata fields'... | title = '%s.assign_address' % self . __class__ . __name__
# validate inputs
input_fields = { 'ip_address' : ip_address , 'instance_id' : instance_id }
for key , value in input_fields . items ( ) :
object_title = '%s(%s=%s)' % ( title , key , str ( value ) )
self . fields . validate ( value , '.%s' % key , objec... |
def _check_enum ( parameter_name , value , parameter_config ) :
"""Checks if an enum value is valid .
This is called by the transform _ parameter _ value function and shouldn ' t be
called directly .
This verifies that the value of an enum parameter is valid .
Args :
parameter _ name : A string containing... | enum_values = [ enum [ 'backendValue' ] for enum in parameter_config [ 'enum' ] . values ( ) if 'backendValue' in enum ]
if value not in enum_values :
raise errors . EnumRejectionError ( parameter_name , value , enum_values ) |
def _process_model_dict ( self , d ) :
"""Remove redundant items from a model ' s configuration dict .
Parameters
d : dict
Modified in place .
Returns
dict
Modified ` d ` .""" | del d [ 'model_type' ]
del d [ 'sample_size' ]
del d [ 'probability_mode' ]
del d [ 'choice_mode' ]
del d [ 'choosers_fit_filters' ]
del d [ 'choosers_predict_filters' ]
del d [ 'alts_fit_filters' ]
del d [ 'alts_predict_filters' ]
del d [ 'interaction_predict_filters' ]
del d [ 'estimation_sample_size' ]
del d [ 'pred... |
def make_sgf ( move_history , result_string , ruleset = "Chinese" , komi = 7.5 , white_name = PROGRAM_IDENTIFIER , black_name = PROGRAM_IDENTIFIER , comments = [ ] ) :
"""Turn a game into SGF .
Doesn ' t handle handicap games or positions with incomplete history .
Args :
move _ history : iterable of PlayerMov... | boardsize = go . N
game_moves = '' . join ( translate_sgf_move ( * z ) for z in itertools . zip_longest ( move_history , comments ) )
result = result_string
return SGF_TEMPLATE . format ( ** locals ( ) ) |
def swd_write ( self , output , value , nbits ) :
"""Writes bytes over SWD ( Serial Wire Debug ) .
Args :
self ( JLink ) : the ` ` JLink ` ` instance
output ( int ) : the output buffer offset to write to
value ( int ) : the value to write to the output buffer
nbits ( int ) : the number of bits needed to r... | pDir = binpacker . pack ( output , nbits )
pIn = binpacker . pack ( value , nbits )
bitpos = self . _dll . JLINK_SWD_StoreRaw ( pDir , pIn , nbits )
if bitpos < 0 :
raise errors . JLinkException ( bitpos )
return bitpos |
def parse_readme ( ) :
"""Parse contents of the README .""" | # Get the long description from the relevant file
readme_file = str ( Path ( __file__ ) . parent / 'README.rst' )
with codecs . open ( readme_file , encoding = 'utf-8' ) as handle :
long_description = handle . read ( )
return long_description |
def set_sync_limit ( self , limit : int ) -> Optional [ int ] :
"""Sets the events limit per room for sync and return previous limit""" | try :
prev_limit = json . loads ( self . sync_filter ) [ 'room' ] [ 'timeline' ] [ 'limit' ]
except ( json . JSONDecodeError , KeyError ) :
prev_limit = None
self . sync_filter = json . dumps ( { 'room' : { 'timeline' : { 'limit' : limit } } } )
return prev_limit |
def convert_file ( filename , renderer ) :
"""Parse a Markdown file and dump the output to stdout .""" | try :
with open ( filename , 'r' ) as fin :
rendered = mistletoe . markdown ( fin , renderer )
print ( rendered , end = '' )
except OSError :
sys . exit ( 'Cannot open file "{}".' . format ( filename ) ) |
def find_files ( self ) :
"""Find versioned files in self . location""" | all_files = self . _invoke ( 'locate' , '-I' , '.' ) . splitlines ( )
# now we have a list of all files in self . location relative to
# self . find _ root ( )
# Remove the parent dirs from them .
from_root = os . path . relpath ( self . location , self . find_root ( ) )
loc_rel_paths = [ os . path . relpath ( path , f... |
def get_history ( self ) :
"""Get history of applied upgrades .""" | self . load_history ( )
return map ( lambda x : ( x , self . history [ x ] ) , self . ordered_history ) |
def acquire ( lock , blocking = True ) :
"""Acquire a lock , possibly in a non - blocking fashion .
Includes backwards compatibility hacks for old versions of Python , dask
and dask - distributed .""" | if blocking : # no arguments needed
return lock . acquire ( )
elif DistributedLock is not None and isinstance ( lock , DistributedLock ) : # distributed . Lock doesn ' t support the blocking argument yet :
# https : / / github . com / dask / distributed / pull / 2412
return lock . acquire ( timeout = 0 )
else :... |
def write_adj_list ( self , path : str ) -> None :
"""Write the network as an adjacency list to a file .
: param path : File path to write the adjacency list .""" | adj_list = self . get_adjlist ( )
with open ( path , mode = "w" ) as file :
for i , line in enumerate ( adj_list ) :
print ( i , * line , file = file ) |
def crypto_hash_sha256 ( message ) :
"""Hashes and returns the message ` ` message ` ` .
: param message : bytes
: rtype : bytes""" | digest = ffi . new ( "unsigned char[]" , crypto_hash_sha256_BYTES )
rc = lib . crypto_hash_sha256 ( digest , message , len ( message ) )
ensure ( rc == 0 , 'Unexpected library error' , raising = exc . RuntimeError )
return ffi . buffer ( digest , crypto_hash_sha256_BYTES ) [ : ] |
def tags_with_text ( xml , tags = None ) :
"""Return a list of tags that contain text retrieved recursively from an
XML tree .""" | if tags is None :
tags = [ ]
for element in xml :
if element . text is not None :
tags . append ( element )
elif len ( element ) > 0 : # pylint : disable = len - as - condition
tags_with_text ( element , tags )
else :
message = 'Unknown XML structure: {}' . format ( element )
... |
def query_rates ( self , pairs = [ ] ) :
'''Perform a request against truefx data''' | # If no pairs , TrueFx will use the ones given the last time
payload = { 'id' : self . _session }
if pairs :
payload [ 'c' ] = _clean_pairs ( pairs )
response = requests . get ( self . _api_url , params = payload )
mapped_data = _fx_mapping ( response . content . split ( '\n' ) [ : - 2 ] )
return Series ( mapped_da... |
def _subtoken_ids_to_tokens ( self , subtokens ) :
"""Converts a list of subtoken ids to a list of tokens .
Args :
subtokens : a list of integers in the range [ 0 , vocab _ size )
Returns :
a list of strings .""" | concatenated = "" . join ( [ self . _subtoken_id_to_subtoken_string ( s ) for s in subtokens ] )
split = concatenated . split ( "_" )
ret = [ ]
for t in split :
if t :
unescaped = _unescape_token ( t + "_" )
if unescaped :
ret . append ( unescaped )
return ret |
def list_configs ( ) :
'''List all available configs
CLI example :
. . code - block : : bash
salt ' * ' snapper . list _ configs''' | try :
configs = snapper . ListConfigs ( )
return dict ( ( config [ 0 ] , config [ 2 ] ) for config in configs )
except dbus . DBusException as exc :
raise CommandExecutionError ( 'Error encountered while listing configurations: {0}' . format ( _dbus_exception_to_reason ( exc , locals ( ) ) ) ) |
def find_seq_homologues ( self , return_raw = False ) :
"""Uses NCBI BLAST to look for structures deposited in the PDB database
that share _ _ sequence _ _ homology with the target protein / chain .
Bridges to Bio . BLAST . NCBIWWW .""" | # Get sequence from structure / chain
# We could use Bio . PDB . Polypeptide ?
from Bio . SCOP . Raf import to_one_letter_code
s = self
seq_iter = s . get_residues ( )
seq_str = ''
for aa in seq_iter :
if aa . resname in to_one_letter_code :
seq_str += to_one_letter_code [ aa . resname ]
# Use BLAST to find... |
def request_raw_reverse ( self , req , msg ) :
"""A raw request handler to demonstrate the calling convention if
@ request decoraters are not used . Reverses the message arguments .""" | # msg is a katcp . Message . request object
reversed_args = msg . arguments [ : : - 1 ]
# req . make _ reply ( ) makes a katcp . Message . reply using the correct request
# name and message ID
return req . make_reply ( * reversed_args ) |
def get_scanner_param_default ( self , param ) :
"""Returns default value of a scanner parameter .""" | assert isinstance ( param , str )
entry = self . scanner_params . get ( param )
if not entry :
return None
return entry . get ( 'default' ) |
def to_text ( self ) :
"""Render a Text MessageElement as plain text
Args :
None
Returns :
Str the plain text representation of the Text MessageElement
Raises :
Errors are propagated""" | if self . items is None :
return
else :
text = ''
for i , item in enumerate ( self . items ) :
text += ' %s. %s\n' % ( i + 1 , item . to_text ( ) )
return text |
def macs ( nasv , T ) :
'''Returns
MACS
[ mb ] at T [ K ] from Na * < sigma v > .''' | Na = avogadro_constant
k = boltzmann_constant
vtherm = ( 2. * k * T / mass_H_atom ) ** 0.5
s = old_div ( nasv , ( vtherm * Na ) )
macs = s * 1.e27
return macs |
def get_intersection ( self , division ) :
"""Get intersection percentage of intersecting divisions .""" | try :
return IntersectRelationship . objects . get ( from_division = self , to_division = division ) . intersection
except ObjectDoesNotExist :
raise Exception ( "No intersecting relationship with that division." ) |
def _check_convergence ( self , F ) :
"""Checks if the solution has converged to within the specified
tolerance .""" | normF = linalg . norm ( F , Inf )
if normF < self . tolerance :
converged = True
else :
converged = False
if self . verbose :
logger . info ( "Difference: %.3f" % ( normF - self . tolerance ) )
return converged |
def space_time_cluster ( catalog , t_thresh , d_thresh ) :
"""Cluster detections in space and time .
Use to separate repeaters from other events . Clusters by distance
first , then removes events in those groups that are at different times .
: type catalog : obspy . core . event . Catalog
: param catalog : ... | initial_spatial_groups = space_cluster ( catalog = catalog , d_thresh = d_thresh , show = False )
# Need initial _ spatial _ groups to be lists at the moment
initial_spatial_lists = [ ]
for group in initial_spatial_groups :
initial_spatial_lists . append ( list ( group ) )
# Check within these groups and throw them... |
def min_interval ( self , name , alpha = _alpha , ** kwargs ) :
"""Calculate minimum interval for parameter .""" | data = self . get ( name , ** kwargs )
return min_interval ( data , alpha ) |
def _safe_reshape ( arr , new_shape ) :
"""If possible , reshape ` arr ` to have shape ` new _ shape ` ,
with a couple of exceptions ( see gh - 13012 ) :
1 ) If ` arr ` is a ExtensionArray or Index , ` arr ` will be
returned as is .
2 ) If ` arr ` is a Series , the ` _ values ` attribute will
be reshaped ... | if isinstance ( arr , ABCSeries ) :
arr = arr . _values
if not isinstance ( arr , ABCExtensionArray ) :
arr = arr . reshape ( new_shape )
return arr |
def img2img_transformer_base_tpu ( ) :
"""Hparams for training img2img _ transformer on tpu .""" | hparams = img2img_transformer_base ( )
update_hparams_for_tpu ( hparams )
hparams . batch_size = 2
hparams . num_heads = 4
# heads are expensive on tpu
hparams . num_decoder_layers = 8
hparams . num_encoder_layers = 4
hparams . shared_embedding_and_softmax_weights = False
return hparams |
def main ( argv = None ) :
"""Entry point for the ` simpl ` command .""" | # ` simpl server `
logging . basicConfig ( level = logging . INFO )
server_func = functools . partial ( server . main , argv = argv )
server_parser = server . attach_parser ( default_subparser ( ) )
server_parser . set_defaults ( _func = server_func )
# the following code shouldn ' t need to change when
# we add a new ... |
def proxies ( self , url ) :
"""Get the transport proxy configuration
: param url : string
: return : Proxy configuration dictionary
: rtype : Dictionary""" | netloc = urllib . parse . urlparse ( url ) . netloc
proxies = { }
if settings . PROXIES and settings . PROXIES . get ( netloc ) :
proxies [ "http" ] = settings . PROXIES [ netloc ]
proxies [ "https" ] = settings . PROXIES [ netloc ]
elif settings . PROXY_URL :
proxies [ "http" ] = settings . PROXY_URL
p... |
def parse_output ( self , s ) :
'''Example output :
AVR Memory Usage
Device : atmega2561
Program : 4168 bytes ( 1.6 % Full )
( . text + . data + . bootloader )
Data : 72 bytes ( 0.9 % Full )
( . data + . bss + . noinit )''' | for x in s . splitlines ( ) :
if '%' in x :
name = x . split ( ':' ) [ 0 ] . strip ( ) . lower ( )
nbytes = x . split ( ':' ) [ 1 ] . split ( 'b' ) [ 0 ] . strip ( )
nbytes = int ( nbytes )
perc = x . split ( '(' ) [ 1 ] . split ( '%' ) [ 0 ] . strip ( )
perc = float ( perc )... |
def quast_table ( self ) :
"""Write some more statistics about the assemblies in a table .""" | headers = OrderedDict ( )
headers [ 'N50' ] = { 'title' : 'N50 ({})' . format ( self . contig_length_suffix ) , 'description' : 'N50 is the contig length such that using longer or equal length contigs produces half (50%) of the bases of the assembly.' , 'min' : 0 , 'suffix' : self . contig_length_suffix , 'scale' : 'Rd... |
def find_widget ( self , name ) :
"""Look for a widget with a specified name .
: param name : The name to search for .
: returns : The widget that matches or None if one couldn ' t be found .""" | result = None
for column in self . _columns :
for widget in column :
if widget . name is not None and name == widget . name :
result = widget
break
return result |
def count_plus ( self , uid ) :
'''Ajax request , that the view count will plus 1.''' | self . set_header ( "Content-Type" , "application/json" )
output = { # ToDo : Test the following codes .
# MPost . _ _ update _ view _ count _ by _ uid ( uid ) else 0,
'status' : 1 if MPost . update_misc ( uid , count = 1 ) else 0 }
# return json . dump ( output , self )
self . write ( json . dumps ( output ) ) |
def update ( self , body = values . unset , attributes = values . unset ) :
"""Update the MessageInstance
: param unicode body : The new message body string .
: param unicode attributes : The new attributes metadata field you can use to store any data you wish .
: returns : Updated MessageInstance
: rtype :... | data = values . of ( { 'Body' : body , 'Attributes' : attributes , } )
payload = self . _version . update ( 'POST' , self . _uri , data = data , )
return MessageInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , channel_sid = self . _solution [ 'channel_sid' ] , sid = self . _solu... |
def validateInterfaceName ( n ) :
"""Verifies that the supplied name is a valid DBus Interface name . Throws
an L { error . MarshallingError } if the format is invalid
@ type n : C { string }
@ param n : A DBus interface name""" | try :
if '.' not in n :
raise Exception ( 'At least two components required' )
if '..' in n :
raise Exception ( '".." not allowed in interface names' )
if len ( n ) > 255 :
raise Exception ( 'Name exceeds maximum length of 255' )
if n [ 0 ] == '.' :
raise Exception ( 'Nam... |
def list ( self , svc_rec = None , hostfilter = None , compromised = False ) :
"""List user accounts
: param svc _ rec : db . t _ services . id
: param hostfilter :
: param compromised : Show only compromised accounts
: return : [ acct . t _ accounts . f _ services _ id , acct . t _ hosts . f _ ipaddr ,
a... | return self . send . accounts_list ( svc_rec , hostfilter , compromised ) |
def as_series ( x ) :
"""Cast as pandas Series .
Cast an iterable to a Pandas Series object . Note that the index
will simply be a positional ` ` arange ` ` and cannot be set in this
function .
Parameters
x : array - like , shape = ( n _ samples , )
The 1d array on which to compute the auto correlation ... | if isinstance ( x , pd . Series ) :
return x
return pd . Series ( column_or_1d ( x ) ) |
def ijk_jlk_to_il ( A , B ) :
"""Faster version of einsum einsum ( ' ijk , jlk - > il ' , A , B )""" | res = np . zeros ( ( A . shape [ 0 ] , B . shape [ 1 ] ) )
[ np . add ( np . dot ( A [ : , : , k ] , B [ : , : , k ] ) , res , out = res ) for k in range ( B . shape [ - 1 ] ) ]
return res |
def showTabMenu ( self , panel , point = None ) :
"""Creates the panel menu for this view widget . If no point is supplied , then the current cursor position will be used .
: param panel | < XViewPanel >
point | < QPoint > | | None""" | if not self . _tabMenu :
self . _tabMenu = XViewTabMenu ( self )
if point is None :
point = QtGui . QCursor . pos ( )
self . _tabMenu . setCurrentPanel ( panel )
self . _tabMenu . exec_ ( point ) |
def at ( * args , ** kwargs ) : # pylint : disable = C0103
'''Add a job to the queue .
The ' timespec ' follows the format documented in the
at ( 1 ) manpage .
CLI Example :
. . code - block : : bash
salt ' * ' at . at < timespec > < cmd > [ tag = < tag > ] [ runas = < user > ]
salt ' * ' at . at 12:05a... | # check args
if len ( args ) < 2 :
return { 'jobs' : [ ] }
# build job
if 'tag' in kwargs :
stdin = '### SALT: {0}\n{1}' . format ( kwargs [ 'tag' ] , ' ' . join ( args [ 1 : ] ) )
else :
stdin = ' ' . join ( args [ 1 : ] )
cmd_kwargs = { 'stdin' : stdin , 'python_shell' : False }
if 'runas' in kwargs :
... |
def register_device ( ctx , device , model , nickname , client_type ) :
"""Registers a device instance under an existing device model .
Device instance fields must start with a letter or number . The device ID
can only contain letters , numbers , and the following symbols : period ( . ) ,
hyphen ( - ) , under... | session , api_url , project_id = build_client_from_context ( ctx )
device_base_url = '/' . join ( [ api_url , 'devices' ] )
device_url = '/' . join ( [ device_base_url , device ] )
payload = { 'id' : device , 'model_id' : model , }
if client_type :
payload [ 'client_type' ] = 'SDK_' + client_type
if nickname :
... |
def step ( self , state , clamping ) :
"""Performs a simulation step from the given state and with respect to the given clamping
Parameters
state : dict
The key - value mapping describing the current state of the logical network
clamping : caspo . core . clamping . Clamping
A clamping over variables in th... | ns = state . copy ( )
for var in state :
if clamping . has_variable ( var ) :
ns [ var ] = int ( clamping . bool ( var ) )
else :
or_value = 0
for clause , _ in self . in_edges_iter ( var ) :
or_value = or_value or clause . bool ( state )
if or_value :
... |
def export_metrics ( self , metrics ) :
"""Exports given metrics to target metric service .""" | metric_protos = [ ]
for metric in metrics :
metric_protos . append ( _get_metric_proto ( metric ) )
self . _rpc_handler . send ( metrics_service_pb2 . ExportMetricsServiceRequest ( metrics = metric_protos ) ) |
def prepare_params ( modeline , fileconfig , options ) :
"""Prepare and merge a params from modelines and configs .
: return dict :""" | params = dict ( skip = False , ignore = [ ] , select = [ ] , linters = [ ] )
if options :
params [ 'ignore' ] = list ( options . ignore )
params [ 'select' ] = list ( options . select )
for config in filter ( None , [ modeline , fileconfig ] ) :
for key in ( 'ignore' , 'select' , 'linters' ) :
param... |
def info ( ctx , objects ) :
"""Obtain all kinds of information""" | if not objects :
t = [ [ "Key" , "Value" ] ]
info = ctx . bitshares . rpc . get_dynamic_global_properties ( )
for key in info :
t . append ( [ key , info [ key ] ] )
print_table ( t )
for obj in objects : # Block
if re . match ( "^[0-9]*$" , obj ) :
block = Block ( obj , lazy = False... |
def add_resource ( self , filename ) :
"""Add a file as a resource .
In Sacred terminology a resource is a file that the experiment needed
to access during a run . In case of a MongoObserver that means making
sure the file is stored in the database ( but avoiding duplicates ) along
its path and md5 sum .
... | filename = os . path . abspath ( filename )
self . _emit_resource_added ( filename ) |
def update_optimiser ( context , * args , ** kwargs ) -> None :
"""Writes optimiser state into corresponding TensorFlow variables . This may need to be done
for optimisers like ScipyOptimiser that work with their own copies of the variables .
Normally the source variables would be updated only when the optimise... | if context . optimiser is None or context . optimiser_updated :
return
if isinstance ( context . optimiser , ScipyOptimizer ) and len ( args ) > 0 :
optimizer = context . optimiser . optimizer
# get access to ExternalOptimizerInterface
var_vals = [ args [ 0 ] [ packing_slice ] for packing_slice in optim... |
def _getField ( self , field , native = 0 , prompt = 1 ) :
"""Get a parameter field value""" | try : # expand field name using minimum match
field = _getFieldDict [ field ]
except KeyError as e : # re - raise the exception with a bit more info
raise SyntaxError ( "Cannot get field " + field + " for parameter " + self . name + "\n" + str ( e ) )
if field == "p_value" : # return value of parameter
# Note t... |
def edit ( self , ** kwargs ) :
"""Modify this calendar event .
: calls : ` PUT / api / v1 / calendar _ events / : id < https : / / canvas . instructure . com / doc / api / calendar _ events . html # method . calendar _ events _ api . update > ` _
: rtype : : class : ` canvasapi . calendar _ event . CalendarEve... | response = self . _requester . request ( 'PUT' , 'calendar_events/{}' . format ( self . id ) , _kwargs = combine_kwargs ( ** kwargs ) )
if 'title' in response . json ( ) :
super ( CalendarEvent , self ) . set_attributes ( response . json ( ) )
return CalendarEvent ( self . _requester , response . json ( ) ) |
def _recv_return ( self , method_frame ) :
'''Handle basic . return method . If we have a complete message , will call the
user ' s return listener callabck ( if any ) . If there are not enough
frames , will re - queue current frames and raise a FrameUnderflow
NOTE : if the channel was in confirmation mode wh... | msg = self . _read_returned_msg ( method_frame )
if callable ( self . _return_listener ) :
self . _return_listener ( msg )
else :
self . logger . error ( "Published message returned by broker: info=%s, properties=%s" , msg . return_info , msg . properties ) |
def calculeToday ( self ) :
"""Calcule the intervals from the last date .""" | self . __logger . debug ( "Add today" )
last = datetime . datetime . strptime ( self . __lastDay , "%Y-%m-%d" )
today = datetime . datetime . now ( ) . date ( )
self . __validInterval ( last , today ) |
def dim_extent_size ( self , * args , ** kwargs ) :
"""Returns extent sizes of the dimensions in args .
. . code - block : : python
ts , bs , cs = cube . dim _ extent _ size ( ' ntime ' , ' nbl ' , ' nchan ' )
or
. . code - block : : python
ts , bs , cs , ss = cube . dim _ extent _ size ( ' ntime , nbl : ... | extents = self . dim_extents ( * args , ** kwargs )
# Handle tuples and sequences differently
if isinstance ( extents , tuple ) :
return extents [ 1 ] - extents [ 0 ]
else : # isinstance ( extents , collections . Sequence ) :
return ( u - l for l , u in extents ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.