signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def metabolites_per_compartment ( model , compartment_id ) :
"""Identify all metabolites that belong to a given compartment .
Parameters
model : cobra . Model
The metabolic model under investigation .
compartment _ id : string
Model specific compartment identifier .
Returns
list
List of metabolites ... | return [ met for met in model . metabolites if met . compartment == compartment_id ] |
def _get_params ( self ) :
"""return the value of the parameters .""" | return np . hstack ( ( self . varianceU , self . varianceY , self . lengthscaleU , self . lengthscaleY ) ) |
def task_status ( request , task_id ) :
"""Returns task status and result in JSON format .""" | result = AsyncResult ( task_id )
state , retval = result . state , result . result
response_data = { 'id' : task_id , 'status' : state , 'result' : retval }
if state in states . EXCEPTION_STATES :
traceback = result . traceback
response_data . update ( { 'result' : safe_repr ( retval ) , 'exc' : get_full_cls_na... |
def drop_all ( self ) :
'''Drops all tables from this database''' | self . drop ( self . get_table_names ( ) )
if self . persistent :
with self . _lock :
try :
dbfolder = os . path . join ( self . root_dir , self . name )
if os . path . exists ( dbfolder ) and not os . listdir ( dbfolder ) :
rmtree ( dbfolder )
except ( IOErro... |
def has_attribute ( self , attribute : str ) -> bool :
"""Whether the node has an attribute with the given name .
Use only if is _ mapping ( ) returns True .
Args :
attribute : The name of the attribute to check for .
Returns :
True iff the attribute is present .""" | return any ( [ key_node . value == attribute for key_node , _ in self . yaml_node . value ] ) |
def mixin ( cls ) :
"""A decorator which adds event methods to a class giving it the ability to
bind to and trigger events
: param cls : the class to add the event logic to
: type cls : class
: return : the modified class
: rtype : class""" | cls . _events = { }
cls . bind = Pyevent . bind . __func__
cls . unbind = Pyevent . unbind . __func__
cls . trigger = Pyevent . trigger . __func__
return cls |
def do_remove ( config , config_dir ) :
"""CLI action " remove configuration " .""" | if not os . path . exists ( config_dir ) :
print "Configuration '{}' does not exist." . format ( config )
exit ( 1 )
if confirm ( "Confirm removal of the configuration '{}'" . format ( config ) ) :
shutil . rmtree ( config_dir )
print "Configuration '{}' has been removed." . format ( config )
else :
... |
def mdadm ( ) :
'''Return list of mdadm devices''' | devices = set ( )
try :
with salt . utils . files . fopen ( '/proc/mdstat' , 'r' ) as mdstat :
for line in mdstat :
line = salt . utils . stringutils . to_unicode ( line )
if line . startswith ( 'Personalities : ' ) :
continue
if line . startswith ( 'unuse... |
def string_to_config ( s ) :
"""s is a comma - separated list of stores .""" | from . machines import Configuration
s = lexer ( s )
x = parse_multiple ( s , parse_store )
parse_end ( s )
return Configuration ( x ) |
def guess_external_url ( local_host , port ) :
"""Return a URL that is most likely to route to ` local _ host ` from outside .
The point is that we may be running on a remote host from the user ' s
point of view , so they can ' t access ` local _ host ` from a Web browser just
by typing ` ` http : / / localho... | if local_host in [ '0.0.0.0' , '::' ] : # The server is listening on all interfaces , but we have to pick one .
# The system ' s FQDN should give us a hint .
local_host = socket . getfqdn ( )
# https : / / github . com / vfaronov / turq / issues / 9
match = IPV4_REVERSE_DNS . match ( local_host )
if mat... |
def copy ( self , * args , ** kwargs ) :
"""Copy the request and environment object .
This only does a shallow copy , except of wsgi . input""" | self . make_body_seekable ( )
env = self . environ . copy ( )
new_req = self . __class__ ( env , * args , ** kwargs )
new_req . copy_body ( )
new_req . identity = self . identity
return new_req |
def _hex_ids ( self , dev_list ) :
"""! Build a USBID map for a device list
@ param disk _ list List of disks in a system with USBID decoration
@ return Returns map USBID - > device file in / dev
@ details Uses regular expressions to get a USBID ( TargeTIDs ) a " by - id "
symbolic link""" | for dl in dev_list :
match = self . nlp . search ( dl )
if match :
yield match . group ( "usbid" ) , _readlink ( dl ) |
async def artwork ( self ) :
"""Return an image file ( png ) for what is currently playing .
None is returned if no artwork is available . Must be logged in .""" | art = await self . daap . get ( _ARTWORK_CMD , daap_data = False )
return art if art != b'' else None |
def encode ( self , o , depth = 0 ) :
"""encode the json object at given depth
: param o : the object
: param depth : the depth
: return : the json encoding""" | if isinstance ( o , OrderedDict ) :
return "{" + ",\n " . join ( [ self . encode ( k ) + ":" + self . encode ( v , depth + 1 ) for ( k , v ) in o . items ( ) ] ) + "}\n"
else :
return simplejson . JSONEncoder . encode ( self , o ) |
def boolean ( value ) :
"""Parse the string ` ` " true " ` ` or ` ` " false " ` ` as a boolean ( case
insensitive ) . Also accepts ` ` " 1 " ` ` and ` ` " 0 " ` ` as ` ` True ` ` / ` ` False ` `
( respectively ) . If the input is from the request JSON body , the type is
already a native python boolean , and w... | if isinstance ( value , bool ) :
return value
if not value :
raise ValueError ( "boolean type must be non-null" )
value = value . lower ( )
if value in ( 'true' , '1' , ) :
return True
if value in ( 'false' , '0' , ) :
return False
raise ValueError ( "Invalid literal for boolean(): {0}" . format ( value... |
def run ( self ) :
"""Fork , daemonize and invoke self . post _ fork _ child ( ) ( via ProcessManager ) .
The scheduler has thread pools which need to be re - initialized after a fork : this ensures that
when the pantsd - runner forks from pantsd , there is a working pool for any work that happens
in that chi... | fork_context = self . _graph_helper . scheduler_session . with_fork_context if self . _graph_helper else None
self . daemonize ( write_pid = False , fork_context = fork_context ) |
def _realpath ( fs , path , seen = pset ( ) ) :
""". . warning : :
The ` ` os . path ` ` module ' s realpath does not error or warn about
loops , but we do , following the behavior of GNU ` ` realpath ( 1 ) ` ` !""" | real = Path . root ( )
for segment in path . segments :
current = real / segment
seen = seen . add ( current )
while True :
try :
current = fs . readlink ( current )
except ( exceptions . FileNotFound , exceptions . NotASymlink ) :
break
else :
cur... |
def get_appliance_event_after_time ( self , location_id , since , per_page = None , page = None , min_power = None ) :
"""Get appliance events by location Id after defined time .
Args :
location _ id ( string ) : hexadecimal id of the sensor to query , e . g .
` ` 0x0013A20040B65FAD ` `
since ( string ) : I... | url = "https://api.neur.io/v1/appliances/events"
headers = self . __gen_headers ( )
headers [ "Content-Type" ] = "application/json"
params = { "locationId" : location_id , "since" : since }
if min_power :
params [ "minPower" ] = min_power
if per_page :
params [ "perPage" ] = per_page
if page :
params [ "pag... |
def get_stream_handle ( stream = sys . stdout ) :
"""Get the OS appropriate handle for the corresponding output stream .
: param str stream : The the stream to get the handle for
: return : A handle to the appropriate stream , either a ctypes buffer
or * * sys . stdout * * or * * sys . stderr * * .""" | handle = stream
if os . name == "nt" :
from . _winconsole import get_stream_handle as get_win_stream_handle
return get_win_stream_handle ( stream )
return handle |
def close_list ( ctx , root ) :
"""Close already opened list if needed .
This will try to see if it is needed to close already opened list .
: Args :
- ctx ( : class : ` Context ` ) : Context object
- root ( Element ) : lxml element representing current position .
: Returns :
lxml element where future c... | try :
n = len ( ctx . in_list )
if n <= 0 :
return root
elem = root
while n > 0 :
while True :
if elem . tag in [ 'ul' , 'ol' , 'td' ] :
elem = elem . getparent ( )
break
elem = elem . getparent ( )
n -= 1
ctx . in_list ... |
def get_obsmeta ( self , lcid ) :
"""Get the observation metadata for the given id .
This is table 3 of Sesar 2010""" | if self . _obsdata is None :
self . _obsdata = fetch_rrlyrae_fitdata ( )
i = np . where ( self . _obsdata [ 'id' ] == lcid ) [ 0 ]
if len ( i ) == 0 :
raise ValueError ( "invalid lcid: {0}" . format ( lcid ) )
return self . _obsdata [ i [ 0 ] ] |
def _edit_name ( name , code , add_code = None , delete_end = False ) :
"""Helping function for creating file names in . SAFE format
: param name : initial string
: type name : str
: param code :
: type code : str
: param add _ code :
: type add _ code : str or None
: param delete _ end :
: type del... | info = name . split ( '_' )
info [ 2 ] = code
if add_code is not None :
info [ 3 ] = add_code
if delete_end :
info . pop ( )
return '_' . join ( info ) |
def bin ( values , bins , labels = None ) :
"""Bins data into declared bins
Bins data into declared bins . By default each bin is labelled
with bin center values but an explicit list of bin labels may be
defined .
Args :
values : Array of values to be binned
bins : List or array containing the bin bound... | bins = np . asarray ( bins )
if labels is None :
labels = ( bins [ : - 1 ] + np . diff ( bins ) / 2. )
else :
labels = np . asarray ( labels )
dtype = 'float' if labels . dtype . kind == 'f' else 'O'
binned = np . full_like ( values , ( np . nan if dtype == 'f' else None ) , dtype = dtype )
for lower , upper , ... |
def get_assessments_by_bank ( self , bank_id ) :
"""Gets the list of ` ` Assessments ` ` associated with a ` ` Bank ` ` .
arg : bank _ id ( osid . id . Id ) : ` ` Id ` ` of the ` ` Bank ` `
return : ( osid . assessment . AssessmentList ) - list of related
assessments
raise : NotFound - ` ` bank _ id ` ` is ... | # Implemented from template for
# osid . resource . ResourceBinSession . get _ resources _ by _ bin
mgr = self . _get_provider_manager ( 'ASSESSMENT' , local = True )
lookup_session = mgr . get_assessment_lookup_session_for_bank ( bank_id , proxy = self . _proxy )
lookup_session . use_isolated_bank_view ( )
return look... |
def addSlider3D ( self , sliderfunc , pos1 , pos2 , xmin , xmax , value = None , s = 0.03 , title = "" , rotation = 0 , c = None , showValue = True , ) :
"""Add a 3D slider widget which can call an external custom function .
: param sliderfunc : external function to be called by the widget
: param list pos1 : f... | return addons . addSlider3D ( sliderfunc , pos1 , pos2 , xmin , xmax , value , s , title , rotation , c , showValue ) |
def enhance ( self ) :
"""Load metadata from a data service to improve naming .
: raises tvrenamer . exceptions . ShowNotFound :
when unable to find show / series name based on parsed name
: raises tvrenamer . exceptions . EpisodeNotFound :
when unable to find episode name ( s ) based on parsed data""" | series , error = self . api . get_series_by_name ( self . series_name )
if series is None :
self . messages . append ( str ( error ) )
LOG . info ( self . messages [ - 1 ] )
raise exc . ShowNotFound ( str ( error ) )
self . series_name = self . api . get_series_name ( series )
self . episode_names , error =... |
def _decimal_to_xsd_format ( value ) :
"""Converts a decimal . Decimal value to its XSD decimal type value .
Result is a string containing the XSD decimal type ' s lexical value
representation . The conversion is done without any precision loss .
Note that Python ' s native decimal . Decimal string representa... | value = XDecimal . _decimal_canonical ( value )
negative , digits , exponent = value . as_tuple ( )
# The following implementation assumes the following tuple decimal
# encoding ( part of the canonical decimal value encoding ) :
# - digits must contain at least one element
# - no leading integral 0 digits except a sing... |
def typeahead ( self , workspace , params = { } , ** options ) :
"""Retrieves objects in the workspace based on an auto - completion / typeahead
search algorithm . This feature is meant to provide results quickly , so do
not rely on this API to provide extremely accurate search results . The
result set is lim... | path = "/workspaces/%s/typeahead" % ( workspace )
return self . client . get_collection ( path , params , ** options ) |
def get_valid_residue ( residue ) :
"""Check if the given string represents a valid amino acid residue .""" | if residue is not None and amino_acids . get ( residue ) is None :
res = amino_acids_reverse . get ( residue . lower ( ) )
if res is None :
raise InvalidResidueError ( residue )
else :
return res
return residue |
def _factorize_from_iterables ( iterables ) :
"""A higher - level wrapper over ` _ factorize _ from _ iterable ` .
* This is an internal function *
Parameters
iterables : list - like of list - likes
Returns
codes _ list : list of ndarrays
categories _ list : list of Indexes
Notes
See ` _ factorize _... | if len ( iterables ) == 0 : # For consistency , it should return a list of 2 lists .
return [ [ ] , [ ] ]
return map ( list , lzip ( * [ _factorize_from_iterable ( it ) for it in iterables ] ) ) |
def run_region ( data , region , vrn_files , out_file ) :
"""Perform variant calling on gVCF inputs in a specific genomic region .""" | broad_runner = broad . runner_from_config ( data [ "config" ] )
if broad_runner . gatk_type ( ) == "gatk4" :
genomics_db = _run_genomicsdb_import ( vrn_files , region , out_file , data )
return _run_genotype_gvcfs_genomicsdb ( genomics_db , region , out_file , data )
else :
vrn_files = _batch_gvcfs ( data ,... |
def directory ( name , user = None , group = None , recurse = None , max_depth = None , dir_mode = None , file_mode = None , makedirs = False , clean = False , require = None , exclude_pat = None , follow_symlinks = False , force = False , backupname = None , allow_symlink = True , children_only = False , win_owner = N... | name = os . path . expanduser ( name )
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
if not name :
return _error ( ret , 'Must provide name to file.directory' )
# Remove trailing slash , if present and we ' re not working on " / " itself
if name [ - 1 ] == '/' and name != '/' :
na... |
def parse_external_id ( output , type = EXTERNAL_ID_TYPE_ANY ) :
"""Attempt to parse the output of job submission commands for an external id . _ _ doc _ _
> > > parse _ external _ id ( " 12345 . pbsmanager " )
'12345 . pbsmanager '
> > > parse _ external _ id ( ' Submitted batch job 185 ' )
'185'
> > > p... | external_id = None
for pattern_type , pattern in EXTERNAL_ID_PATTERNS :
if type != EXTERNAL_ID_TYPE_ANY and type != pattern_type :
continue
match = search ( pattern , output )
if match :
external_id = match . group ( 1 )
break
return external_id |
def _container_getitem ( instance , elts , index , context = None ) :
"""Get a slice or an item , using the given * index * , for the given sequence .""" | try :
if isinstance ( index , Slice ) :
index_slice = _infer_slice ( index , context = context )
new_cls = instance . __class__ ( )
new_cls . elts = elts [ index_slice ]
new_cls . parent = instance . parent
return new_cls
if isinstance ( index , Const ) :
return e... |
def _prepare_wsdl_objects ( self ) :
"""Create the data structure and get it ready for the WSDL request .""" | self . CarrierCode = 'FDXE'
self . Origin = self . client . factory . create ( 'Address' )
self . Destination = self . client . factory . create ( 'Address' )
self . ShipDate = datetime . date . today ( ) . isoformat ( )
self . Service = None
self . Packaging = 'YOUR_PACKAGING' |
def capzone ( self , nt = 10 , zstart = None , hstepmax = 10 , vstepfrac = 0.2 , tmax = None , nstepmax = 100 , silent = '.' ) :
"""Compute a capture zone
Parameters
nt : int
number of path lines
zstart : scalar
starting elevation of the path lines
hstepmax : scalar
maximum step in horizontal space
... | xstart , ystart , zstart = self . capzonestart ( nt , zstart )
xyzt = timtracelines ( self . model , xstart , ystart , zstart , - np . abs ( hstepmax ) , vstepfrac = 0.2 , tmax = tmax , nstepmax = 100 , silent = '.' )
return xyzt |
def get_data ( self ) :
"""reads data from current WD measurement . txt or magic _ measurements . txt
depending on data model and sorts it into main measurements data
structures given bellow :
Data - { specimen : {
zijdblock : [ [ treatment temp - str , dec - float , inc - float ,
mag _ moment - float , Z... | # Read magic measurement file and sort to blocks
# All meas data information is stored in Data [ secimen ] = { }
Data = { }
Data_hierarchy = { }
Data_hierarchy [ 'study' ] = { }
Data_hierarchy [ 'locations' ] = { }
Data_hierarchy [ 'sites' ] = { }
Data_hierarchy [ 'samples' ] = { }
Data_hierarchy [ 'specimens' ] = { }
... |
def get_locale_choices ( locale_dir ) :
"""Get a list of locale file names in the given locale dir .""" | file_name_s = os . listdir ( locale_dir )
choice_s = [ ]
for file_name in file_name_s :
if file_name . endswith ( I18n . TT_FILE_EXT_STXT ) :
file_name_noext , _ = os . path . splitext ( file_name )
if file_name_noext :
choice_s . append ( file_name_noext )
choice_s = sorted ( choice_s )... |
def create_epub ( ident_hash , file , format = 'raw' ) :
"""Creates an epub from an ` ` ident _ hash ` ` , which is output to the given
` ` file ` ` ( a file - like object ) .
Returns None , writes to the given ` ` file ` ` .""" | model = factory ( ident_hash , baked = ( format != 'raw' ) )
if isinstance ( model , cnxepub . Document ) :
model = cnxepub . TranslucentBinder ( nodes = [ model ] )
cnxepub . make_epub ( model , file ) |
def _strip_top_comments ( lines : Sequence [ str ] , line_separator : str ) -> str :
"""Strips # comments that exist at the top of the given lines""" | lines = copy . copy ( lines )
while lines and lines [ 0 ] . startswith ( "#" ) :
lines = lines [ 1 : ]
return line_separator . join ( lines ) |
def get_stoch ( self , symbol , interval = 'daily' , fastkperiod = None , slowkperiod = None , slowdperiod = None , slowkmatype = None , slowdmatype = None ) :
"""Return the stochatic oscillator values in two
json objects as data and meta _ data . It raises ValueError when problems
arise
Keyword Arguments :
... | _FUNCTION_KEY = "STOCH"
return _FUNCTION_KEY , 'Technical Analysis: STOCH' , 'Meta Data' |
def thermostat_states ( self ) :
""": return : A list of thermostatstate object modeled as named tuples""" | return [ ThermostatState ( STATES [ state . get ( 'id' ) ] , state . get ( 'id' ) , state . get ( 'tempValue' ) , state . get ( 'dhw' ) ) for state in self . _state [ 'thermostatStates' ] [ 'state' ] ] |
def n_bifurcation_points ( neurites , neurite_type = NeuriteType . all ) :
'''number of bifurcation points in a collection of neurites''' | return n_sections ( neurites , neurite_type = neurite_type , iterator_type = Tree . ibifurcation_point ) |
def generate_type ( self ) :
"""Validation of type . Can be one type or list of types .
Since draft 06 a float without fractional part is an integer .
. . code - block : : python
{ ' type ' : ' string ' }
{ ' type ' : [ ' string ' , ' number ' ] }""" | types = enforce_list ( self . _definition [ 'type' ] )
try :
python_types = ', ' . join ( JSON_TYPE_TO_PYTHON_TYPE [ t ] for t in types )
except KeyError as exc :
raise JsonSchemaDefinitionException ( 'Unknown type: {}' . format ( exc ) )
extra = ''
if 'integer' in types :
extra += ' and not (isinstance({va... |
def create ( cls , name , user = None , network_element = None , domain_name = None , zone = None , executable = None ) :
"""Create a match expression
: param str name : name of match expression
: param str user : name of user or user group
: param Element network _ element : valid network element type , i . ... | ref_list = [ ]
if user :
pass
if network_element :
ref_list . append ( network_element . href )
if domain_name :
ref_list . append ( domain_name . href )
if zone :
ref_list . append ( zone . href )
if executable :
pass
json = { 'name' : name , 'ref' : ref_list }
return ElementCreator ( cls , json ) |
def adapt_single_html ( html ) :
"""Adapts a single html document generated by
` ` . formatters . SingleHTMLFormatter ` ` to a ` ` models . Binder ` `""" | html_root = etree . fromstring ( html )
metadata = parse_metadata ( html_root . xpath ( '//*[@data-type="metadata"]' ) [ 0 ] )
id_ = metadata [ 'cnx-archive-uri' ] or 'book'
binder = Binder ( id_ , metadata = metadata )
nav_tree = parse_navigation_html_to_tree ( html_root , id_ )
body = html_root . xpath ( '//xhtml:bod... |
def get_dimension_indices ( self , query ) :
"""Converts a dimension / category list of dicts into a list of dimensions ’ indices .
Args :
query ( list ) : dimension / category list of dicts .
Returns :
indices ( list ) : list of dimensions ' indices .""" | ids = self [ 'id' ] if self . get ( 'id' ) else self [ 'dimension' ] [ 'id' ]
indices = [ ]
for idx , id in enumerate ( ids ) :
indices . append ( self . get_dimension_index ( id , [ d . get ( id ) for d in query if id in d ] [ 0 ] ) )
return indices |
def parse ( self , arguments ) :
"""Parses one or more arguments with the installed parser .
Args :
arguments : a single argument or a list of arguments ( typically a
list of default values ) ; a single argument is converted
internally into a list containing one item .""" | if not isinstance ( arguments , list ) : # Default value may be a list of values . Most other arguments
# will not be , so convert them into a single - item list to make
# processing simpler below .
arguments = [ arguments ]
if self . present : # keep a backup reference to list of previously supplied option values
... |
def _remap_pair ( self , operation , src , dst , * args , ** kw ) :
"""Called for path pairs like rename , link , and symlink operations""" | if not self . _ok ( src ) or not self . _ok ( dst ) :
self . _violation ( operation , src , dst , * args , ** kw )
return ( src , dst ) |
def replace_in_files ( dirname , replace ) :
"""Replace current version with new version in requirements files .""" | filepath = os . path . abspath ( dirname / "requirements.in" )
if os . path . isfile ( filepath ) and header_footer_exists ( filepath ) :
replaced = re . sub ( Utils . exp , replace , get_file_string ( filepath ) )
with open ( filepath , "w" ) as f :
f . write ( replaced )
print ( color ( "Written t... |
async def rotate_slaves ( self ) :
"Round - robin slave balancer" | slaves = await self . sentinel_manager . discover_slaves ( self . service_name )
slave_address = list ( )
if slaves :
if self . slave_rr_counter is None :
self . slave_rr_counter = random . randint ( 0 , len ( slaves ) - 1 )
for _ in range ( len ( slaves ) ) :
self . slave_rr_counter = ( self . ... |
def ParseOptions ( cls , options , configuration_object ) :
"""Parses and validates options .
Args :
options ( argparse . Namespace ) : parser options .
configuration _ object ( CLITool ) : object to be configured by the argument
helper .
Raises :
BadConfigObject : when the configuration object is of th... | if not isinstance ( configuration_object , tools . CLITool ) :
raise errors . BadConfigObject ( 'Configuration object is not an instance of CLITool' )
profilers = cls . _ParseStringOption ( options , 'profilers' )
if not profilers :
profilers = set ( )
elif profilers . lower ( ) != 'list' :
profilers = set ... |
def trail ( self ) :
"""Return an ( N , 2 ) array of mouse coordinates for every event in the
current mouse drag operation .
Returns None if there is no current drag operation .""" | events = self . drag_events ( )
if events is None :
return None
trail = np . empty ( ( len ( events ) , 2 ) , dtype = int )
for i , ev in enumerate ( events ) :
trail [ i ] = ev . pos
return trail |
def start ( self ) :
"""Commence audio processing .
If successful , the stream is considered active .""" | err = _pa . Pa_StartStream ( self . _stream )
if err == _pa . paStreamIsNotStopped :
return
self . _handle_error ( err ) |
def rev_comp ( seq , molecule = 'dna' ) :
"""DNA | RNA seq - > reverse complement""" | if molecule == 'dna' :
nuc_dict = { "A" : "T" , "B" : "V" , "C" : "G" , "D" : "H" , "G" : "C" , "H" : "D" , "K" : "M" , "M" : "K" , "N" : "N" , "R" : "Y" , "S" : "S" , "T" : "A" , "V" : "B" , "W" : "W" , "Y" : "R" }
elif molecule == 'rna' :
nuc_dict = { "A" : "U" , "B" : "V" , "C" : "G" , "D" : "H" , "G" : "C" ... |
def get_vector ( self , lr_motor : float , rr_motor : float , lf_motor : float , rf_motor : float ) -> typing . Tuple [ float , float , float ] :
"""Given motor values , retrieves the vector of ( distance , speed ) for your robot
: param lr _ motor : Left rear motor value ( - 1 to 1 ) ; 1 is forward
: param rr ... | # From http : / / www . chiefdelphi . com / media / papers / download / 2722 pp7-9
# [ F ] [ omega ] ( r ) = [ V ]
# F is
# .25 . 25 . 25 . 25
# - . 25 . 25 - . 25 . 25
# - . 25k - . 25k . 25k . 25k
# omega is
# [ lf lr rr rf ]
if self . deadzone :
lf_motor = self . deadzone ( lf_motor )
lr_motor = self . deadz... |
def generate_sample_cdk_py_module ( env_root , module_dir = None ) :
"""Generate skeleton CDK python sample module .""" | if module_dir is None :
module_dir = os . path . join ( env_root , 'sampleapp.cdk' )
generate_sample_module ( module_dir )
for i in [ 'app.py' , 'cdk.json' , 'lambda-index.py' , 'package.json' , 'runway.module.yml' , 'Pipfile' ] :
shutil . copyfile ( os . path . join ( ROOT , 'templates' , 'cdk-py' , i ) , os .... |
def _search ( self , u , start_dim , total_dim , n_add ) :
"""Search the graph for all the layers to be widened caused by an operation .
It is an recursive function with duplication check to avoid deadlock .
It searches from a starting node u until the corresponding layers has been widened .
Args :
u : The ... | if ( u , start_dim , total_dim , n_add ) in self . vis :
return
self . vis [ ( u , start_dim , total_dim , n_add ) ] = True
for v , layer_id in self . adj_list [ u ] :
layer = self . layer_list [ layer_id ]
if is_layer ( layer , "Conv" ) :
new_layer = wider_next_conv ( layer , start_dim , total_dim ... |
def _sub_latlon ( self , other ) :
'''Called when subtracting a LatLon object from self''' | inv = self . _pyproj_inv ( other )
heading = inv [ 'heading_reverse' ]
distance = inv [ 'distance' ]
return GeoVector ( initial_heading = heading , distance = distance ) |
def get_bundle_by_name ( self , bundle_name ) : # type : ( str ) - > Optional [ Bundle ]
"""Retrieves the bundle with the given name
: param bundle _ name : Name of the bundle to look for
: return : The requested bundle , None if not found""" | if bundle_name is None : # Nothing to do
return None
if bundle_name is self . get_symbolic_name ( ) : # System bundle requested
return self
with self . __bundles_lock :
for bundle in self . __bundles . values ( ) :
if bundle_name == bundle . get_symbolic_name ( ) : # Found !
return bundl... |
def write_pagerange ( self , pagerange , prefix = '' ) :
"""Save the subset of pages specified in ` pagerange ` ( dict ) as separate PDF .
e . g . pagerange = { ' title ' : ' First chapter ' , ' page _ start ' : 0 , ' page _ end ' : 5}""" | writer = PdfFileWriter ( )
slug = "" . join ( [ c for c in pagerange [ 'title' ] . replace ( " " , "-" ) if c . isalnum ( ) or c == "-" ] )
write_to_path = os . path . sep . join ( [ self . directory , "{}{}.pdf" . format ( prefix , slug ) ] )
for page in range ( pagerange [ 'page_start' ] , pagerange [ 'page_end' ] ) ... |
def _flush_index ( self ) :
"""Writes the current list of file paths in the index to the json file
and then sets self . _ _ index = None .""" | data = { 'version' : self . version , 'index' : self . _index }
with open ( self . _get_path ( 'index.json' ) , 'w' ) as f :
json . dump ( data , f )
self . __index = None |
def _fetch ( self , params , required , defaults ) :
"""Make the NVP request and store the response .""" | defaults . update ( params )
pp_params = self . _check_and_update_params ( required , defaults )
pp_string = self . signature + urlencode ( pp_params )
response = self . _request ( pp_string )
response_params = self . _parse_response ( response )
log . debug ( 'PayPal Request:\n%s\n' , pprint . pformat ( defaults ) )
l... |
def _create_network_backing ( network_name , switch_type , parent_ref ) :
'''Returns a vim . vm . device . VirtualDevice . BackingInfo object specifying a
virtual ethernet card backing information
network _ name
string , network name
switch _ type
string , type of switch
parent _ ref
Parent reference ... | log . trace ( 'Configuring virtual machine network backing network_name=%s ' 'switch_type=%s parent=%s' , network_name , switch_type , salt . utils . vmware . get_managed_object_name ( parent_ref ) )
backing = { }
if network_name :
if switch_type == 'standard' :
networks = salt . utils . vmware . get_networ... |
def generate_key ( ctx , slot , public_key_output , management_key , pin , algorithm , format , pin_policy , touch_policy ) :
"""Generate an asymmetric key pair .
The private key is generated on the YubiKey , and written to one of the
slots .
SLOT PIV slot where private key should be stored .
PUBLIC - KEY F... | dev = ctx . obj [ 'dev' ]
controller = ctx . obj [ 'controller' ]
_ensure_authenticated ( ctx , controller , pin , management_key )
algorithm_id = ALGO . from_string ( algorithm )
if pin_policy :
pin_policy = PIN_POLICY . from_string ( pin_policy )
if touch_policy :
touch_policy = TOUCH_POLICY . from_string ( t... |
def ecef_to_geodetic ( x , y , z , method = None ) :
"""Convert ECEF into Geodetic WGS84 coordinates
Parameters
x : float or array _ like
ECEF - X in km
y : float or array _ like
ECEF - Y in km
z : float or array _ like
ECEF - Z in km
method : ' iterative ' or ' closed ' ( ' closed ' is deafult )
... | # quick notes on ECEF to Geodetic transformations
# http : / / danceswithcode . net / engineeringnotes / geodetic _ to _ ecef / geodetic _ to _ ecef . html
method = method or 'closed'
# ellipticity of Earth
ellip = np . sqrt ( 1. - earth_b ** 2 / earth_a ** 2 )
# first eccentricity squared
e2 = ellip ** 2
# 6.694379990... |
def create ( name , profile ) :
'''Create the named vm
CLI Example :
. . code - block : : bash
salt < minion - id > saltcloud . create webserver rackspace _ centos _ 512''' | cmd = 'salt-cloud --out json -p {0} {1}' . format ( profile , name )
out = __salt__ [ 'cmd.run_stdout' ] ( cmd , python_shell = False )
try :
ret = salt . utils . json . loads ( out )
except ValueError :
ret = { }
return ret |
def main ( model_folder , override = False ) :
"""Parse the info . yml from ` ` model _ folder ` ` and create the model file .""" | model_description_file = os . path . join ( model_folder , "info.yml" )
# Read the model description file
with open ( model_description_file , 'r' ) as ymlfile :
model_description = yaml . load ( ymlfile )
project_root = utils . get_project_root ( )
# Read the feature description file
feature_folder = os . path . j... |
def log_to_ganttplot ( execution_history_items ) :
"""Example how to use the DataFrame representation""" | import matplotlib . pyplot as plt
import matplotlib . dates as dates
import numpy as np
d = log_to_DataFrame ( execution_history_items )
# de - duplicate states and make mapping from state to idx
unique_states , idx = np . unique ( d . path_by_name , return_index = True )
ordered_unique_states = np . array ( d . path_b... |
def set_app_id ( self , id , version , icon ) :
'''Sets some meta - information about the application .
See also L { set _ user _ agent } ( ) .
@ param id : Java - style application identifier , e . g . " com . acme . foobar " .
@ param version : application version numbers , e . g . " 1.2.3 " .
@ param ico... | return libvlc_set_app_id ( self , str_to_bytes ( id ) , str_to_bytes ( version ) , str_to_bytes ( icon ) ) |
def send_api_request ( self , method , url , params = { } , valid_parameters = [ ] , needs_api_key = False ) :
"""Sends the url with parameters to the requested url , validating them
to make sure that they are what we expect to have passed to us
: param method : a string , the request method you want to make
... | if needs_api_key :
params . update ( { 'api_key' : self . request . consumer_key } )
valid_parameters . append ( 'api_key' )
files = { }
if 'data' in params :
if isinstance ( params [ 'data' ] , list ) :
for idx , data in enumerate ( params [ 'data' ] ) :
files [ 'data[' + str ( idx ) + ... |
def filename_to_url ( filename : str , cache_dir : str = None ) -> Tuple [ str , str ] :
"""Return the url and etag ( which may be ` ` None ` ` ) stored for ` filename ` .
Raise ` ` FileNotFoundError ` ` if ` filename ` or its stored metadata do not exist .""" | if cache_dir is None :
cache_dir = CACHE_DIRECTORY
cache_path = os . path . join ( cache_dir , filename )
if not os . path . exists ( cache_path ) :
raise FileNotFoundError ( "file {} not found" . format ( cache_path ) )
meta_path = cache_path + '.json'
if not os . path . exists ( meta_path ) :
raise FileNo... |
def contribute_to_class ( self , process , fields , name ) :
"""Register this field with a specific process .
: param process : Process descriptor instance
: param fields : Fields registry to use
: param name : Field name""" | super ( ) . contribute_to_class ( process , fields , name )
self . inner . name = name
self . inner . process = process |
def create_one_index ( self , instance , update = False , delete = False , commit = True ) :
''': param instance : sqlalchemy instance object
: param update : when update is True , use ` update _ document ` , default ` False `
: param delete : when delete is True , use ` delete _ by _ term ` with id ( primary k... | if update and delete :
raise ValueError ( "update and delete can't work togther" )
table = instance . __class__
ix = self . _index ( table )
searchable = ix . fields
attrs = { DEFAULT_PRIMARY_KEY : str ( instance . id ) }
for field in searchable :
if '.' in field :
attrs [ field ] = str ( relation_colum... |
def create_model_from_job ( self , training_job_name , name = None , role = None , primary_container_image = None , model_data_url = None , env = None , vpc_config_override = vpc_utils . VPC_CONFIG_DEFAULT ) :
"""Create an Amazon SageMaker ` ` Model ` ` from a SageMaker Training Job .
Args :
training _ job _ na... | training_job = self . sagemaker_client . describe_training_job ( TrainingJobName = training_job_name )
name = name or training_job_name
role = role or training_job [ 'RoleArn' ]
env = env or { }
primary_container = container_def ( primary_container_image or training_job [ 'AlgorithmSpecification' ] [ 'TrainingImage' ] ... |
def ColorLuminance ( color ) :
"""Compute the brightness of an sRGB color using the formula from
http : / / www . w3 . org / TR / 2000 / WD - AERT - 20000426 # color - contrast .
Args :
color : a string of 6 hex digits in the format verified by IsValidHexColor ( ) .
Returns :
A floating - point number bet... | r = int ( color [ 0 : 2 ] , 16 )
g = int ( color [ 2 : 4 ] , 16 )
b = int ( color [ 4 : 6 ] , 16 )
return ( 299 * r + 587 * g + 114 * b ) / 1000.0 |
def cache_key ( self , request , method = None ) :
"""the cache key is the absolute uri and the request method""" | if method is None :
method = request . method
return "bettercache_page:%s:%s" % ( request . build_absolute_uri ( ) , method ) |
def execute_script ( self , name , keys , * args , ** options ) :
'''Execute a script .
makes sure all required scripts are loaded .''' | script = get_script ( name )
if not script :
raise redis . RedisError ( 'No such script "%s"' % name )
address = self . address ( )
if address not in all_loaded_scripts :
all_loaded_scripts [ address ] = set ( )
loaded = all_loaded_scripts [ address ]
toload = script . required_scripts . difference ( loaded )
f... |
def configure_logger ( self , name , config , incremental = False ) :
"""Configure a non - root logger from a dictionary .""" | logger = logging . getLogger ( name )
self . common_logger_config ( logger , config , incremental )
propagate = config . get ( 'propagate' , None )
if propagate is not None :
logger . propagate = propagate |
def parse_tag ( tag ) :
"""Parse the syntax of a language tag , without looking up anything in the
registry , yet . Returns a list of ( type , value ) tuples indicating what
information will need to be looked up .""" | tag = normalize_characters ( tag )
if tag in EXCEPTIONS :
return [ ( 'grandfathered' , tag ) ]
else : # The first subtag is always either the language code , or ' x ' to mark
# the entire tag as private - use . Other subtags are distinguished
# by their length and format , but the language code is distinguished
# e... |
def prepare_token_request ( self , token_url , authorization_response = None , redirect_url = None , state = None , body = '' , ** kwargs ) :
"""Prepare a token creation request .
Note that these requests usually require client authentication , either
by including client _ id or a set of provider specific authe... | if not is_secure_transport ( token_url ) :
raise InsecureTransportError ( )
state = state or self . state
if authorization_response :
self . parse_request_uri_response ( authorization_response , state = state )
self . redirect_url = redirect_url or self . redirect_url
body = self . prepare_request_body ( body =... |
def stem ( self , p , metadata = None ) :
"""In stem ( p , i , j ) , p is a char pointer , and the string to be stemmed
is from p [ i ] to p [ j ] inclusive . Typically i is zero and j is the
offset to the last character of a string , ( p [ j + 1 ] = = ' \0 ' ) . The
stemmer adjusts the characters p [ i ] . .... | # TODO : removed i and j from the original implementation
# to comply with the ` token . update ` API
i = 0
j = len ( p ) - 1
# copy the parameters into statics
self . b = p
self . k = j
self . k0 = i
if self . k <= self . k0 + 1 :
return self . b
# - - DEPARTURE - -
# With this line , strings of length 1 or 2 don ... |
def scrypt_mcf ( password , salt = None , N = SCRYPT_N , r = SCRYPT_r , p = SCRYPT_p , prefix = SCRYPT_MCF_PREFIX_DEFAULT ) :
"""Derives a Modular Crypt Format hash using the scrypt KDF
Parameter space is smaller than for scrypt ( ) :
N must be a power of two larger than 1 but no larger than 2 * * 31
r and p ... | if ( prefix != SCRYPT_MCF_PREFIX_s1 and prefix != SCRYPT_MCF_PREFIX_ANY ) :
return mcf_mod . scrypt_mcf ( scrypt , password , salt , N , r , p , prefix )
if isinstance ( password , unicode ) :
password = password . encode ( 'utf8' )
elif not isinstance ( password , bytes ) :
raise TypeError ( 'password must... |
def rescan_hba ( kwargs = None , call = None ) :
'''To rescan a specified HBA or all the HBAs on the Host System
CLI Example :
. . code - block : : bash
salt - cloud - f rescan _ hba my - vmware - config host = " hostSystemName "
salt - cloud - f rescan _ hba my - vmware - config hba = " hbaDeviceName " hos... | if call != 'function' :
raise SaltCloudSystemExit ( 'The rescan_hba function must be called with ' '-f or --function.' )
hba = kwargs . get ( 'hba' ) if kwargs and 'hba' in kwargs else None
host_name = kwargs . get ( 'host' ) if kwargs and 'host' in kwargs else None
if not host_name :
raise SaltCloudSystemExit ... |
def get_X_gradients ( self , X ) :
"""Get the gradients of the posterior distribution of X in its specific form .""" | return X . mean . gradient , X . variance . gradient , X . binary_prob . gradient |
def toggle_pawn_cfg ( self ) :
"""Show or hide the pop - over where you can configure the dummy pawn""" | if self . app . manager . current == 'pawncfg' :
dummything = self . app . dummything
self . ids . thingtab . remove_widget ( dummything )
dummything . clear ( )
if self . app . pawncfg . prefix :
dummything . prefix = self . app . pawncfg . prefix
dummything . num = dummynum ( self . ap... |
def get_venue_details ( self , venue_id ) :
'''a method to retrieve venue details from meetup api
: param venue _ id : integer for meetup id for venue
: return : dictionary with venue details inside [ json ] key
venue _ details = self . objects . venue . schema''' | title = '%s.get_venue_details' % self . __class__ . __name__
# validate inputs
input_fields = { 'venue_id' : venue_id }
for key , value in input_fields . items ( ) :
if value :
object_title = '%s(%s=%s)' % ( title , key , str ( value ) )
self . fields . validate ( value , '.%s' % key , object_title ... |
def update ( self , visualization ) :
"""Updates existing visualization
: param visualization : instance of Visualization that was previously loaded
: return :""" | res = self . es . update ( index = self . index , id = visualization . id , doc_type = self . doc_type , body = { 'doc' : visualization . to_kibana ( ) } , refresh = True )
return res |
def delete ( cls , repo , * heads , ** kwargs ) :
"""Delete the given heads
: param force :
If True , the heads will be deleted even if they are not yet merged into
the main development stream .
Default False""" | force = kwargs . get ( "force" , False )
flag = "-d"
if force :
flag = "-D"
repo . git . branch ( flag , * heads ) |
def swapaxes ( vari , ax1 , ax2 ) :
"""Interchange two axes of a polynomial .""" | if isinstance ( vari , Poly ) :
core = vari . A . copy ( )
for key in vari . keys :
core [ key ] = swapaxes ( core [ key ] , ax1 , ax2 )
return Poly ( core , vari . dim , None , vari . dtype )
return numpy . swapaxes ( vari , ax1 , ax2 ) |
def pairs ( sel , excluded_neighbors = 0 ) :
"""Creates all pairs between indexes . Will exclude closest neighbors up to : py : obj : ` excluded _ neighbors `
The self - pair ( i , i ) is always excluded
Parameters
sel : ndarray ( ( n ) , dtype = int )
array with selected atom indexes
excluded _ neighbors... | assert isinstance ( excluded_neighbors , int )
p = [ ]
for i in range ( len ( sel ) ) :
for j in range ( i + 1 , len ( sel ) ) : # get ordered pair
I = sel [ i ]
J = sel [ j ]
if ( I > J ) :
I = sel [ j ]
J = sel [ i ]
# exclude 1 and 2 neighbors
if ( ... |
def readlines ( self , size = None ) :
"""Reads a file into a list of strings . It calls : meth : ` readline `
until the file is read to the end . It does support the optional
` size ` argument if the underlaying stream supports it for
` readline ` .""" | last_pos = self . _pos
result = [ ]
if size is not None :
end = min ( self . limit , last_pos + size )
else :
end = self . limit
while 1 :
if size is not None :
size -= last_pos - self . _pos
if self . _pos >= end :
break
result . append ( self . readline ( size ) )
if size is no... |
def pack_tuple ( self , values ) :
"""Pack tuple of values
< tuple > : : = < cardinality > < field > +
: param value : tuple to be packed
: type value : tuple of scalar values ( bytes , str or int )
: return : packed tuple
: rtype : bytes""" | assert isinstance ( values , ( tuple , list ) )
cardinality = [ struct_L . pack ( len ( values ) ) ]
packed_items = [ self . pack_field ( v ) for v in values ]
return b'' . join ( itertools . chain ( cardinality , packed_items ) ) |
def groupBy ( self , * cols ) :
"""Groups the : class : ` DataFrame ` using the specified columns ,
so we can run aggregation on them . See : class : ` GroupedData `
for all the available aggregate functions .
: func : ` groupby ` is an alias for : func : ` groupBy ` .
: param cols : list of columns to grou... | jgd = self . _jdf . groupBy ( self . _jcols ( * cols ) )
from pyspark . sql . group import GroupedData
return GroupedData ( jgd , self ) |
def subject_areas ( self ) :
"""List of named tuples of subject areas in the form
( area , abbreviation , code ) of author ' s publication .""" | path = [ 'subject-areas' , 'subject-area' ]
area = namedtuple ( 'Subjectarea' , 'area abbreviation code' )
areas = [ area ( area = item [ '$' ] , code = item [ '@code' ] , abbreviation = item [ '@abbrev' ] ) for item in chained_get ( self . _json , path , [ ] ) ]
return areas or None |
def detect_and_visualize ( self , im_list , root_dir = None , extension = None , classes = [ ] , thresh = 0.6 , show_timer = False ) :
"""wrapper for im _ detect and visualize _ detection
Parameters :
im _ list : list of str or str
image path or list of image paths
root _ dir : str or None
directory of in... | dets = self . im_detect ( im_list , root_dir , extension , show_timer = show_timer )
if not isinstance ( im_list , list ) :
im_list = [ im_list ]
assert len ( dets ) == len ( im_list )
for k , det in enumerate ( dets ) :
img = cv2 . imread ( im_list [ k ] )
img = cv2 . cvtColor ( img , cv2 . COLOR_BGR2RGB )... |
def vinet_dPdV ( v , v0 , k0 , k0p , precision = 1.e-5 ) :
"""calculate dP / dV for numerical calculation of bulk modulus
according to test this differs from analytical result by 1 . e - 5
: param v : unit - cell volume in A ^ 3
: param v0 : unit - cell volume in A ^ 3 at 1 bar
: param k0 : bulk modulus at ... | def f_scalar ( v , v0 , k0 , k0p , precision = 1.e-5 ) :
return derivative ( vinet_p , v , args = ( v0 , k0 , k0p ) , dx = v0 * precision )
f_v = np . vectorize ( f_scalar , excluded = [ 1 , 2 , 3 , 4 ] )
return f_v ( v , v0 , k0 , k0p , precision = precision ) |
def read ( in_path ) :
"""Read a grp file at the path specified by in _ path .
Args :
in _ path ( string ) : path to GRP file
Returns :
grp ( list )""" | assert os . path . exists ( in_path ) , "The following GRP file can't be found. in_path: {}" . format ( in_path )
with open ( in_path , "r" ) as f :
lines = f . readlines ( )
# need the second conditional to ignore comment lines
grp = [ line . strip ( ) for line in lines if line and not re . match ( "^#" , ... |
def write_obs_summary_table ( self , filename = None , group_names = None ) :
"""write a stand alone observation summary latex table
Parameters
filename : str
latex filename . If None , use < case > . par . tex . Default is None
group _ names : dict
par group names : table names for example { " w0 " : " w... | ffmt = lambda x : "{0:5G}" . format ( x )
obs = self . observation_data . copy ( )
obsgp = obs . groupby ( obs . obgnme ) . groups
cols = [ "obgnme" , "obsval" , "nzcount" , "zcount" , "weight" , "stdev" , "pe" ]
labels = { "obgnme" : "group" , "obsval" : "value" , "nzcount" : "non-zero weight" , "zcount" : "zero weigh... |
def is_watertight ( self ) :
"""Check if a mesh is watertight by making sure every edge is
included in two faces .
Returns
is _ watertight : bool
Is mesh watertight or not""" | if self . is_empty :
return False
watertight , winding = graph . is_watertight ( edges = self . edges , edges_sorted = self . edges_sorted )
self . _cache [ 'is_winding_consistent' ] = winding
return watertight |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.