signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _request ( self , service , ** parameters ) :
"""request builder""" | urlformat = "{baseurl}/{service}?{parameters}&format=json"
url = urlformat . format ( baseurl = API_BASE_URL , service = service , parameters = "&" . join ( [ "{}={}" . format ( key , value ) for key , value in parameters . items ( ) ] ) )
if datetime . now ( ) > self . _token_expire_date :
self . update_token ( )
... |
def populate_user ( self , request , sociallogin , data ) :
"""Hook that can be used to further populate the user instance .
For convenience , we populate several common fields .
Note that the user instance being populated represents a
suggested User instance that represents the social user that is
in the p... | username = data . get ( 'username' )
first_name = data . get ( 'first_name' )
last_name = data . get ( 'last_name' )
email = data . get ( 'email' )
name = data . get ( 'name' )
user = sociallogin . user
user_username ( user , username or '' )
user_email ( user , valid_email_or_none ( email ) or '' )
name_parts = ( name... |
def add_email_address ( self , email , hidden = None ) :
"""Add email address .
Args :
: param email : email of the author .
: type email : string
: param hidden : if email is public or not .
: type hidden : boolean""" | existing_emails = get_value ( self . obj , 'email_addresses' , [ ] )
found_email = next ( ( existing_email for existing_email in existing_emails if existing_email . get ( 'value' ) == email ) , None )
if found_email is None :
new_email = { 'value' : email }
if hidden is not None :
new_email [ 'hidden' ]... |
def get_tmuxinator_dir ( ) :
"""Return tmuxinator configuration directory .
Checks for ` ` TMUXINATOR _ CONFIG ` ` environmental variable .
Returns
str :
absolute path to tmuxinator config directory
See Also
: meth : ` tmuxp . config . import _ tmuxinator `""" | if 'TMUXINATOR_CONFIG' in os . environ :
return os . path . expanduser ( os . environ [ 'TMUXINATOR_CONFIG' ] )
return os . path . expanduser ( '~/.tmuxinator/' ) |
def env ( self ) :
"""Dict of all environment variables that will be run with this command .""" | env_vars = os . environ . copy ( )
env_vars . update ( self . _env )
new_path = ":" . join ( self . _paths + [ env_vars [ "PATH" ] ] if "PATH" in env_vars else [ ] + self . _paths )
env_vars [ "PATH" ] = new_path
for env_var in self . _env_drop :
if env_var in env_vars :
del env_vars [ env_var ]
return env_... |
def script ( vm_ ) :
'''Return the script deployment object''' | script_name = config . get_cloud_config_value ( 'script' , vm_ , __opts__ )
if not script_name :
script_name = 'bootstrap-salt'
return salt . utils . cloud . os_script ( script_name , vm_ , __opts__ , salt . utils . cloud . salt_config_to_yaml ( salt . utils . cloud . minion_config ( __opts__ , vm_ ) ) ) |
def solarcalcs ( self ) :
"""Solar Calculation
Mutates RSM , BEM , and UCM objects based on following parameters :
UCM # Urban Canopy - Building Energy Model object
BEM # Building Energy Model object
simTime # Simulation time bbject
RSM # Rural Site & Vertical Diffusion Model Object
forc # Forcing objec... | self . dir = self . forc . dir
# Direct sunlight ( perpendicular to the sun ' s ray )
self . dif = self . forc . dif
# Diffuse sunlight
if self . dir + self . dif > 0. :
self . logger . debug ( "{} Solar radiation > 0" . format ( __name__ ) )
# calculate zenith tangent , and critOrient solar angles
self . s... |
def close ( self ) :
"""Stops the read thread , waits for it to exit cleanly , then closes the underlying serial port""" | self . alive = False
self . rxThread . join ( )
self . serial . close ( ) |
def execute ( self ) :
"""Execute the actions necessary to perform a ` molecule lint ` and
returns None .
: return : None""" | self . print_info ( )
linters = [ l for l in [ self . _config . lint , self . _config . verifier . lint , self . _config . provisioner . lint , ] if l ]
for l in linters :
l . execute ( ) |
def per_chat_id_in ( s , types = 'all' ) :
""": param s :
a list or set of chat id
: param types :
` ` all ` ` or a list of chat types ( ` ` private ` ` , ` ` group ` ` , ` ` channel ` ` )
: return :
a seeder function that returns the chat id only if the chat id is in ` ` s ` `
and chat type is in ` ` t... | return _wrap_none ( lambda msg : msg [ 'chat' ] [ 'id' ] if ( types == 'all' or msg [ 'chat' ] [ 'type' ] in types ) and msg [ 'chat' ] [ 'id' ] in s else None ) |
def fw_int_to_hex ( * args ) :
"""Pack integers into hex string .
Use little - endian and unsigned int format .""" | return binascii . hexlify ( struct . pack ( '<{}H' . format ( len ( args ) ) , * args ) ) . decode ( 'utf-8' ) |
def main ( ) :
"""Paperboy entry point - parse the arguments and run a command""" | parser = argparse . ArgumentParser ( description = 'Paperboy deep learning launcher' )
parser . add_argument ( 'config' , metavar = 'FILENAME' , help = 'Configuration file for the run' )
parser . add_argument ( 'command' , metavar = 'COMMAND' , help = 'A command to run' )
parser . add_argument ( 'varargs' , nargs = '*'... |
def _gather_variables ( stack_def ) :
"""Merges context provided & stack defined variables .
If multiple stacks have a variable with the same name , we can specify the
value for a specific stack by passing in the variable name as : ` < stack
name > : : < variable name > ` . This variable value will only be us... | variable_values = copy . deepcopy ( stack_def . variables or { } )
return [ Variable ( k , v ) for k , v in variable_values . items ( ) ] |
def _call_member ( obj , name , failfast = True , * args , ** kwargs ) :
"""Calls the specified method , property or attribute of the given object
Parameters
obj : object
The object that will be used
name : str
Name of method , property or attribute
failfast : bool
If True , will raise an exception wh... | try :
attr = getattr ( obj , name )
except AttributeError as e :
if failfast :
raise e
else :
return None
try :
if inspect . ismethod ( attr ) : # call function
return attr ( * args , ** kwargs )
elif isinstance ( attr , property ) : # call property
return obj . attr
... |
def wait_for_array ( self , wait_for , timeout_ms ) :
"""Waits for one or more events to happen .
Scriptable version of : py : func : ` wait _ for ` .
in wait _ for of type : class : ` ProcessWaitForFlag `
Specifies what to wait for ;
see : py : class : ` ProcessWaitForFlag ` for more information .
in tim... | if not isinstance ( wait_for , list ) :
raise TypeError ( "wait_for can only be an instance of type list" )
for a in wait_for [ : 10 ] :
if not isinstance ( a , ProcessWaitForFlag ) :
raise TypeError ( "array can only contain objects of type ProcessWaitForFlag" )
if not isinstance ( timeout_ms , baseint... |
def get_obj_url ( request , obj ) :
"""Returns object URL if current logged user has permissions to see the object""" | if ( is_callable ( getattr ( obj , 'get_absolute_url' , None ) ) and ( not hasattr ( obj , 'can_see_edit_link' ) or ( is_callable ( getattr ( obj , 'can_see_edit_link' , None ) ) and obj . can_see_edit_link ( request ) ) ) ) :
return call_method_with_unknown_input ( obj . get_absolute_url , request = request )
else... |
def tryMatch ( self , textToMatchObject ) :
"""Try to find themselves in the text .
Returns ( contextStack , count , matchedRule ) or ( contextStack , None , None ) if doesn ' t match""" | # Skip if column doesn ' t match
if self . column != - 1 and self . column != textToMatchObject . currentColumnIndex :
return None
if self . firstNonSpace and ( not textToMatchObject . firstNonSpace ) :
return None
return self . _tryMatch ( textToMatchObject ) |
def get ( self , path , params , ** options ) :
"""Parses GET request options and dispatches a request""" | return self . request ( 'get' , path , params = params , ** options ) |
def interface_by_ipaddr ( self , ipaddr ) :
'''Given an IP address , return the interface that ' owns ' this address''' | ipaddr = IPAddr ( ipaddr )
for devname , iface in self . _devinfo . items ( ) :
if iface . ipaddr == ipaddr :
return iface
raise KeyError ( "No device has IP address {}" . format ( ipaddr ) ) |
def _apply_fd_rule ( self , step_ratio , sequence , steps ) :
"""Return derivative estimates of fun at x0 for a sequence of stepsizes h
Member variables used""" | f_del , h , original_shape = self . _vstack ( sequence , steps )
fd_rule = self . _get_finite_difference_rule ( step_ratio )
ne = h . shape [ 0 ]
nr = fd_rule . size - 1
_assert ( nr < ne , 'num_steps ({0:d}) must be larger than ' '({1:d}) n + order - 1 = {2:d} + {3:d} -1' ' ({4:s})' . format ( ne , nr + 1 , self . n ... |
def vt2esofspy ( vesseltree , outputfilename = "tracer.txt" , axisorder = [ 0 , 1 , 2 ] ) :
"""exports vesseltree to esofspy format
: param vesseltree : filename or vesseltree dictionary structure
: param outputfilename : output file name
: param axisorder : order of axis can be specified with this option
:... | if ( type ( vesseltree ) == str ) and os . path . isfile ( vesseltree ) :
import io3d
vt = io3d . misc . obj_from_file ( vesseltree )
else :
vt = vesseltree
print ( vt [ 'general' ] )
print ( vt . keys ( ) )
vtgm = vt [ 'graph' ] [ 'microstructure' ]
lines = [ ]
vs = vt [ 'general' ] [ 'voxel_size_mm' ]
sh ... |
def new_messages_handler ( stream ) :
"""Saves a new chat message to db and distributes msg to connected users""" | # TODO : handle no user found exception
while True :
packet = yield from stream . get ( )
session_id = packet . get ( 'session_key' )
msg = packet . get ( 'message' )
username_opponent = packet . get ( 'username' )
if session_id and msg and username_opponent :
user_owner = get_user_from_sess... |
def selectSQL ( conn , sql , args = None ) :
'''sql : a select statement
args : if sql has parameters defined with either % s or % ( key ) s then args should be a either list or dict of parameter
values respectively .
returns a tuple of rows , each of which is a tuple .''' | with doCursor ( conn ) as cursor :
cursor . execute ( sql , args )
results = cursor . fetchall ( )
return results |
def render_indirect ( self , buffer , mode = None , count = - 1 , * , first = 0 ) -> None :
'''The render primitive ( mode ) must be the same as
the input primitive of the GeometryShader .
The draw commands are 5 integers : ( count , instanceCount , firstIndex , baseVertex , baseInstance ) .
Args :
buffer (... | if mode is None :
mode = TRIANGLES
self . mglo . render_indirect ( buffer . mglo , mode , count , first ) |
def read_sex_problems ( file_name ) :
"""Reads the sex problem file .
: param file _ name : the name of the file containing sex problems .
: type file _ name : str
: returns : a : py : class : ` frozenset ` containing samples with sex problem .
If there is no ` ` file _ name ` ` ( * i . e . * is ` ` None ` ... | if file_name is None :
return frozenset ( )
problems = None
with open ( file_name , 'r' ) as input_file :
header_index = dict ( [ ( col_name , i ) for i , col_name in enumerate ( input_file . readline ( ) . rstrip ( "\r\n" ) . split ( "\t" ) ) ] )
if "IID" not in header_index :
msg = "{}: no column ... |
def normalizeGlyphWidth ( value ) :
"""Normalizes glyph width .
* * * value * * must be a : ref : ` type - int - float ` .
* Returned value is the same type as the input value .""" | if not isinstance ( value , ( int , float ) ) :
raise TypeError ( "Glyph width must be an :ref:`type-int-float`, not %s." % type ( value ) . __name__ )
return value |
def library_directories ( self ) -> typing . List [ str ] :
"""The list of directories to all of the library locations""" | def listify ( value ) :
return [ value ] if isinstance ( value , str ) else list ( value )
# If this is a project running remotely remove external library
# folders as the remote shared libraries folder will contain all
# of the necessary dependencies
is_local_project = not self . is_remote_project
folders = [ f fo... |
def sendm ( self_p , dest ) :
"""Send message to destination socket as part of a multipart sequence , and
destroy the message after sending it successfully . Note that after a
zmsg _ sendm , you must call zmsg _ send or another method that sends a final
message part . If the message has no frames , sends noth... | return lib . zmsg_sendm ( byref ( zmsg_p . from_param ( self_p ) ) , dest ) |
def remove_masquerade ( zone = None , permanent = True ) :
'''Remove masquerade on a zone .
If zone is omitted , default zone will be used .
. . versionadded : : 2015.8.0
CLI Example :
. . code - block : : bash
salt ' * ' firewalld . remove _ masquerade
To remove masquerade on a specific zone
. . code... | if zone :
cmd = '--zone={0} --remove-masquerade' . format ( zone )
else :
cmd = '--remove-masquerade'
if permanent :
cmd += ' --permanent'
return __firewall_cmd ( cmd ) |
def acquisition_function_withGradients ( self , x ) :
"""Returns the acquisition function and its its gradient at x .""" | aqu_x = self . acquisition_function ( x )
aqu_x_grad = self . d_acquisition_function ( x )
return aqu_x , aqu_x_grad |
def find ( self , _id , instance = None ) :
"""Find
Args :
_ id ( str ) : instance id or binding Id
Keyword Arguments :
instance ( AtlasServiceInstance . Instance ) : Existing instance
Returns :
AtlasServiceInstance . Instance or AtlasServiceBinding . Binding : An instance or binding .""" | if instance is None : # We are looking for an instance
return self . service_instance . find ( _id )
else : # We are looking for a binding
return self . service_binding . find ( _id , instance ) |
def remove ( text , what , count = None , strip = False ) :
'''Like ` ` replace ` ` , where ` ` new ` ` replacement is an empty string .''' | return replace ( text , what , '' , count = count , strip = strip ) |
def OnText ( self , event = None ) :
"text event" | try :
if event . GetString ( ) != '' :
self . __CheckValid ( event . GetString ( ) )
except :
pass
event . Skip ( ) |
def main ( self ) :
"""Run all the methods required for pipeline outputs""" | self . fasta_records ( )
self . fasta_stats ( )
self . find_largest_contig ( )
self . find_genome_length ( )
self . find_num_contigs ( )
self . find_n50 ( )
self . perform_pilon ( )
self . clear_attributes ( ) |
def handle ( self ) :
"""Creates a child process that is fully controlled by this
request handler , and serves data to and from it via the
protocol handler .""" | pid , fd = pty . fork ( )
if pid :
protocol = TelnetServerProtocolHandler ( self . request , fd )
protocol . handle ( )
else :
self . execute ( ) |
def intcomma ( value ) :
"""Borrowed from django . contrib . humanize
Converts an integer to a string containing commas every three digits .
For example , 3000 becomes ' 3,000 ' and 45000 becomes ' 45,000 ' .""" | orig = str ( value )
new = re . sub ( "^(-?\d+)(\d{3})" , '\g<1>,\g<2>' , orig )
if orig == new :
return new
else :
return intcomma ( new ) |
def save ( self , model ) :
"""Attach a model instance to the parent models .
: param model : The model instance to attach
: type model : Model
: rtype : Model""" | model . set_attribute ( self . get_plain_morph_type ( ) , self . _morph_class )
return super ( MorphOneOrMany , self ) . save ( model ) |
def load_checkpoint ( with_local = False ) :
"""Load latest check point .
Parameters
with _ local : bool , optional
whether the checkpoint contains local model
Returns
tuple : tuple
if with _ local : return ( version , gobal _ model , local _ model )
else return ( version , gobal _ model )
if return... | gptr = ctypes . POINTER ( ctypes . c_char ) ( )
global_len = ctypes . c_ulong ( )
if with_local :
lptr = ctypes . POINTER ( ctypes . c_char ) ( )
local_len = ctypes . c_ulong ( )
version = _LIB . RabitLoadCheckPoint ( ctypes . byref ( gptr ) , ctypes . byref ( global_len ) , ctypes . byref ( lptr ) , ctypes... |
def commit ( config , no_verify ) :
"""Commit the current branch with all files .""" | repo = config . repo
active_branch = repo . active_branch
if active_branch . name == "master" :
error_out ( "Can't commit when on the master branch. " "You really ought to do work in branches." )
now = time . time ( )
def count_files_in_directory ( directory ) :
count = 0
for root , _ , files in os . walk (... |
def index ( ) :
"""This is not served anywhere in the web application .
It is used explicitly in the context of generating static files since
flask - frozen requires url _ for ' s to crawl content .
url _ for ' s are not used with result . show _ result directly and are instead
dynamically generated through... | if current_app . config [ 'ARA_PLAYBOOK_OVERRIDE' ] is not None :
override = current_app . config [ 'ARA_PLAYBOOK_OVERRIDE' ]
results = ( models . TaskResult . query . join ( models . Task ) . filter ( models . Task . playbook_id . in_ ( override ) ) )
else :
results = models . TaskResult . query . all ( )
... |
def appendhdf5 ( table , source , where = None , name = None ) :
"""As : func : ` petl . io . hdf5 . tohdf5 ` but don ' t truncate the target table before
loading .""" | with _get_hdf5_table ( source , where , name , mode = 'a' ) as h5table : # load the data
_insert ( table , h5table ) |
def get_wu_settings ( ) :
'''Get current Windows Update settings .
Returns :
dict : A dictionary of Windows Update settings :
Featured Updates :
Boolean value that indicates whether to display notifications for
featured updates .
Group Policy Required ( Read - only ) :
Boolean value that indicates whe... | ret = { }
day = [ 'Every Day' , 'Sunday' , 'Monday' , 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday' , 'Saturday' ]
# Initialize the PyCom system
with salt . utils . winapi . Com ( ) : # Create an AutoUpdate object
obj_au = win32com . client . Dispatch ( 'Microsoft.Update.AutoUpdate' )
# Create an AutoUpdate Setti... |
def create_hooks ( config : dict , model : AbstractModel , dataset : AbstractDataset , output_dir : str ) -> Iterable [ AbstractHook ] :
"""Create hooks specified in ` ` config [ ' hooks ' ] ` ` list .
Hook config entries may be one of the following types :
. . code - block : : yaml
: caption : A hook with de... | logging . info ( 'Creating hooks' )
hooks = [ ]
if 'hooks' in config :
for hook_config in config [ 'hooks' ] :
if isinstance ( hook_config , str ) :
hook_config = { hook_config : { } }
assert len ( hook_config ) == 1 , 'Hook configuration must have exactly one key (fully qualified name).... |
def teardown_logical_port_connectivity ( self , context , port_db , hosting_device_id ) :
"""Removes connectivity for a logical port .
Unplugs the corresponding data interface from the VM .""" | if port_db is None or port_db . get ( 'id' ) is None :
LOG . warning ( "Port id is None! Cannot remove port " "from hosting_device:%s" , hosting_device_id )
return
hosting_port_id = port_db . hosting_info . hosting_port . id
try :
self . _dev_mgr . svc_vm_mgr . interface_detach ( hosting_device_id , hosting... |
def _handle_version ( self , data ) :
"""Handles received version data .
: param data : Version string to parse
: type data : string""" | _ , version_string = data . split ( ':' )
version_parts = version_string . split ( ',' )
self . serial_number = version_parts [ 0 ]
self . version_number = version_parts [ 1 ]
self . version_flags = version_parts [ 2 ] |
def article ( self ) :
"""| Comment : Id of the associated article , if present""" | if self . api and self . article_id :
return self . api . _get_article ( self . article_id ) |
def load_state ( cls , path : PathOrStr , state : dict ) -> 'LabelList' :
"Create a ` LabelList ` from ` state ` ." | x = state [ 'x_cls' ] ( [ ] , path = path , processor = state [ 'x_proc' ] , ignore_empty = True )
y = state [ 'y_cls' ] ( [ ] , path = path , processor = state [ 'y_proc' ] , ignore_empty = True )
res = cls ( x , y , tfms = state [ 'tfms' ] , tfm_y = state [ 'tfm_y' ] , ** state [ 'tfmargs' ] ) . process ( )
if state ... |
def load_json ( path : str , encoding : str = "utf-8" ) -> HistogramBase :
"""Load histogram from a JSON file .""" | with open ( path , "r" , encoding = encoding ) as f :
text = f . read ( )
return parse_json ( text ) |
def _containing_contigs ( self , hits ) :
'''Given a list of hits , all with same query ,
returns a set of the contigs containing that query''' | return { hit . ref_name for hit in hits if self . _contains ( hit ) } |
def iter ( self , match = "*" , count = 1000 ) :
"""Iterates the set of keys in : prop : key _ prefix in : prop : _ client
@ match : # str pattern to match after the : prop : key _ prefix
@ count : the user specified the amount of work that should be done
at every call in order to retrieve elements from the c... | replace_this = self . key_prefix + ":"
for key in self . _client . scan_iter ( match = "{}:{}" . format ( self . key_prefix , match ) , count = count ) :
yield self . _decode ( key ) . replace ( replace_this , "" , 1 ) |
def to_string ( self , format_str ) :
'''Output lat , lon coordinates as string in chosen format
Inputs :
format ( str ) - A string of the form A % B % C where A , B and C are identifiers .
Unknown identifiers ( e . g . ' ' , ' , ' or ' _ ' will be inserted as separators
in a position corresponding to the p... | format2value = { 'H' : self . get_hemisphere ( ) , 'M' : abs ( self . decimal_minute ) , 'm' : int ( abs ( self . minute ) ) , 'd' : int ( self . degree ) , 'D' : self . decimal_degree , 'S' : abs ( self . second ) }
format_elements = format_str . split ( '%' )
coord_list = [ str ( format2value . get ( element , elemen... |
def write_message ( self , msg , timeout = None ) :
"""Write an arbitrary message ( of one of the types above ) .
For the host side implementation , this will only ever be a DataMessage , but
it ' s implemented generically enough here that you could use
FilesyncTransport to implement the device side if you wa... | replace_dict = { 'command' : self . CMD_TO_WIRE [ msg . command ] }
if msg . has_data : # Swap out data for the data length for the wire .
data = msg [ - 1 ]
replace_dict [ msg . _fields [ - 1 ] ] = len ( data )
self . stream . write ( struct . pack ( msg . struct_format , * msg . _replace ( ** replace_dict ) )... |
def _screen ( self , include = True , ** kwargs ) :
"""Filters a DataFrame for columns that contain the given strings .
Parameters :
include : bool
If False then it will exclude items that match
the given filters .
This is the same as passing a regex ^ keyword
kwargs :
Key value pairs that indicate th... | df = self . copy ( )
for k , v in list ( kwargs . items ( ) ) :
v = [ v ] if type ( v ) != list else v
if include :
df = df [ df [ k ] . str . contains ( '|' . join ( v ) , flags = re . IGNORECASE ) . fillna ( False ) ]
else :
df = df [ df [ k ] . str . contains ( '|' . join ( v ) , flags = ... |
def reset ( self , required = False ) :
"""Perform a reset and check for presence pulse .
: param bool required : require presence pulse""" | reset = self . _ow . reset ( )
if required and reset :
raise OneWireError ( "No presence pulse found. Check devices and wiring." )
return not reset |
def _report_line_to_dict ( cls , line ) :
'''Takes report line string as input . Returns a dict of column name - > value in line''' | data = line . split ( '\t' )
if len ( data ) != len ( report . columns ) :
return None
d = dict ( zip ( report . columns , data ) )
for key in report . int_columns :
try :
d [ key ] = int ( d [ key ] )
except :
assert d [ key ] == '.'
for key in report . float_columns :
try :
d [... |
def _get_id ( self ) :
"""Construct and return the identifier""" | return '' . join ( map ( str , filter ( is_not_None , [ self . Prefix , self . Name ] ) ) ) |
def create ( tournament , name , ** params ) :
"""Add a participant to a tournament .""" | params . update ( { "name" : name } )
return api . fetch_and_parse ( "POST" , "tournaments/%s/participants" % tournament , "participant" , ** params ) |
def search_channels ( self , query , limit = 25 , offset = 0 ) :
"""Search for channels and return them
: param query : the query string
: type query : : class : ` str `
: param limit : maximum number of results
: type limit : : class : ` int `
: param offset : offset for pagination
: type offset : : cl... | r = self . kraken_request ( 'GET' , 'search/channels' , params = { 'query' : query , 'limit' : limit , 'offset' : offset } )
return models . Channel . wrap_search ( r ) |
def process_alarms ( self , snmp_data ) :
"Build list with active alarms" | self . active_alarms = [ ]
for i in range ( 0 , len ( self . models [ self . modem_type ] [ 'alarms' ] ) ) :
if bool ( int ( snmp_data [ i ] ) ) == True :
self . active_alarms . append ( self . models [ self . modem_type ] [ 'alarms' ] [ i ] ) |
def num_strips ( self ) :
"""The number of strips a device with
the : attr : ` ~ libinput . constant . DeviceCapability . TABLET _ PAD `
capability provides .
Returns :
int : The number of strips or 0 if the device has no strips .
Raises :
AttributeError""" | num = self . _libinput . libinput_device_tablet_pad_get_num_strips ( self . _handle )
if num < 0 :
raise AttributeError ( 'This device is not a tablet pad device' )
return num |
def _get_summary ( self , text , ** kwargs ) :
"""Render out just the summary""" | card = cards . extract_card ( text , kwargs , self . search_path )
return flask . Markup ( ( card . description or '' ) . strip ( ) ) |
def args ( self ) -> str :
"""Provides arguments for the command .""" | return '{}{}{}{}{}' . format ( to_ascii_hex ( self . _index , 2 ) , to_ascii_hex ( self . _group_number , 2 ) , to_ascii_hex ( self . _unit_number , 2 ) , to_ascii_hex ( int ( self . _enable_status ) , 4 ) , to_ascii_hex ( int ( self . _switches ) , 4 ) ) |
def _prepare_sphx_glr_dirs ( gallery_conf , srcdir ) :
"""Creates necessary folders for sphinx _ gallery files""" | examples_dirs = gallery_conf [ 'examples_dirs' ]
gallery_dirs = gallery_conf [ 'gallery_dirs' ]
if not isinstance ( examples_dirs , list ) :
examples_dirs = [ examples_dirs ]
if not isinstance ( gallery_dirs , list ) :
gallery_dirs = [ gallery_dirs ]
if bool ( gallery_conf [ 'backreferences_dir' ] ) :
backr... |
def next ( self ) :
"""Returns the first YAML document in stream .
. . warning : :
Assume that the YAML document are closed explicitely with the sentinel ' . . . '""" | in_doc , lines , doc_tag = None , [ ] , None
for i , line in enumerate ( self . stream ) :
self . linepos += 1
# print ( i , line )
if line . startswith ( "---" ) : # Include only lines in the form :
# " - - - ! tag "
# Other lines are spurious .
in_doc = False
l = line [ 3 : ] . str... |
def cell_fate ( data , groupby = 'clusters' , disconnected_groups = None , self_transitions = False , n_neighbors = None , copy = False ) :
"""Computes individual cell endpoints
Arguments
data : : class : ` ~ anndata . AnnData `
Annotated data matrix .
groupby : ` str ` ( default : ` ' clusters ' ` )
Key ... | adata = data . copy ( ) if copy else data
logg . info ( 'computing cell fates' , r = True )
n_neighbors = 10 if n_neighbors is None else n_neighbors
_adata = adata . copy ( )
vgraph = VelocityGraph ( _adata , n_neighbors = n_neighbors , approx = True , n_recurse_neighbors = 1 )
vgraph . compute_cosines ( )
_adata . uns... |
def runAddAnnouncement ( self , flaskrequest ) :
"""Takes a flask request from the frontend and attempts to parse
into an AnnouncePeerRequest . If successful , it will log the
announcement to the ` announcement ` table with some other metadata
gathered from the request .""" | announcement = { }
# We want to parse the request ourselves to collect a little more
# data about it .
try :
requestData = protocol . fromJson ( flaskrequest . get_data ( ) , protocol . AnnouncePeerRequest )
announcement [ 'hostname' ] = flaskrequest . host_url
announcement [ 'remote_addr' ] = flaskrequest ... |
def makeSyncAnglePacket ( info ) :
"""Write sync angle information to servos .
info = [ [ ID , angle ] , [ ID , angle ] , . . . ]""" | addr = le ( xl320 . XL320_GOAL_POSITION )
data = [ ]
# since all servo angles have the same register addr ( XL320 _ GOAL _ POSITION )
# and data size ( 2 ) , a sinc packet is smart choice
# compare bulk vs sync for the same commands :
# bulk = 94 bytes
# sync = 50 bytes
data . append ( addr [ 0 ] )
# LSB
data . append ... |
def require_linklocal ( handler ) :
"""Ensure the decorated is only called if the request is linklocal .
The host ip address should be in the X - Host - IP header ( provided by nginx )""" | @ functools . wraps ( handler )
async def decorated ( request : web . Request ) -> web . Response :
ipaddr_str = request . headers . get ( 'x-host-ip' )
invalid_req_data = { 'error' : 'bad-interface' , 'message' : f'The endpoint {request.url} can only be used from ' 'local connections' }
if not ipaddr_str :... |
def delete_collection_validating_webhook_configuration ( self , ** kwargs ) :
"""delete collection of ValidatingWebhookConfiguration
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . delete _ collection _ valida... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . delete_collection_validating_webhook_configuration_with_http_info ( ** kwargs )
else :
( data ) = self . delete_collection_validating_webhook_configuration_with_http_info ( ** kwargs )
return data |
def median ( self ) :
"""Computes the median of a log - normal distribution built with the stats data .""" | mu = self . mean ( )
ret_val = math . exp ( mu )
if math . isnan ( ret_val ) :
ret_val = float ( "inf" )
return ret_val |
def is_canonical ( version , loosedev = False ) : # type : ( str , bool ) - > bool
"""Return whether or not the version string is canonical according to Pep 440""" | if loosedev :
return loose440re . match ( version ) is not None
return pep440re . match ( version ) is not None |
def dict_from_mmcif ( mmcif , path = True ) :
"""Parse mmcif file into a dictionary .
Notes
Full list of keys / value types , and further information on them can be viewed here :
http : / / mmcif . wwpdb . org / docs / pdb _ to _ pdbx _ correspondences . html
All values in the returned dict are str or list ... | if path :
with open ( mmcif , 'r' ) as foo :
lines = foo . readlines ( )
else :
lines = mmcif . splitlines ( )
lines = [ ' ' . join ( x . strip ( ) . split ( ) ) for x in lines ]
# Some of the data in a . cif files are stored between ' loop _ ' to initiate a loop , and ' # ' to terminate it .
# The vari... |
def get_subdomain_ops_at_txid ( self , txid , cur = None ) :
"""Given a txid , get all subdomain operations at that txid .
Include unaccepted operations .
Order by zone file index""" | get_cmd = 'SELECT * FROM {} WHERE txid = ? ORDER BY zonefile_offset' . format ( self . subdomain_table )
cursor = None
if cur is None :
cursor = self . conn . cursor ( )
else :
cursor = cur
db_query_execute ( cursor , get_cmd , ( txid , ) )
try :
return [ x for x in cursor . fetchall ( ) ]
except Exception ... |
def run ( self , * args ) :
"""Endit profile information .""" | uuid , kwargs = self . __parse_arguments ( * args )
code = self . edit_profile ( uuid , ** kwargs )
return code |
def _render ( tmpl , ctx ) :
""": param tmpl : mako . template . Template object
: param ctx : A dict or dict - like object to instantiate given""" | is_py3k = anytemplate . compat . IS_PYTHON_3
return tmpl . render_unicode ( ** ctx ) if is_py3k else tmpl . render ( ** ctx ) |
def tuned ( name , ** kwargs ) :
'''Manage options of block device
name
The name of the block device
opts :
- read - ahead
Read - ahead buffer size
- filesystem - read - ahead
Filesystem Read - ahead buffer size
- read - only
Set Read - Only
- read - write
Set Read - Write''' | ret = { 'changes' : { } , 'comment' : '' , 'name' : name , 'result' : True }
kwarg_map = { 'read-ahead' : 'getra' , 'filesystem-read-ahead' : 'getfra' , 'read-only' : 'getro' , 'read-write' : 'getro' }
if not __salt__ [ 'file.is_blkdev' ] :
ret [ 'comment' ] = ( 'Changes to {0} cannot be applied. ' 'Not a block dev... |
def request_url ( req = None ) :
"""Get full url of a request""" | from uliweb import request
r = req or request
if request :
if r . query_string :
return r . path + '?' + r . query_string
else :
return r . path
else :
return '' |
def borrow ( self , amount , collateral_ratio = None , account = None , target_collateral_ratio = None ) :
"""Borrow bitassets / smartcoins from the network by putting up
collateral in a CFD at a given collateral ratio .
: param float amount : Amount to borrow ( denoted in ' asset ' )
: param float collateral... | return self . adjust_debt ( amount , collateral_ratio , account , target_collateral_ratio = target_collateral_ratio , ) |
def generate_token ( self , user , password ) :
"""Takes user and password credentials and generates a new token
: param user : user
: param password : password
: return :
- dictionary containing token data
: raises :
- TokenCreateError : If there was an error generating the new token""" | logger . debug ( '(TOKEN_CREATE) :: User: %s' % user )
session = OAuth2Session ( client = LegacyApplicationClient ( client_id = self . client_id ) )
try :
return dict ( session . fetch_token ( token_url = self . token_url , username = user , password = password , client_id = self . client_id , client_secret = self ... |
def get_all_confirmations ( self , params = None ) :
"""Get all confirmations
This will iterate over all pages until it gets all elements .
So if the rate limit exceeded it will throw an Exception and you will get nothing
: param params : search params
: return : list""" | if not params :
params = { }
return self . _iterate_through_pages ( self . get_confirmations_per_page , resource = CONFIRMATIONS , ** { 'params' : params } ) |
def unpause ( self , container ) :
"""Unpause all processes within a container .
Args :
container ( str ) : The container to unpause""" | url = self . _url ( '/containers/{0}/unpause' , container )
res = self . _post ( url )
self . _raise_for_status ( res ) |
def _JsonValueToPythonValue ( json_value ) :
"""Convert the given JsonValue to a json string .""" | util . Typecheck ( json_value , JsonValue )
_ValidateJsonValue ( json_value )
if json_value . is_null :
return None
entries = [ ( f , json_value . get_assigned_value ( f . name ) ) for f in json_value . all_fields ( ) ]
assigned_entries = [ ( f , value ) for f , value in entries if value is not None ]
field , value... |
def check_existance ( f ) :
"""Check if the file supplied as input exists .""" | if not opath . isfile ( f ) :
logging . error ( "Nanoget: File provided doesn't exist or the path is incorrect: {}" . format ( f ) )
sys . exit ( "File provided doesn't exist or the path is incorrect: {}" . format ( f ) ) |
def ObtenerTablaParametros ( self , tipo_recurso , sep = "||" ) :
"Devuelve un array de elementos que tienen id y descripción" | if not self . client :
self . Conectar ( )
self . response = self . client ( "parametros" , "v1" , tipo_recurso )
result = json . loads ( self . response )
ret = { }
if result [ 'success' ] :
data = result [ 'data' ]
# armo un diccionario con los datos devueltos :
key = [ k for k in data [ 0 ] . keys ( ... |
def to_file_mode ( self ) :
"""Write all the messages to files""" | for message_no in range ( len ( self . messages ) ) :
self . __to_file ( message_no ) |
def check_encoding_and_env ( ) :
"""It brings the environment variables to the screen .
The user checks to see if they are using the correct variables .""" | import sys
import os
if sys . getfilesystemencoding ( ) in [ 'utf-8' , 'UTF-8' ] :
print ( __ ( u"{0}File system encoding correct{1}" ) . format ( CheckList . OKGREEN , CheckList . ENDC ) )
else :
print ( __ ( u"{0}File system encoding wrong!!{1}" ) . format ( CheckList . FAIL , CheckList . ENDC ) )
check_env_l... |
def kde_statsmodels_m ( data , grid , ** kwargs ) :
"""Multivariate Kernel Density Estimation with Statsmodels
Parameters
data : numpy . array
Data points used to compute a density estimator . It
has ` n x p ` dimensions , representing n points and p
variables .
grid : numpy . array
Data points at whi... | kde = KDEMultivariate ( data , ** kwargs )
return kde . pdf ( grid ) |
def set_flair ( self , * args , ** kwargs ) :
"""Set flair for this submission .
Convenience function that utilizes : meth : ` . ModFlairMixin . set _ flair `
populating both the ` subreddit ` and ` item ` parameters .
: returns : The json response from the server .""" | return self . subreddit . set_flair ( self , * args , ** kwargs ) |
def until ( name , m_args = None , m_kwargs = None , condition = None , period = 0 , timeout = 604800 ) :
'''Loop over an execution module until a condition is met .
name
The name of the execution module
m _ args
The execution module ' s positional arguments
m _ kwargs
The execution module ' s keyword a... | ret = { 'name' : name , 'changes' : { } , 'result' : False , 'comment' : '' }
if name not in __salt__ :
ret [ 'comment' ] = 'Cannot find module {0}' . format ( name )
return ret
if condition is None :
ret [ 'comment' ] = 'An exit condition must be specified'
return ret
if not isinstance ( period , int )... |
def get_xrefs_list_from_element ( cls , element ) :
"""Helper for get _ xrefs _ list
element is a ClassDefItem or MethodDefItem
At the end of the function , we lost if we worked on
a class or method but we do not care for now .""" | xref_items = element . XREFfrom . items
log . debug ( "%d XREFs found" % len ( xref_items ) )
xrefs = [ ]
for xref_item in xref_items :
class_ = xref_item [ 0 ] . get_class_name ( )
method_ = xref_item [ 0 ] . get_name ( )
descriptor_ = xref_item [ 0 ] . get_descriptor ( )
xrefs . append ( classmethod2d... |
def _generate_message_error ( cls , response_code , messages , response_id ) :
""": type response _ code : int
: type messages : list [ str ]
: type response _ id : str
: rtype : str""" | line_response_code = cls . _FORMAT_RESPONSE_CODE_LINE . format ( response_code )
line_response_id = cls . _FORMAT_RESPONSE_ID_LINE . format ( response_id )
line_error_message = cls . _FORMAT_ERROR_MESSAGE_LINE . format ( cls . _GLUE_ERROR_MESSAGE_STRING_EMPTY . join ( messages ) )
return cls . _glue_all_error_message (... |
def _get_env_activate ( bin_env ) :
'''Return the path to the activate binary''' | if not bin_env :
raise CommandNotFoundError ( 'Could not find a `activate` binary' )
if os . path . isdir ( bin_env ) :
if salt . utils . platform . is_windows ( ) :
activate_bin = os . path . join ( bin_env , 'Scripts' , 'activate.bat' )
else :
activate_bin = os . path . join ( bin_env , 'b... |
def insert_feasible_configurations ( cur , feasible_configurations , encoded_data = None ) :
"""Insert a group of feasible configurations into the cache .
Args :
cur ( : class : ` sqlite3 . Cursor ` ) : An sqlite3 cursor . This function
is meant to be run within a : obj : ` with ` statement .
feasible _ con... | if encoded_data is None :
encoded_data = { }
if 'num_variables' not in encoded_data :
encoded_data [ 'num_variables' ] = len ( next ( iter ( feasible_configurations ) ) )
if 'num_feasible_configurations' not in encoded_data :
encoded_data [ 'num_feasible_configurations' ] = len ( feasible_configurations )
i... |
def classes_to_clusters ( self ) :
"""Return the array ( ordered by cluster number ) of minimum error class to cluster mappings .
: return : the mappings
: rtype : ndarray""" | array = javabridge . call ( self . jobject , "getClassesToClusters" , "()[I" )
if array is None :
return None
else :
return javabridge . get_env ( ) . get_int_array_elements ( array ) |
def _container_registration ( self , alias ) :
"""Check for an available name and return that to the caller .""" | containers = Container . find_by_name ( self . _client_session , alias )
def validate_name ( name ) :
valid = True
if name in containers :
valid = False
return valid
count = 1
container_name = "{0}-0{1}" . format ( alias , count )
while not validate_name ( container_name ) :
count += 1
conta... |
def price ( pc , service , attrib , sku ) :
"""Get a list of a service ' s prices .
The list will be in the given region , matching the specific terms and
any given attribute filters or a SKU .""" | pc . service = service . lower ( )
pc . sku = sku
pc . add_attributes ( attribs = attrib )
click . echo ( "Service Alias: {0}" . format ( pc . service_alias ) )
click . echo ( "URL: {0}" . format ( pc . service_url ) )
click . echo ( "Region: {0}" . format ( pc . region ) )
click . echo ( "Product Terms: {0}" . format ... |
async def wait_for_send ( self , event , * , until = None ) :
'''Send an event to the main event queue . Can call without delegate .
: param until : if the callback returns True , stop sending and return
: return : the last True value the callback returns , or None''' | while True :
if until :
r = until ( )
if r :
return r
waiter = self . scheduler . send ( event )
if waiter is None :
break
await waiter |
def generate_labels_from_classifications ( classifications , timestamps ) :
"""This is to generate continuous segments out of classified small windows
: param classifications :
: param timestamps :
: return :""" | window_length = timestamps [ 1 ] - timestamps [ 0 ]
combo_list = [ ( classifications [ k ] , timestamps [ k ] ) for k in range ( 0 , len ( classifications ) ) ]
labels = [ ]
for k , g in itertools . groupby ( combo_list , lambda x : x [ 0 ] ) :
items = list ( g )
start_time = items [ 0 ] [ 1 ]
end_time = it... |
def retrieve ( url ) :
"""Retrieve and parse PEM - encoded X . 509 certificate chain .
See ` validate . request ` for additional info .
Args :
url : str . SignatureCertChainUrl header value sent by request .
Returns :
list or bool : If url is valid , returns the certificate chain as a list
of cryptograp... | try :
pem_data = urlopen ( url ) . read ( )
except ( ValueError , HTTPError ) :
warnings . warn ( 'Certificate URL is invalid.' )
return False
if sys . version >= '3' :
try :
pem_data = pem_data . decode ( )
except ( UnicodeDecodeError ) :
warnings . warn ( 'Certificate encoding is n... |
def checksuper ( sometext , interchange = ALL ) :
"""Checks that some text is superpalindrome . Checking performs case - insensitive
: param str sometext :
It is some string that will be checked for superpalindrome as text .
What is the text see at help ( palindromus . istext )
The text can be multiline .
... | def text_by_columns ( text , columns ) :
column_idx = 0
result_text = ""
while column_idx + 1 <= columns :
for idx in range ( columns ) :
result_text += text [ idx * columns + column_idx ]
column_idx += 1
return result_text
# check invalid data types
OnlyStringsCanBeChecked (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.