signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def grant_assistance ( self , column = None , value = None , ** kwargs ) :
"""Many - to - many table connecting grants and assistance .""" | return self . _resolve_call ( 'GIC_GRANT_ASST_PGM' , column , value , ** kwargs ) |
def parse_code ( code , var_factory , ** kwargs ) :
"""Parse a piece of text and substitude $ var by either unique
variable names or by the given kwargs mapping . Use $ $ to escape $ .
Returns a CodeBlock and the resulting variable mapping .
parse ( " $ foo = $ foo + $ bar " , bar = " 1 " )
( " t1 = t1 + 1 ... | block = CodeBlock ( )
defdict = collections . defaultdict ( var_factory )
defdict . update ( kwargs )
indent = - 1
code = code . strip ( )
for line in code . splitlines ( ) :
length = len ( line )
line = line . lstrip ( )
spaces = length - len ( line )
if spaces :
if indent < 0 :
ind... |
def create ( self , request , * args , ** kwargs ) :
"""Grabbing the user from request . user , and the rest of the method
is the same as ModelViewSet . create ( ) .
: param request : a WSGI request object
: param args : inline arguments ( optional )
: param kwargs : keyword arguments ( optional )
: retur... | data = get_request_data ( request ) . copy ( )
data [ "user" ] = request . user . id
serializer = self . get_serializer ( data = data , files = request . FILES )
if serializer . is_valid ( ) :
self . pre_save ( serializer . object )
self . object = serializer . save ( force_insert = True )
self . post_save ... |
def set_param ( self , params , value = None ) :
"""Set parameters into the Booster .
Parameters
params : dict / list / str
list of key , value pairs , dict of key to value or simply str key
value : optional
value of the specified parameter , when params is str key""" | if isinstance ( params , Mapping ) :
params = params . items ( )
elif isinstance ( params , STRING_TYPES ) and value is not None :
params = [ ( params , value ) ]
for key , val in params :
_check_call ( _LIB . XGBoosterSetParam ( self . handle , c_str ( key ) , c_str ( str ( val ) ) ) ) |
def thing2place ( self , name ) :
"""Unset a Thing ' s location , and thus turn it into a Place .""" | self . engine . _set_thing_loc ( self . name , name , None )
if ( self . name , name ) in self . engine . _node_objs :
thing = self . engine . _node_objs [ self . name , name ]
place = Place ( self , name )
for port in thing . portals ( ) :
port . origin = place
for port in thing . preportals ( ... |
def _get_non_defined ( self , data , class_types ) :
"""returns a list of URIs and blanknodes that are not defined within
the dataset . For example : schema : Person has an associated rdf : type
then it is considered defined .
args :
data : a list of triples
class _ types : list of subjects that are defin... | subj_set = set ( [ item [ self . smap ] for item in class_types ] )
non_def_set = set ( [ item [ self . smap ] for item in data ] )
return list ( non_def_set - subj_set ) |
def _pooling_output_shape ( input_shape , pool_size = ( 2 , 2 ) , strides = None , padding = 'VALID' ) :
"""Helper : compute the output shape for the pooling layer .""" | dims = ( 1 , ) + pool_size + ( 1 , )
# NHWC
spatial_strides = strides or ( 1 , ) * len ( pool_size )
strides = ( 1 , ) + spatial_strides + ( 1 , )
pads = padtype_to_pads ( input_shape , dims , strides , padding )
operand_padded = onp . add ( input_shape , onp . add ( * zip ( * pads ) ) )
t = onp . floor_divide ( onp . ... |
def compaction ( self , request_compaction = False ) :
"""Retrieve a report on , or request compaction for this instance .
: param bool request _ compaction : A boolean indicating whether or not to request compaction .""" | url = self . _service_url + 'compaction/'
if request_compaction :
response = requests . post ( url , ** self . _instances . _default_request_kwargs )
else :
response = requests . get ( url , ** self . _instances . _default_request_kwargs )
return response . json ( ) |
def getFileFormat ( self , name , args ) :
"""Récupération du contenu d ' un fichier via la configuration
et interprétation des variables données en argument""" | # récupération du nom du fichier
template_pathname = self . get ( name , "--" )
if not os . path . isfile ( template_pathname ) :
return False
# configuration
content = ""
with open ( template_pathname ) as fp : # Create a text / plain message
content = fp . read ( ) . format ( ** args )
# retour ok
return co... |
def add_node ( self , node ) :
"""Link to the agent from a parent based on the parent ' s fitness""" | num_agents = len ( self . nodes ( type = Agent ) )
curr_generation = int ( ( num_agents - 1 ) / float ( self . generation_size ) )
node . generation = curr_generation
if curr_generation == 0 and self . initial_source :
parent = self . _select_oldest_source ( )
else :
parent = self . _select_fit_node_from_genera... |
def _avro_schema ( read_session ) :
"""Extract and parse Avro schema from a read session .
Args :
read _ session ( ~ google . cloud . bigquery _ storage _ v1beta1 . types . ReadSession ) :
The read session associated with this read rows stream . This
contains the schema , which is required to parse the data... | json_schema = json . loads ( read_session . avro_schema . schema )
column_names = tuple ( ( field [ "name" ] for field in json_schema [ "fields" ] ) )
return fastavro . parse_schema ( json_schema ) , column_names |
def lex ( code , lexer ) :
"""Lex ` ` code ` ` with ` ` lexer ` ` and return an iterable of tokens .""" | try :
return lexer . get_tokens ( code )
except TypeError as err :
if ( isinstance ( err . args [ 0 ] , str ) and ( 'unbound method get_tokens' in err . args [ 0 ] or 'missing 1 required positional argument' in err . args [ 0 ] ) ) :
raise TypeError ( 'lex() argument must be a lexer instance, ' 'not a c... |
def shift_right ( self , times = 1 ) :
"""Finds Location shifted right by 1
: rtype : Location""" | try :
return Location ( self . _rank , self . _file + times )
except IndexError as e :
raise IndexError ( e ) |
def lowercased_words ( content , filter = True , predicate = None ) :
"""Returns an iterable of lowercased words from the provided text .
` content `
A text .
` filter `
Indicates if stop words and garbage like " xxxxx " should be removed from
the word list .
` predicate `
An alternative word filter .... | return ( w . lower ( ) for w in words ( content , filter , predicate ) ) |
def _timeout_expired ( self ) :
"""A timeout was supplied during setup , and the time has run out .""" | self . _did_timeout = True
try :
self . transport . signalProcess ( 'TERM' )
except error . ProcessExitedAlready : # XXX why don ' t we just always do this ?
self . transport . loseConnection ( )
fail = Failure ( RuntimeError ( "timeout while launching Tor" ) )
self . _maybe_notify_connected ( fail ) |
def leave_chat ( chat_id , ** kwargs ) :
"""Use this method for your bot to leave a group , supergroup or channel .
: param chat _ id : Unique identifier for the target chat or username of the target channel ( in the format @ channelusername )
: param kwargs : Args that get passed down to : class : ` TelegramBo... | # required args
params = dict ( chat_id = chat_id , )
return TelegramBotRPCRequest ( 'leaveChat' , params = params , on_result = lambda result : result , ** kwargs ) |
def _find_docstring_line ( self , start , end ) :
"""Find the row where a docstring starts in a function or class .
This will search for the first match of a triple quote token in
row sequence from the start of the class or function .
Args :
start : the row where the class / function starts .
end : the ro... | for i in range ( start , end + 1 ) :
if i in self . _tokenized_triple_quotes :
return i
return None |
def create_elb_dns ( self , regionspecific = False ) :
"""Create dns entries in route53.
Args :
regionspecific ( bool ) : The DNS entry should have region on it
Returns :
str : Auto - generated DNS name for the Elastic Load Balancer .""" | if regionspecific :
dns_elb = self . generated . dns ( ) [ 'elb_region' ]
else :
dns_elb = self . generated . dns ( ) [ 'elb' ]
dns_elb_aws = find_elb ( name = self . app_name , env = self . env , region = self . region )
zone_ids = get_dns_zone_ids ( env = self . env , facing = self . elb_subnet )
self . log .... |
def _register_allocator ( self , plugin_name , plugin_instance ) :
"""Register an allocator .
: param plugin _ name : Allocator name
: param plugin _ instance : RunPluginBase
: return :""" | for allocator in plugin_instance . get_allocators ( ) . keys ( ) :
if allocator in self . _allocators :
raise PluginException ( "Allocator with name {} already exists! unable to add " "allocators from plugin {}" . format ( allocator , plugin_name ) )
self . _allocators [ allocator ] = plugin_instance . ... |
def _get_payload ( self , key ) :
"""Retrieve an item and expiry time from the cache by key .
: param key : The cache key
: type key : str
: rtype : dict""" | path = self . _path ( key )
# If the file doesn ' t exists , we obviously can ' t return the cache so we will
# just return null . Otherwise , we ' ll get the contents of the file and get
# the expiration UNIX timestamps from the start of the file ' s contents .
if not os . path . exists ( path ) :
return { 'data' ... |
def set_focus_to_state_model ( self , state_m , ratio_requested = 0.8 ) :
"""Focus a state view of respective state model
: param rafcon . gui . model . state state _ m : Respective state model of state view to be focused
: param ratio _ requested : Minimum ratio of the screen which is requested , so can be mor... | state_machine_m = self . model
state_v = self . canvas . get_view_for_model ( state_m )
if state_v is None :
logger . warning ( 'There is no view for state model {0}' . format ( state_m ) )
self . move_item_into_viewport ( state_v )
# check _ relative size in view and call it again if the state is still very small
... |
def plot_bargraph ( self , data , cats = None , pconfig = None ) :
"""Depreciated function . Forwards to new location .""" | from multiqc . plots import bargraph
if pconfig is None :
pconfig = { }
return bargraph . plot ( data , cats , pconfig ) |
def parse_event_record ( self , node ) :
"""Parses < EventRecord >
@ param node : Node containing the < EventRecord > element
@ type node : xml . etree . Element""" | if self . current_simulation == None :
self . raise_error ( '<EventRecord> must be only be used inside a ' + 'simulation specification' )
if 'quantity' in node . lattrib :
quantity = node . lattrib [ 'quantity' ]
else :
self . raise_error ( '<EventRecord> must specify a quantity.' )
if 'eventport' in node .... |
def _get_doubles_target ( module , class_name , path ) :
"""Validate and return the class to be doubled .
: param module module : The module that contains the class that will be doubled .
: param str class _ name : The name of the class that will be doubled .
: param str path : The full path to the class that... | try :
doubles_target = getattr ( module , class_name )
if isinstance ( doubles_target , ObjectDouble ) :
return doubles_target . _doubles_target
if not isclass ( doubles_target ) :
raise VerifyingDoubleImportError ( 'Path does not point to a class: {}.' . format ( path ) )
return doubles... |
def mark_in_progress ( self , rr_id : str , rr_size : int ) -> None :
"""Prepare sentinel directory for revocation registry construction .
: param rr _ id : revocation registry identifier
: rr _ size : size of revocation registry to build""" | try :
makedirs ( join ( self . _dir_tails_sentinel , rr_id ) , exist_ok = False )
except FileExistsError :
LOGGER . warning ( 'Rev reg %s construction already in progress' , rr_id )
else :
open ( join ( self . _dir_tails_sentinel , rr_id , '.{}' . format ( rr_size ) ) , 'w' ) . close ( ) |
def edit ( path ) :
"""Edit a post .
If requested over GET , shows the edit UI .
If requested over POST , saves the post and shows the edit UI .
: param path : Path to post to edit .""" | context = { 'path' : path , 'site' : site }
post = find_post ( path )
if post is None :
return error ( "No such post or page." , 404 )
current_auid = int ( post . meta ( 'author.uid' ) or current_user . uid )
if ( not current_user . can_edit_all_posts and current_auid != current_user . uid ) :
return error ( "C... |
def build_ast ( self ) :
"""Convert an top level parse tree node into an AST mod .""" | n = self . root_node
if n . type == syms . file_input :
stmts = [ ]
for i in range ( len ( n . children ) - 1 ) :
stmt = n . children [ i ]
if stmt . type == tokens . NEWLINE :
continue
sub_stmts_count = self . number_of_statements ( stmt )
if sub_stmts_count == 1 :
... |
def dispatch ( self , event : Any ) -> None :
"""Send an event to an ` ev _ * ` method .
` * ` will be the events type converted to lower - case .
If ` event . type ` is an empty string or None then it will be ignored .""" | if event . type :
getattr ( self , "ev_%s" % ( event . type . lower ( ) , ) ) ( event ) |
def normalize_fft_params ( series , kwargs = None , func = None ) :
"""Normalize a set of FFT parameters for processing
This method reads the ` ` fftlength ` ` and ` ` overlap ` ` keyword arguments
( presumed to be values in seconds ) , works out sensible defaults ,
then updates ` ` kwargs ` ` in place to inc... | # parse keywords
if kwargs is None :
kwargs = dict ( )
samp = series . sample_rate
fftlength = kwargs . pop ( 'fftlength' , None ) or series . duration
overlap = kwargs . pop ( 'overlap' , None )
window = kwargs . pop ( 'window' , None )
# parse function library and name
if func is None :
method = library = Non... |
def encipher ( self , string ) :
"""Encipher string using Foursquare cipher according to initialised key . Punctuation and whitespace
are removed from the input . If the input plaintext is not an even number of characters , an ' X ' will be appended .
Example : :
ciphertext = Foursquare ( key1 = ' zgptfoihmuw... | string = self . remove_punctuation ( string )
if len ( string ) % 2 == 1 :
string = string + 'X'
ret = ''
for c in range ( 0 , len ( string . upper ( ) ) , 2 ) :
a , b = self . encipher_pair ( string [ c ] , string [ c + 1 ] )
ret += a + b
return ret |
def warn_if_element_not_of_class ( element , class_suffix , special_ui_components_prefix ) :
"""Log a warning if the element is not of the given type ( indicating that it is not internationalized ) .
Args :
element : The xib ' s XML element .
class _ name : The type the element should be , but is missing .
... | valid_class_names = [ "%s%s" % ( DEFAULT_UI_COMPONENTS_PREFIX , class_suffix ) ]
if special_ui_components_prefix is not None :
valid_class_names . append ( "%s%s" % ( special_ui_components_prefix , class_suffix ) )
if ( not element . hasAttribute ( 'customClass' ) ) or element . attributes [ 'customClass' ] . value... |
def query ( self , transport , protocol , * data ) :
"""Generates and sends a query message unit .
: param transport : An object implementing the ` . Transport ` interface .
It is used by the protocol to send the message and receive the
response .
: param protocol : An object implementing the ` . Protocol `... | if not self . _query :
raise AttributeError ( 'Command is not queryable' )
if self . protocol :
protocol = self . protocol
if self . _query . data_type :
data = _dump ( self . _query . data_type , data )
else : # TODO We silently ignore possible data
data = ( )
if isinstance ( transport , SimulatedTrans... |
def set_handler ( self , handler ) :
"""set the callback processing object to be used by the receiving thread after receiving the data . User should set
their own callback object setting in order to achieve event driven .
: param handler : the object in callback handler base
: return : ret _ error or ret _ ok... | set_flag = False
for protoc in self . _handler_table :
if isinstance ( handler , self . _handler_table [ protoc ] [ "type" ] ) :
self . _handler_table [ protoc ] [ "obj" ] = handler
return RET_OK
if set_flag is False :
return RET_ERROR |
def untargz ( input_targz_file , untar_to_dir ) :
"""This module accepts a tar . gz archive and untars it .
RETURN VALUE : path to the untar - ed directory / file
NOTE : this module expects the multiple files to be in a directory before
being tar - ed .""" | assert tarfile . is_tarfile ( input_targz_file ) , 'Not a tar file.'
tarball = tarfile . open ( input_targz_file )
return_value = os . path . join ( untar_to_dir , tarball . getmembers ( ) [ 0 ] . name )
tarball . extractall ( path = untar_to_dir )
tarball . close ( )
return return_value |
def _set_interface_reverse_metric ( self , v , load = False ) :
"""Setter method for interface _ reverse _ metric , mapped from YANG variable / routing _ system / interface / ve / intf _ isis / interface _ isis / interface _ reverse _ metric ( container )
If this variable is read - only ( config : false ) in the ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = interface_reverse_metric . interface_reverse_metric , is_container = 'container' , presence = True , yang_name = "interface-reverse-metric" , rest_name = "reverse-metric" , parent = self , path_helper = self . _path_helper , ... |
def __fix_bases ( base_classes , have_mt ) :
"""This function check whether base _ classes contains a Model
instance . If not , choose the best fitting class for
model . Furthermore , it makes the list in a cannonical
ordering form in a way that ic can be used as memoization
key""" | fixed = list ( base_classes )
contains_model = False
for b in fixed :
if isinstance ( fixed , Model ) :
contains_model = True ;
break
pass
# adds a model when user is lazy
if not contains_model :
if have_mt :
from gtkmvc3 . model_mt import ModelMT
fixed . insert ( 0 , ModelMT... |
def list_rules ( self , service = None ) :
"""List fault fault injection rules installed on instances of a given service ( or all services )
returns a JSON dictionary""" | rules = { }
for service in self . app . get_services ( ) :
rules [ service ] = { }
for instance in self . app . get_service_instances ( service ) :
rules [ service ] [ instance ] = { }
resp = requests . get ( "http://{}/gremlin/v1/rules/list" . format ( instance ) )
if resp . status_code... |
def parse_reference_line ( ref_line , kbs , bad_titles_count = { } , linker_callback = None ) :
"""Parse one reference line
@ input a string representing a single reference bullet
@ output parsed references ( a list of elements objects )""" | # Strip the ' marker ' ( e . g . [ 1 ] ) from this reference line :
line_marker , ref_line = remove_reference_line_marker ( ref_line )
# Find DOI sections in citation
ref_line , identified_dois = identify_and_tag_DOI ( ref_line )
# Identify and replace URLs in the line :
ref_line , identified_urls = identify_and_tag_UR... |
def extract_schemas_from_source ( source , filename = '<unknown>' ) :
"""Extract schemas from ' source ' .
The ' source ' parameter must be a string , and should be valid python
source .
If ' source ' is not valid python source , a SyntaxError will be raised .
: returns : a list of ViewSchema objects .""" | # Track which acceptable services have been configured .
acceptable_services = set ( )
# Track which acceptable views have been configured :
acceptable_views = { }
schemas_found = [ ]
ast_tree = ast . parse ( source , filename )
simple_names = _get_simple_assignments ( ast_tree )
assigns = [ n for n in ast_tree . body ... |
def _get_uptime ( self , app_stats ) :
"""Return Icinga ' s uptime""" | if "program_start" not in app_stats . keys ( ) :
return 0
if not app_stats [ "program_start" ] . isdigit ( ) :
return 0
uptime = int ( time . time ( ) ) - int ( app_stats [ "program_start" ] )
if uptime < 0 :
return 0
return uptime |
def _get_relative_ext ( of , sf ) :
"""Retrieve relative extension given the original and secondary files .""" | def half_finished_trim ( orig , prefix ) :
return ( os . path . basename ( prefix ) . count ( "." ) > 0 and os . path . basename ( orig ) . count ( "." ) == os . path . basename ( prefix ) . count ( "." ) )
# Handle remote files
if of . find ( ":" ) > 0 :
of = os . path . basename ( of . split ( ":" ) [ - 1 ] )... |
def sort_descendants ( self , attr = "name" ) :
"""This function sort the branches of a given tree by
considerening node names . After the tree is sorted , nodes are
labeled using ascendent numbers . This can be used to ensure
that nodes in a tree with the same node names are always
labeled in the same way ... | node2content = self . get_cached_content ( store_attr = attr , container_type = list )
for n in self . traverse ( ) :
if not n . is_leaf ( ) :
n . children . sort ( key = lambda x : str ( sorted ( node2content [ x ] ) ) ) |
def _config_chooser_dialog ( self , title_text , description ) :
"""Dialog to select which config shall be exported
: param title _ text : Title text
: param description : Description""" | dialog = Gtk . Dialog ( title_text , self . view [ "preferences_window" ] , flags = 0 , buttons = ( Gtk . STOCK_CANCEL , Gtk . ResponseType . REJECT , Gtk . STOCK_OK , Gtk . ResponseType . ACCEPT ) )
label = Gtk . Label ( label = description )
label . set_padding ( xpad = 10 , ypad = 10 )
dialog . vbox . pack_start ( l... |
def mdl_nominal ( x , y , separate_max ) :
"""Function calculates minimum description length for discrete features . If feature is continuous it is firstly discretized .
x : numpy array - numerical or discrete feature
y : numpy array - labels""" | x_vals = np . unique ( x )
# unique values
if len ( x_vals ) == 1 : # if there is just one unique value
return None
y_dist = Counter ( y )
# label distribution
# calculate distributions and splits in accordance with feature type
dist , splits = nominal_splits ( x , y , x_vals , y_dist , separate_max )
prior_mdl = c... |
def init_app ( self , app , session ) :
"""Will initialize the Flask app , supporting the app factory pattern .
: param app :
: param session : The SQLAlchemy session""" | app . config . setdefault ( "APP_NAME" , "F.A.B." )
app . config . setdefault ( "APP_THEME" , "" )
app . config . setdefault ( "APP_ICON" , "" )
app . config . setdefault ( "LANGUAGES" , { "en" : { "flag" : "gb" , "name" : "English" } } )
app . config . setdefault ( "ADDON_MANAGERS" , [ ] )
app . config . setdefault ( ... |
def write_badge ( self , file_path , overwrite = False ) :
"""Write badge to file .""" | # Validate path ( part 1)
if file_path . endswith ( '/' ) :
raise Exception ( 'File location may not be a directory.' )
# Get absolute filepath
path = os . path . abspath ( file_path )
if not path . lower ( ) . endswith ( '.svg' ) :
path += '.svg'
# Validate path ( part 2)
if not overwrite and os . path . exist... |
def _tidy_repr ( self , max_vals = 10 , footer = True ) :
"""a short repr displaying only max _ vals and an optional ( but default
footer )""" | num = max_vals // 2
head = self [ : num ] . _get_repr ( length = False , footer = False )
tail = self [ - ( max_vals - num ) : ] . _get_repr ( length = False , footer = False )
result = '{head}, ..., {tail}' . format ( head = head [ : - 1 ] , tail = tail [ 1 : ] )
if footer :
result = '{result}\n{footer}' . format ... |
def _cron_id ( cron ) :
'''SAFETYBELT , Only set if we really have an identifier''' | cid = None
if cron [ 'identifier' ] :
cid = cron [ 'identifier' ]
else :
cid = SALT_CRON_NO_IDENTIFIER
if cid :
return _ensure_string ( cid ) |
def port_bindings ( val , ** kwargs ) :
'''On the CLI , these are passed as multiple instances of a given CLI option .
In Salt , we accept these as a comma - delimited list but the API expects a
Python dictionary mapping ports to their bindings . The format the API
expects is complicated depending on whether ... | validate_ip_addrs = kwargs . get ( 'validate_ip_addrs' , True )
if not isinstance ( val , dict ) :
if not isinstance ( val , list ) :
try :
val = helpers . split ( val )
except AttributeError :
val = helpers . split ( six . text_type ( val ) )
for idx in range ( len ( val... |
def _register_key ( fingerprint , gpg ) :
"""Registers key in config""" | for private_key in gpg . list_keys ( True ) :
try :
if str ( fingerprint ) == private_key [ 'fingerprint' ] :
config [ "gpg_key_fingerprint" ] = repr ( private_key [ 'fingerprint' ] )
except KeyError :
pass |
def com_adobe_fonts_check_name_postscript_vs_cff ( ttFont ) :
"""CFF table FontName must match name table ID 6 ( PostScript name ) .""" | failed = False
cff_names = ttFont [ 'CFF ' ] . cff . fontNames
if len ( cff_names ) != 1 :
yield ERROR , ( "Unexpected number of font names in CFF table." )
return
cff_name = cff_names [ 0 ]
for entry in ttFont [ 'name' ] . names :
if entry . nameID == NameID . POSTSCRIPT_NAME :
postscript_name = en... |
def dihed_iter ( self , g_nums , ats_1 , ats_2 , ats_3 , ats_4 , invalid_error = False ) :
"""Iterator over selected dihedral angles .
Angles are in degrees as with : meth : ` dihed _ single ` .
See ` above < toc - generators _ > ` _ for more information on
calling options .
Parameters
g _ nums
| int | ... | # Suitability of ats _ n indices will be checked within the
# self . dihed _ single ( ) calls and thus no check is needed here .
# Import the tuple - generating function
from . utils import pack_tups
# Print the function inputs if debug mode is on
if _DEBUG : # pragma : no cover
print ( "g_nums = {0}" . format ( g_... |
def __RemoteExecuteHelper ( args ) :
"""Helper for multiprocessing .""" | cmd , hostname , ssh_key = args
# Random . atfork ( ) # needed to fix bug in old python 2.6 interpreters
private_key = paramiko . RSAKey . from_private_key ( StringIO . StringIO ( ssh_key ) )
client = paramiko . SSHClient ( )
client . set_missing_host_key_policy ( paramiko . AutoAddPolicy ( ) )
while True :
try :
... |
def listen_forever ( self , timeout_ms : int = 30000 , exception_handler : Callable [ [ Exception ] , None ] = None , bad_sync_timeout : int = 5 , ) :
"""Keep listening for events forever .
Args :
timeout _ ms : How long to poll the Home Server for before retrying .
exception _ handler : Optional exception ha... | _bad_sync_timeout = bad_sync_timeout
self . should_listen = True
while self . should_listen :
try : # may be killed and raise exception from _ handle _ thread
self . _sync ( timeout_ms )
_bad_sync_timeout = bad_sync_timeout
except MatrixRequestError as e :
log . warning ( 'A MatrixReques... |
def _set_get_lldp_neighbor_detail ( self , v , load = False ) :
"""Setter method for get _ lldp _ neighbor _ detail , mapped from YANG variable / brocade _ lldp _ ext _ rpc / get _ lldp _ neighbor _ detail ( rpc )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ get _ ll... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = get_lldp_neighbor_detail . get_lldp_neighbor_detail , is_leaf = True , yang_name = "get-lldp-neighbor-detail" , rest_name = "get-lldp-neighbor-detail" , parent = self , path_helper = self . _path_helper , extmethods = self . ... |
def get_widget ( title ) :
"""Get the Qt widget of the IDA window with the given title .""" | tform = idaapi . find_tform ( title )
if not tform :
raise exceptions . FormNotFound ( "No form titled {!r} found." . format ( title ) )
return form_to_widget ( tform ) |
def liftover ( args ) :
"""% prog liftover blastfile anchorfile [ options ]
Typical use for this program is given a list of anchors ( syntennic
genes ) , choose from the blastfile the pairs that are close to the anchors .
Anchorfile has the following format , each row defines a pair .
geneA geneB
geneC ge... | p = OptionParser ( liftover . __doc__ )
p . set_stripnames ( )
blast_file , anchor_file , dist , opts = add_options ( p , args )
qbed , sbed , qorder , sorder , is_self = check_beds ( blast_file , p , opts )
filtered_blast = read_blast ( blast_file , qorder , sorder , is_self = is_self , ostrip = opts . strip_names )
b... |
def root ( x , k , context = None ) :
"""Return the kth root of x .
For k odd and x negative ( including - Inf ) , return a negative number .
For k even and x negative ( including - Inf ) , return NaN .
The kth root of - 0 is defined to be - 0 , whatever the parity of k .
This function is only implemented f... | if k < 0 :
raise ValueError ( "root function not implemented for negative k" )
return _apply_function_in_current_context ( BigFloat , mpfr . mpfr_root , ( BigFloat . _implicit_convert ( x ) , k ) , context , ) |
def sign ( node = None ) :
"""Sign a specific node to grant it access
you can specify " all " to sign all nodes
returns the nodes that were signed""" | if not node :
raise Exception ( "Specify either 'all' your specify token/host_name of node to sign. " )
if node == 'all' :
node = 'unsigned'
nodes = list_nodes ( search = node )
result = { }
for token , i in nodes . items ( ) :
i [ 'access' ] = 'node'
i . save ( )
result [ token ] = i
return result |
def _process_strainmeans_file ( self , limit ) :
"""This will store the entire set of strain means in a hash .
Not the most efficient representation ,
but easy access .
We will loop through this later to then apply cutoffs
and add associations
: param limit :
: return :""" | LOG . info ( "Processing strain means ..." )
line_counter = 0
raw = '/' . join ( ( self . rawdir , self . files [ 'strainmeans' ] [ 'file' ] ) )
with gzip . open ( raw , 'rb' ) as f :
f = io . TextIOWrapper ( f )
reader = csv . reader ( f )
self . check_header ( self . files [ 'strainmeans' ] [ 'file' ] , f... |
def pretty_print ( ast , indent_str = ' ' ) :
"""Simple pretty print function ; returns a string rendering of an input
AST of an ES5 Program .
arguments
ast
The AST to pretty print
indent _ str
The string used for indentations . Defaults to two spaces .""" | return '' . join ( chunk . text for chunk in pretty_printer ( indent_str ) ( ast ) ) |
def delete_repository ( self , repository_id = None ) :
"""Deletes a ` ` Repository ` ` .
arg : repository _ id ( osid . id . Id ) : the ` ` Id ` ` of the
` ` Repository ` ` to remove
raise : NotFound - ` ` repository _ id ` ` not found
raise : NullArgument - ` ` repository _ id ` ` is ` ` null ` `
raise ... | # Implemented from awsosid template for -
# osid . resource . BinAdminSession . delete _ bin _ template
if not self . _can ( 'delete' ) :
raise PermissionDenied ( )
else :
return self . _provider_session . delete_repository ( repository_id ) |
def make_jvp_reversemode ( fun , x ) :
"""Builds a function for evaluating the Jacobian - vector product at a
point . Roughly 1.5x more FLOPs than forward - mode , plus memory requirements
that scale with the number of primitives applied in the evaluation of f , as
well as other overheads . See j - towns . gi... | vjp , y = _make_vjp ( fun , x )
vjp_vjp , _ = _make_vjp ( vjp , vspace ( y ) . zeros ( ) )
return vjp_vjp |
def getFirstLevel ( self ) :
"""returns a list of couples ( x1 , x2 ) of all the first level indexed regions""" | res = [ ]
if len ( self . children ) > 0 :
for c in self . children :
res . append ( ( c . x1 , c . x2 ) )
else :
if self . x1 != None :
res = [ ( self . x1 , self . x2 ) ]
else :
res = None
return res |
def push ( self , id ) :
"Sends a message to the specified connection ( id )" | conn = session [ 'connections' ] . get ( id , None )
if conn :
msgs = simplejson . loads ( request . body )
for msg in msgs :
try :
cmd = msg . pop ( 0 ) . upper ( )
assert ' ' not in cmd , "Bad message"
if cmd in ( 'USER' , ) :
sufix = " :" + msg . po... |
def cell_sides_angstrom ( self ) :
"""Array of sizes of a unit cell in Angstroms .
The value is determined from the ` ` ' cella ' ` ` entry in ` header ` .""" | return np . asarray ( self . header [ 'cella' ] [ 'value' ] , dtype = float ) / self . data_shape |
def format_docstring ( owner_name , docstring , formatters ) :
"""Template ` ` formatters ` ` into ` ` docstring ` ` .
Parameters
owner _ name : str
The name of the function or class whose docstring is being templated .
Only used for error messages .
docstring : str
The docstring to template .
formatt... | # Build a dict of parameters to a vanilla format ( ) call by searching for
# each entry in * * formatters and applying any leading whitespace to each
# line in the desired substitution .
format_params = { }
for target , doc_for_target in iteritems ( formatters ) : # Search for ' { name } ' , with optional leading white... |
def load_labels ( path : Union [ str , Path ] ) -> List [ SingleConditionSpec ] :
"""Load labels files .
Parameters
path
Path of labels file .
Returns
List [ SingleConditionSpec ]
List of SingleConditionSpec stored in labels file .""" | condition_specs = np . load ( str ( path ) )
return [ c . view ( SingleConditionSpec ) for c in condition_specs ] |
def modifyExtensions ( self , extensionObjects = [ ] ) :
"""enables / disables a service extension type based on the name""" | if len ( extensionObjects ) > 0 and isinstance ( extensionObjects [ 0 ] , Extension ) :
self . _extensions = extensionObjects
res = self . edit ( str ( self ) )
self . _json = None
self . __init ( )
return res |
def get_pool_for_host ( self , host_id ) :
"""Returns the connection pool for the given host .
This connection pool is used by the redis clients to make sure
that it does not have to reconnect constantly . If you want to use
a custom redis client you can pass this in as connection pool
manually .""" | if isinstance ( host_id , HostInfo ) :
host_info = host_id
host_id = host_info . host_id
else :
host_info = self . hosts . get ( host_id )
if host_info is None :
raise LookupError ( 'Host %r does not exist' % ( host_id , ) )
rv = self . _pools . get ( host_id )
if rv is not None :
return rv
... |
def get_zonefile_inventory ( hostport , offset , count , timeout = 30 , my_hostport = None , proxy = None ) :
"""Get the atlas zonefile inventory from the given peer .
offset / count are in bytes .
Return { ' status ' : True , ' inv ' : inventory } on success .
Return { ' error ' : . . . } on error""" | assert hostport or proxy , 'Need either hostport or proxy'
inv_schema = { 'type' : 'object' , 'properties' : { 'inv' : { 'type' : 'string' , 'pattern' : OP_BASE64_EMPTY_PATTERN } , } , 'required' : [ 'inv' ] }
schema = json_response_schema ( inv_schema )
if proxy is None :
proxy = connect_hostport ( hostport )
zf_i... |
def add_composition ( self , composition ) :
"""Add a composition to the suite .
Raise an UnexpectedObjectError when the supplied argument is not a
Composition object .""" | if not hasattr ( composition , 'tracks' ) :
raise UnexpectedObjectError ( "Object '%s' not expected. Expecting " "a mingus.containers.Composition object." % composition )
self . compositions . append ( composition )
return self |
def parse_record_static ( self , raw ) :
"""Parse raw data ( that is retrieved by static request ) and return pandas . DataFrame .
Returns tuple ( data , metadata )
data - pandas . DataFrame with retrieved data .
metadata - pandas . DataFrame with info about symbol , currency , frequency ,
displayname and s... | # Parsing status
status = self . status ( raw )
# Testing if no errors
if status [ 'StatusType' ] != 'Connected' :
if self . raise_on_error :
raise DatastreamException ( '%s (error %i): %s --> "%s"' % ( status [ 'StatusType' ] , status [ 'StatusCode' ] , status [ 'StatusMessage' ] , status [ 'Request' ] ) )... |
def supplement ( self , coordsys = 'gal' ) :
"""Add some supplemental columns""" | from ugali . utils . projector import gal2cel , gal2cel_angle
from ugali . utils . projector import cel2gal , cel2gal_angle
coordsys = coordsys . lower ( )
kwargs = dict ( usemask = False , asrecarray = True )
out = copy . deepcopy ( self )
if ( 'lon' in out . names ) and ( 'lat' in out . names ) : # Ignore entries tha... |
def list_requests ( self , status = None , assignee = None , author = None ) :
"""Get all pull requests of a project .
: param status : filters the status of the requests
: param assignee : filters the assignee of the requests
: param author : filters the author of the requests
: return :""" | request_url = "{}pull-requests" . format ( self . create_basic_url ( ) )
payload = { }
if status is not None :
payload [ 'status' ] = status
if assignee is not None :
payload [ 'assignee' ] = assignee
if author is not None :
payload [ 'author' ] = author
return_value = self . _call_api ( request_url , param... |
def add_depth_channel ( img_tensor , pad_mode ) :
'''img _ tensor : N , C , H , W''' | img_tensor [ : , 1 ] = get_depth_tensor ( pad_mode )
img_tensor [ : , 2 ] = img_tensor [ : , 0 ] * get_depth_tensor ( pad_mode ) |
def fit ( self , X , y = None , ** fit_params ) :
"""This method performs preliminary computations in order to set up the
figure or perform other analyses . It can also call drawing methods in
order to set up various non - instance related figure elements .
This method must return self .""" | # Handle the feature names if they ' re None .
if self . features_ is None : # If X is a data frame , get the columns off it .
if is_dataframe ( X ) :
self . features_ = np . array ( X . columns )
# Otherwise create numeric labels for each column .
else :
_ , ncols = X . shape
self .... |
def remove_existing_fpaths ( fpath_list , verbose = VERBOSE , quiet = QUIET , strict = False , print_caller = PRINT_CALLER , lbl = 'files' ) :
"""checks existance before removing . then tries to remove exisint paths""" | import utool as ut
if print_caller :
print ( util_dbg . get_caller_name ( range ( 1 , 4 ) ) + ' called remove_existing_fpaths' )
fpath_list_ = ut . filter_Nones ( fpath_list )
exists_list = list ( map ( exists , fpath_list_ ) )
if verbose :
n_total = len ( fpath_list )
n_valid = len ( fpath_list_ )
n_ex... |
def GetMemMappedMB ( self ) :
'''Retrieves the amount of memory that is allocated to the virtual machine .
Memory that is ballooned , swapped , or has never been accessed is
excluded .''' | counter = c_uint ( )
ret = vmGuestLib . VMGuestLib_GetMemMappedMB ( self . handle . value , byref ( counter ) )
if ret != VMGUESTLIB_ERROR_SUCCESS :
raise VMGuestLibException ( ret )
return counter . value |
def make_op_return_outputs ( data , inputs , change_address , fee = OP_RETURN_FEE , send_amount = 0 , format = 'bin' ) :
"""Builds the outputs for an OP _ RETURN transaction .""" | return [ # main output
{ "script_hex" : make_op_return_script ( data , format = format ) , "value" : send_amount } , # change output
{ "script_hex" : make_pay_to_address_script ( change_address ) , "value" : calculate_change_amount ( inputs , send_amount , fee ) } ] |
def replace_dataset ( self , dataset_key , ** kwargs ) :
"""Replace an existing dataset
* This method will completely overwrite an existing dataset . *
: param description : Dataset description
: type description : str , optional
: param summary : Dataset summary markdown
: type summary : str , optional
... | request = self . __build_dataset_obj ( lambda : _swagger . DatasetPutRequest ( title = kwargs . get ( 'title' ) , visibility = kwargs . get ( 'visibility' ) ) , lambda name , url , expand_archive , description , labels : _swagger . FileCreateRequest ( name = name , source = _swagger . FileSourceCreateRequest ( url = ur... |
def getColData ( self , attri , fname , numtype = 'cycNum' ) :
"""In this method a column of data for the associated column
attribute is returned .
Parameters
attri : string
The name of the attribute we are looking for .
fname : string
The name of the file we are getting the data from or the
cycle num... | fname = self . findFile ( fname , numtype )
f = open ( fname , 'r' )
for i in range ( self . index + 1 ) :
f . readline ( )
lines = f . readlines ( )
for i in range ( len ( lines ) ) :
lines [ i ] = lines [ i ] . strip ( )
lines [ i ] = lines [ i ] . split ( )
index = 0
data = [ ]
while index < len ( self .... |
def hamming_emd ( d1 , d2 ) :
"""Return the Earth Mover ' s Distance between two distributions ( indexed
by state , one dimension per node ) using the Hamming distance between states
as the transportation cost function .
Singleton dimensions are sqeezed out .""" | N = d1 . squeeze ( ) . ndim
d1 , d2 = flatten ( d1 ) , flatten ( d2 )
return emd ( d1 , d2 , _hamming_matrix ( N ) ) |
def load_diagram_from_csv ( filepath , bpmn_diagram ) :
"""Reads an CSV file from given filepath and maps it into inner representation of BPMN diagram .
Returns an instance of BPMNDiagramGraph class .
: param filepath : string with output filepath ,
: param bpmn _ diagram : an instance of BpmnDiagramGraph cla... | sequence_flows = bpmn_diagram . sequence_flows
process_elements_dict = bpmn_diagram . process_elements
diagram_attributes = bpmn_diagram . diagram_attributes
plane_attributes = bpmn_diagram . plane_attributes
process_dict = BpmnDiagramGraphCSVImport . import_csv_file_as_dict ( filepath )
BpmnDiagramGraphCSVImport . pop... |
def price_dataframe ( symbols = ( 'sne' , ) , start = datetime . datetime ( 2008 , 1 , 1 ) , end = datetime . datetime ( 2009 , 12 , 31 ) , price_type = 'actual_close' , cleaner = util . clean_dataframe , ) :
"""Retrieve the prices of a list of equities as a DataFrame ( columns = symbols )
Arguments :
symbols (... | if isinstance ( price_type , basestring ) :
price_type = [ price_type ]
start = nlp . util . normalize_date ( start or datetime . date ( 2008 , 1 , 1 ) )
end = nlp . util . normalize_date ( end or datetime . date ( 2009 , 12 , 31 ) )
symbols = util . make_symbols ( symbols )
df = get_dataframes ( symbols )
# t = du... |
def dumps ( asts ) :
"""Create a compressed string from an Trace .""" | d = asts . values . tostring ( )
t = asts . index . values . astype ( float ) . tostring ( )
lt = struct . pack ( '<L' , len ( t ) )
i = asts . name . encode ( 'utf-8' )
li = struct . pack ( '<L' , len ( i ) )
try : # python 2
return buffer ( zlib . compress ( li + lt + i + t + d ) )
except NameError : # python 3
... |
def to_protobuf ( self ) -> SaveStateProto :
"""Create protobuf item .
: return : protobuf structure
: rtype : ~ unidown . plugin . protobuf . save _ state _ pb2 . SaveStateProto""" | result = SaveStateProto ( )
result . version = str ( self . version )
result . last_update . CopyFrom ( datetime_to_timestamp ( self . last_update ) )
result . plugin_info . CopyFrom ( self . plugin_info . to_protobuf ( ) )
for key , link_item in self . link_item_dict . items ( ) :
result . data [ key ] . CopyFrom ... |
def get ( context , resource , ** kwargs ) :
"""List a specific resource""" | uri = '%s/%s/%s' % ( context . dci_cs_api , resource , kwargs . pop ( 'id' ) )
r = context . session . get ( uri , timeout = HTTP_TIMEOUT , params = kwargs )
return r |
def reload ( self ) :
"""Load this object from the server again and update ` ` attrs ` ` with the
new data .""" | new_model = self . collection . get ( self . id )
self . attrs = new_model . attrs |
def _pick_lead_item ( items ) :
"""Pick single representative sample for batch calling to attach calls to .
For cancer samples , attach to tumor .""" | if vcfutils . is_paired_analysis ( [ dd . get_align_bam ( x ) for x in items ] , items ) :
for data in items :
if vcfutils . get_paired_phenotype ( data ) == "tumor" :
return data
raise ValueError ( "Did not find tumor sample in paired tumor/normal calling" )
else :
return items [ 0 ] |
def prepare ( data ) :
"""Restructure / prepare data about refs for output .""" | ref = data . get ( "ref" )
obj = data . get ( "object" )
sha = obj . get ( "sha" )
return { "ref" : ref , "head" : { "sha" : sha } } |
def combine_reducers ( reducers ) :
"""composition tool for creating reducer trees .
Args :
reducers : dict with state keys and reducer functions
that are responsible for each key
Returns :
a new , combined reducer function""" | final_reducers = { key : reducer for key , reducer in reducers . items ( ) if hasattr ( reducer , '__call__' ) }
sanity_error = None
try :
assert_reducer_sanity ( final_reducers )
except Exception as e :
sanity_error = e
def combination ( state = None , action = None ) :
if state is None :
state = {... |
def get_slack_channels ( self , token ) :
'''Get all channel names from Slack''' | ret = salt . utils . slack . query ( function = 'rooms' , api_key = token , # These won ' t be honored until https : / / github . com / saltstack / salt / pull / 41187 / files is merged
opts = { 'exclude_archived' : True , 'exclude_members' : True } )
channels = { }
if 'message' in ret :
for item in ret [ 'message'... |
def run ( self ) :
"""Version of run that traps Exceptions and stores
them in the fifo""" | try :
threading . Thread . run ( self )
except Exception :
t , v , tb = sys . exc_info ( )
error = traceback . format_exception_only ( t , v ) [ 0 ] [ : - 1 ]
tback = ( self . name + ' Traceback (most recent call last):\n' + '' . join ( traceback . format_tb ( tb ) ) )
self . fifo . put ( ( self . n... |
def sipprverse_full ( self ) :
"""Run a subset of the methods - only the targets used in the sipprverse are required here""" | logging . info ( 'Beginning sipprverse full database downloads' )
if self . overwrite or not os . path . isdir ( os . path . join ( self . databasepath , 'genesippr' ) ) :
self . sipprverse_targets ( databasepath = self . databasepath )
if self . overwrite or not os . path . isdir ( os . path . join ( self . databa... |
def __parse ( self , stream , has_orgs ) :
"""Parse identities and organizations using mailmap format .
Mailmap format is a text plain document that stores on each
line a map between an email address and its aliases . Each
line follows any of the next formats :
Proper Name < commit @ email . xx >
< proper... | if has_orgs :
self . __parse_organizations ( stream )
else :
self . __parse_identities ( stream ) |
def _save_results ( options , module , core_results , fit_results ) :
"""Save results of analysis as tables and figures
Parameters
options : dict
Option names and values for analysis
module : str
Module that contained function used to generate core _ results
core _ results : dataframe , array , value , ... | logging . info ( "Saving all results" )
# Use custom plot format
mpl . rcParams . update ( misc . rcparams . ggplot_rc )
# Make run directory
os . makedirs ( options [ 'run_dir' ] )
# Write core results
_write_core_tables ( options , module , core_results )
# Write additional results if analysis from emp
if module == '... |
def save ( self , fname ) :
"""Save a pickled version of the embedding into ` fname ` .""" | vec = self . vectors
voc = self . vocabulary . getstate ( )
state = ( voc , vec )
with open ( fname , 'wb' ) as f :
pickle . dump ( state , f , protocol = pickle . HIGHEST_PROTOCOL ) |
def redirect ( self , url , status = None ) :
"""Redirect to the specified url , optional status code defaults to 302.""" | self . status_code = 302 if status is None else status
self . headers = Headers ( [ ( 'location' , url ) ] )
self . message = ''
self . end ( ) |
def as_namedtuple ( self ) :
"""Export color register as namedtuple .""" | d = self . as_dict ( )
return namedtuple ( 'ColorRegister' , d . keys ( ) ) ( * d . values ( ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.