signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def add_to_list ( my_list , my_element ) :
"""Helper function to add new my _ element to my _ list based on its type .
Add as new element if it ' s not a list , otherwise extend to the list
if it ' s a list .
It ' s also guarantee that all elements are unique
: param my _ list : A list
: type my _ list : ... | if isinstance ( my_element , list ) :
for element in my_element :
my_list = add_to_list ( my_list , element )
else :
if my_element not in my_list :
my_list . append ( my_element )
return my_list |
def make_po_file ( self , potfile , locale ) :
"""Creates or updates the PO file for self . domain and : param locale : .
Uses contents of the existing : param potfile : .
Uses mguniq , msgmerge , and msgattrib GNU gettext utilities .""" | pofile = self . _get_po_path ( potfile , locale )
msgs = self . _get_unique_messages ( potfile )
msgs = self . _merge_messages ( potfile , pofile , msgs )
msgs = self . _strip_package_version ( msgs )
with open ( pofile , 'w' ) as fp :
fp . write ( msgs )
self . _remove_obsolete_messages ( pofile ) |
def set_mode ( self , anchor_id , mode ) :
"""Send a packet to set the anchor mode . If the anchor receive the packet ,
it will change mode and resets .""" | data = struct . pack ( '<BB' , LoPoAnchor . LPP_TYPE_MODE , mode )
self . crazyflie . loc . send_short_lpp_packet ( anchor_id , data ) |
def generatePixmap ( base64_data ) :
"""Generates a new pixmap based on the inputed base64 data .
: param base64 | < str >""" | import_qt ( globals ( ) )
binary_data = binascii . a2b_base64 ( base64_data )
arr = QtCore . QByteArray . fromRawData ( binary_data )
img = QtGui . QImage . fromData ( arr )
return QtGui . QPixmap ( img ) |
def reindex ( self , kdims = [ ] , force = False ) :
"""Reindexes object dropping static or supplied kdims
Creates a new object with a reordered or reduced set of key
dimensions . By default drops all non - varying key dimensions .
Reducing the number of key dimensions will discard information
from the keys... | old_kdims = [ d . name for d in self . kdims ]
if not isinstance ( kdims , list ) :
kdims = [ kdims ]
elif not len ( kdims ) :
kdims = [ d for d in old_kdims if not len ( set ( self . dimension_values ( d ) ) ) == 1 ]
indices = [ self . get_dimension_index ( el ) for el in kdims ]
keys = [ tuple ( k [ i ] for i... |
def start_new_particles ( self ) :
"""Start some new particles from the emitters . We roll the dice
starts _ at _ once times , seeing if we can start each particle based
on starts _ prob . If we start , the particle gets a color form
the palette and a velocity from the vel list .""" | for e_pos , e_dir , e_vel , e_range , e_color , e_pal in self . emitters :
for roll in range ( self . starts_at_once ) :
if random . random ( ) < self . starts_prob : # Start one ?
p_vel = self . vel [ random . choice ( len ( self . vel ) ) ]
if e_dir < 0 or e_dir == 0 and random . r... |
def shorten_paths ( path_list , is_unsaved ) :
"""Takes a list of paths and tries to " intelligently " shorten them all . The
aim is to make it clear to the user where the paths differ , as that is
likely what they care about . Note that this operates on a list of paths
not on individual paths .
If the path... | # TODO : at the end , if the path is too long , should do a more dumb kind of
# shortening , but not completely dumb .
# Convert the path strings to a list of tokens and start building the
# new _ path using the drive
path_list = path_list [ : ]
# Make a local copy
new_path_list = [ ]
for ii , ( path , is_unsav ) in en... |
def get_top_exchanges ( fsym , tsym , limit = 5 ) :
"""Get top exchanges by 24 hour trading volume for the currency pair .
Args :
fsym : FROM symbol .
tsym : TO symbol .
limit : Number of results . Default value returns top 5 exchanges .
Returns :
Function returns a list containing a dictionary for each... | # load data
url = build_url ( 'exchanges' , fsym = fsym , tsym = tsym , limit = limit )
data = load_data ( url )
# price _ data = data [ ' Data ' ]
# return [ { ' exchange ' : p [ ' exchange ' ] ,
# ' volume24hto ' : p [ ' volume24hTo ' ] } for p in price _ data ]
return data [ 'Data' ] |
def get_asset_search_session ( self ) :
"""Gets an asset search session .
return : ( osid . repository . AssetSearchSession ) - an
` ` AssetSearchSession ` `
raise : OperationFailed - unable to complete request
raise : Unimplemented - ` ` supports _ asset _ search ( ) ` ` is ` ` false ` `
* compliance : o... | if not self . supports_asset_search ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . AssetSearchSession ( runtime = self . _runtime ) |
def from_molecule ( cls , mol , theory , charge = None , spin_multiplicity = None , basis_set = "6-31g" , basis_set_option = "cartesian" , title = None , operation = "optimize" , theory_directives = None , alternate_directives = None ) :
"""Very flexible arguments to support many types of potential setups .
Users... | title = title if title is not None else "{} {} {}" . format ( re . sub ( r"\s" , "" , mol . formula ) , theory , operation )
charge = charge if charge is not None else mol . charge
nelectrons = - charge + mol . charge + mol . nelectrons
if spin_multiplicity is not None :
spin_multiplicity = spin_multiplicity
if... |
def cleanup ( graph , subgraphs ) :
"""Clean up the metadata in the subgraphs .
: type graph : pybel . BELGraph
: type subgraphs : dict [ Any , pybel . BELGraph ]""" | for subgraph in subgraphs . values ( ) :
update_node_helper ( graph , subgraph )
update_metadata ( graph , subgraph ) |
def library_line ( self , file_name ) :
"""Specifies GULP library file to read species and potential parameters .
If using library don ' t specify species and potential
in the input file and vice versa . Make sure the elements of
structure are in the library file .
Args :
file _ name : Name of GULP librar... | gulplib_set = lambda : 'GULP_LIB' in os . environ . keys ( )
readable = lambda f : os . path . isfile ( f ) and os . access ( f , os . R_OK )
# dirpath , fname = os . path . split ( file _ name )
# if dirpath : # Full path specified
# if readable ( file _ name ) :
# gin = ' library ' + file _ name
# else :
# raise Gulp... |
def calculate_size ( name , reduction ) :
"""Calculates the request payload size""" | data_size = 0
data_size += calculate_size_str ( name )
data_size += INT_SIZE_IN_BYTES
return data_size |
def gtk_threadsafe ( func ) :
'''Decorator to make wrapped function threadsafe by forcing it to execute
within the GTK main thread .
. . versionadded : : 0.18
. . versionchanged : : 0.22
Add support for keyword arguments in callbacks by supporting functions
wrapped by ` functools . partial ( ) ` . Also , ... | # Set up GDK threading .
# XXX This must be done to support running multiple threads in GTK
# applications .
gtk . gdk . threads_init ( )
# Support
wraps_func = func . func if isinstance ( func , functools . partial ) else func
@ functools . wraps ( wraps_func )
def _gtk_threadsafe ( * args ) :
def _no_return_func ... |
def caesar_cipher ( message , key ) :
"""凯特加密法
: param message : 待加密数据
: param key : 加密向量
: return : 被加密的字符串""" | LEFTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
translated = ''
message = message . upper ( )
for symbol in message :
if symbol in LEFTERS :
num = LEFTERS . find ( symbol )
num = num + key
if num >= len ( LEFTERS ) :
num = num - len ( LEFTERS )
elif num < 0 :
num = num... |
def main ( ) :
"""NAME
hysteresis _ magic . py
DESCRIPTION
calculates hystereis parameters and saves them in rmag _ hystereis format file
makes plots if option selected
SYNTAX
hysteresis _ magic . py [ command line options ]
OPTIONS
- h prints help message and quits
- usr USER : identify user , de... | args = sys . argv
PLT = 1
plots = 0
user , meas_file , rmag_out , rmag_file = "" , "agm_measurements.txt" , "rmag_hysteresis.txt" , ""
pltspec = ""
dir_path = '.'
fmt = 'svg'
verbose = pmagplotlib . verbose
version_num = pmag . get_version ( )
if '-WD' in args :
ind = args . index ( '-WD' )
dir_path = args [ in... |
def checksum ( self ) :
"""Grab checksum string""" | md5sum , md5sum64 , = [ ] , [ ]
for line in self . SLACKBUILDS_TXT . splitlines ( ) :
if line . startswith ( self . line_name ) :
sbo_name = line [ 17 : ] . strip ( )
if line . startswith ( self . line_md5_64 ) :
if sbo_name == self . name and line [ 26 : ] . strip ( ) :
md5sum64 = l... |
def send_message ( target , data , auth = None , debug = False ) :
"""Send a single message to AMQP endpoint .
: param target : The target AMQP endpoint .
: type target : str , bytes or ~ uamqp . address . Target
: param data : The contents of the message to send .
: type data : str , bytes or ~ uamqp . mes... | message = data if isinstance ( data , Message ) else Message ( body = data )
with SendClient ( target , auth = auth , debug = debug ) as send_client :
send_client . queue_message ( message )
return send_client . send_all_messages ( ) |
def _objectify ( self , node , binding , depth , path ) :
"""Given an RDF node URI ( and it ' s associated schema ) , return an
object from the ` ` graph ` ` that represents the information available
about this node .""" | if binding . is_object :
obj = { '$schema' : binding . path }
for ( s , p , o ) in self . graph . triples ( ( node , None , None ) ) :
prop = binding . get_property ( p )
if prop is None or depth <= 1 or o in path :
continue
# This is slightly odd but yield purty objects :
... |
def _convert_errors ( func ) :
"""Decorator to convert throws errors to Voluptuous format .""" | cast_Invalid = lambda e : Invalid ( u"{message}, expected {expected}" . format ( message = e . message , expected = e . expected ) if e . expected != u'-none-' else e . message , e . path , six . text_type ( e ) )
@ wraps ( func )
def wrapper ( * args , ** kwargs ) :
try :
return func ( * args , ** kwargs )... |
def remove_file_by_id ( self , file_id , target_name = None ) :
"""Removes the file id from given target name . If no target name is given , the file is removed
from all targets
: param file _ id : identifier of the file to be removed
: param target _ name : Target name or list of target names where the file ... | file_ref = self . get_file_by_id ( file_id )
if file_ref is None :
return False
for target in self . objects . get_targets ( target_name ) :
for build_phase_id in target . buildPhases :
build_phase = self . objects [ build_phase_id ]
for build_file_id in build_phase . files :
build_f... |
def write_xml ( self , xmlfile ) :
"""Write the XML model for this analysis component .""" | xmlfile = self . get_model_path ( xmlfile )
self . logger . info ( 'Writing %s...' , xmlfile )
self . like . writeXml ( str ( xmlfile ) ) |
def get_machine_group ( self , project_name , group_name ) :
"""get machine group in a project
Unsuccessful opertaion will cause an LogException .
: type project _ name : string
: param project _ name : the Project name
: type group _ name : string
: param group _ name : the group name to get
: return :... | headers = { }
params = { }
resource = "/machinegroups/" + group_name
( resp , headers ) = self . _send ( "GET" , project_name , None , resource , params , headers )
return GetMachineGroupResponse ( resp , headers ) |
def store ( self ) :
'''Write content of the entire cache to disk''' | if msgpack is None :
log . error ( 'Cache cannot be stored on disk: msgpack is missing' )
else : # TODO Dir hashing ?
try :
with salt . utils . files . fopen ( self . _path , 'wb+' ) as fp_ :
cache = { "CacheDisk_data" : self . _dict , "CacheDisk_cachetime" : self . _key_cache_time }
... |
def parse_type ( source : SourceType , ** options : dict ) -> TypeNode :
"""Parse the AST for a given string containing a GraphQL Type .
Throws GraphQLError if a syntax error is encountered .
This is useful within tools that operate upon GraphQL Types directly and
in isolation of complete GraphQL documents . ... | if isinstance ( source , str ) :
source = Source ( source )
lexer = Lexer ( source , ** options )
expect_token ( lexer , TokenKind . SOF )
type_ = parse_type_reference ( lexer )
expect_token ( lexer , TokenKind . EOF )
return type_ |
def get_export_launch_description_form ( self ) :
"""Returns a form for editing the virtual system description .
Since the data for the form are fetched from the cloud a
progress object is also returned to indicate if / when the form
is ready to be used .
out form of type : class : ` IVirtualSystemDescripti... | ( progress , form ) = self . _call ( "getExportLaunchDescriptionForm" )
progress = IProgress ( progress )
form = IVirtualSystemDescriptionForm ( form )
return ( progress , form ) |
def _fill_cache ( self , num = None ) :
"""Fills the result cache with ' num ' more entries ( or until the results
iterator is exhausted ) .""" | if self . _iter :
try :
for i in range ( num or ITER_CHUNK_SIZE ) :
self . _result_cache . append ( next ( self . _iter ) )
except StopIteration :
self . _iter = None |
def register ( self , object_tool_class , model_class = None ) :
"""Registers the given model ( s ) with the given object tool class .
The model ( s ) should be Model classes , not instances .
If a model class isn ' t given the object tool class will be registered
for all models .
If a model is already regi... | if not object_tool_class :
return None
# Don ' t validate unless required .
if object_tool_class and settings . DEBUG :
from object_tools . validation import validate
validate ( object_tool_class , model_class )
# = lambda model , adminclass : None
if not model_class :
models = get_models ( )
else :... |
def OnOpenFile ( self , event ) :
"""Request to open a new profile file""" | dialog = wx . FileDialog ( self , style = wx . OPEN | wx . FD_MULTIPLE )
if dialog . ShowModal ( ) == wx . ID_OK :
paths = dialog . GetPaths ( )
if self . loader : # we ' ve already got a displayed data - set , open new window . . .
frame = MainFrame ( )
frame . Show ( True )
frame . loa... |
def averages ( self , ** kwargs ) :
"""Get the average time / uptime value for a specified check and time
period .
Optional parameters :
* time _ from - - Start time of period . Format is UNIX timestamp
Type : Integer
Default : 0
* time _ to - - End time of period . Format is UNIX timestamp
Type : Int... | # ' from ' is a reserved word , use time _ from instead
if kwargs . get ( 'time_from' ) :
kwargs [ 'from' ] = kwargs . get ( 'time_from' )
del kwargs [ 'time_from' ]
if kwargs . get ( 'time_to' ) :
kwargs [ 'to' ] = kwargs . get ( 'time_to' )
del kwargs [ 'time_to' ]
# Warn user about unhandled paramete... |
def pull ( self , * , index = None ) :
"""Pull item from the chain .""" | item = self . __list . pop ( index )
name = getattr ( item , 'name' , None )
if name is not None :
del self . __dict [ name ]
return item |
def _create_batches ( self , X , batch_size , shuffle_data = True ) :
"""Create batches out of a sequence of data .
This function will append zeros to the end of your data to ensure that
all batches are even - sized . These are masked out during training .""" | if shuffle_data :
X = shuffle ( X )
if batch_size > X . shape [ 0 ] :
batch_size = X . shape [ 0 ]
max_x = int ( np . ceil ( X . shape [ 0 ] / batch_size ) )
X = np . resize ( X , ( max_x , batch_size , X . shape [ - 1 ] ) )
return X |
def generate_sample_set ( self , tags = None ) :
"""Generate a sample _ set that maches the tags or all if tags are not specified .
Args :
tags : Match samples against this tag list ( or all if not specified )
Returns :
The sample _ set of those samples matching the tags""" | if isinstance ( tags , str ) :
tags = [ tags ]
md5_list = self . data_store . tag_match ( tags )
return self . store_sample_set ( md5_list ) |
def set_state ( self , state , speed = None ) :
""": param state : bool
: param speed : a string one of [ " lowest " , " low " ,
" medium " , " high " , " auto " ] defaults to last speed
: return : nothing""" | desired_state = { "powered" : state }
if state :
brightness = self . _to_brightness . get ( speed or self . current_fan_speed ( ) , 0.33 )
desired_state . update ( { 'brightness' : brightness } )
response = self . api_interface . set_device_state ( self , { "desired_state" : desired_state } )
self . _update_sta... |
def define ( self , name : str , default : Any = None , type : type = None , help : str = None , metavar : str = None , multiple : bool = False , group : str = None , callback : Callable [ [ Any ] , None ] = None , ) -> None :
"""Defines a new command line option .
` ` type ` ` can be any of ` str ` , ` int ` , `... | normalized = self . _normalize_name ( name )
if normalized in self . _options :
raise Error ( "Option %r already defined in %s" % ( normalized , self . _options [ normalized ] . file_name ) )
frame = sys . _getframe ( 0 )
options_file = frame . f_code . co_filename
# Can be called directly , or through top level de... |
def files_log_graph ( self , stream ) :
'''Build up a graph ( nodes and edges from a Bro files . log )''' | file_log = list ( stream )
print 'Entering file_log_graph...(%d rows)' % len ( file_log )
for row in file_log : # If the mime - type is interesting add the uri and the host - > uri - > host relationships
if row [ 'mime_type' ] not in self . exclude_mime_types : # Check for weird conditions
if ( row [ 'total... |
def get_bounds ( self , bin_num ) :
"""Get the bonds of a bin , given its index ` bin _ num ` .
: returns : a ` Bounds ` namedtuple with properties min and max
respectively .""" | min_bound = ( self . bin_size * bin_num ) + self . min_value
max_bound = min_bound + self . bin_size
return self . Bounds ( min_bound , max_bound ) |
def lookup ( self , req , parent , name ) :
"""Look up a directory entry by name and get its attributes .
Valid replies :
reply _ entry
reply _ err""" | self . reply_err ( req , errno . ENOENT ) |
def recipients ( preferences , message , valid_paths , config ) :
"""The main API function .
Accepts a fedmsg message as an argument .
Returns a dict mapping context names to lists of recipients .""" | rule_cache = dict ( )
results = defaultdict ( list )
notified = set ( )
for preference in preferences :
user = preference [ 'user' ]
context = preference [ 'context' ]
if ( user [ 'openid' ] , context [ 'name' ] ) in notified :
continue
for filter in preference [ 'filters' ] :
if matches... |
def _iter_walk ( self , fs , # type : FS
path , # type : Text
namespaces = None , # type : Optional [ Collection [ Text ] ]
) : # type : ( . . . ) - > Iterator [ Tuple [ Text , Optional [ Info ] ] ]
"""Get the walk generator .""" | if self . search == "breadth" :
return self . _walk_breadth ( fs , path , namespaces = namespaces )
else :
return self . _walk_depth ( fs , path , namespaces = namespaces ) |
def concat ( left , rights , distinct = False , axis = 0 ) :
"""Concat collections .
: param left : left collection
: param rights : right collections , can be a DataFrame object or a list of DataFrames
: param distinct : whether to remove duplicate entries . only available when axis = = 0
: param axis : wh... | from . . utils import to_collection
if isinstance ( rights , Node ) :
rights = [ rights , ]
if not rights :
raise ValueError ( 'At least one DataFrame should be provided.' )
if axis == 0 :
for right in rights :
left = union ( left , right , distinct = distinct )
return left
else :
rights = [... |
def prop_eq_or_in_or ( default , key , value , dct ) :
"""Ramda propEq / propIn plus propOr
: param default :
: param key :
: param value :
: param dct :
: return :""" | return has ( key , dct ) and ( dct [ key ] == value if key in dct else ( dct [ key ] in value if isinstance ( ( list , tuple ) , value ) and not isinstance ( str , value ) else default ) ) |
def to_json ( self ) :
"""Convert the analysis period to a dictionary .""" | return { 'st_month' : self . st_month , 'st_day' : self . st_day , 'st_hour' : self . st_hour , 'end_month' : self . end_month , 'end_day' : self . end_day , 'end_hour' : self . end_hour , 'timestep' : self . timestep , 'is_leap_year' : self . is_leap_year } |
def getSpec ( cls ) :
"""Return the Spec for ApicalTMPairRegion""" | spec = { "description" : ApicalTMPairRegion . __doc__ , "singleNodeOnly" : True , "inputs" : { "activeColumns" : { "description" : ( "An array of 0's and 1's representing the active " "minicolumns, i.e. the input to the TemporalMemory" ) , "dataType" : "Real32" , "count" : 0 , "required" : True , "regionLevel" : True ,... |
def mac_access_list_extended_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
mac = ET . SubElement ( config , "mac" , xmlns = "urn:brocade.com:mgmt:brocade-mac-access-list" )
access_list = ET . SubElement ( mac , "access-list" )
extended = ET . SubElement ( access_list , "extended" )
name = ET . SubElement ( extended , "name" )
name . text = kwargs . pop ( 'na... |
def check_runtime_errors ( cmd_derived_from_alias , pos_args_table ) :
"""Validate placeholders and their expressions in cmd _ derived _ from _ alias to make sure
that there is no runtime error ( such as index out of range ) .
Args :
cmd _ derived _ from _ alias : The command derived from the alias
( includ... | for placeholder , value in pos_args_table . items ( ) :
exec ( '{} = "{}"' . format ( placeholder , value ) )
# pylint : disable = exec - used
expressions = get_placeholders ( cmd_derived_from_alias )
for expression in expressions :
try :
exec ( expression )
# pylint : disable = exec - used
... |
def run ( self , image , command = None , stdout = True , stderr = False , remove = False , ** kwargs ) :
"""Run a container . By default , it will wait for the container to finish
and return its logs , similar to ` ` docker run ` ` .
If the ` ` detach ` ` argument is ` ` True ` ` , it will start the container ... | if isinstance ( image , Image ) :
image = image . id
stream = kwargs . pop ( 'stream' , False )
detach = kwargs . pop ( 'detach' , False )
platform = kwargs . pop ( 'platform' , None )
if detach and remove :
if version_gte ( self . client . api . _version , '1.25' ) :
kwargs [ "auto_remove" ] = True
... |
def _check_holiday_structure ( self , times ) :
"""To check the structure of the HolidayClass
: param list times : years or months or days or number week
: rtype : None or Exception
: return : in the case of exception returns the exception""" | if not isinstance ( times , list ) :
raise TypeError ( "an list is required" )
for time in times :
if not isinstance ( time , tuple ) :
raise TypeError ( "a tuple is required" )
if len ( time ) > 5 :
raise TypeError ( "Target time takes at most 5 arguments" " ('%d' given)" % len ( time ) )
... |
def create ( cls , card_id , name_on_card = None , pin_code = None , second_line = None , custom_headers = None ) :
"""Request a card replacement .
: type user _ id : int
: type card _ id : int
: param name _ on _ card : The user ' s name as it will be on the card . Check
' card - name ' for the available c... | if custom_headers is None :
custom_headers = { }
request_map = { cls . FIELD_NAME_ON_CARD : name_on_card , cls . FIELD_PIN_CODE : pin_code , cls . FIELD_SECOND_LINE : second_line }
request_map_string = converter . class_to_json ( request_map )
request_map_string = cls . _remove_field_for_request ( request_map_strin... |
def SubtractFromBalance ( self , assetId , fixed8_val ) :
"""Subtract amount to the specified balance .
Args :
assetId ( UInt256 ) :
fixed8 _ val ( Fixed8 ) : amount to add .""" | found = False
for key , balance in self . Balances . items ( ) :
if key == assetId :
self . Balances [ assetId ] = self . Balances [ assetId ] - fixed8_val
found = True
if not found :
self . Balances [ assetId ] = fixed8_val * Fixed8 ( - 1 ) |
def set ( self , key , value , time , compress_level = - 1 ) :
"""Set a value for a key on server .
: param key : Key ' s name
: type key : six . string _ types
: param value : A value to be stored on server .
: type value : object
: param time : Time in seconds that your key will expire .
: type time :... | return self . _set_add_replace ( 'set' , key , value , time , compress_level = compress_level ) |
def run_command ( cmd , debug = False ) :
"""Execute the given command and returns None .
: param cmd : A ` ` sh . Command ` ` object to execute .
: param debug : An optional bool to toggle debug output .
: return : ` ` sh ` ` object""" | if debug : # WARN ( retr0h ) : Uses an internal ` ` sh ` ` data structure to dig
# the environment out of the ` ` sh . command ` ` object .
print_environment_vars ( cmd . _partial_call_args . get ( 'env' , { } ) )
print_debug ( 'COMMAND' , str ( cmd ) )
print ( )
return cmd ( _truncate_exc = False ) |
def galactic_latlon ( self ) :
"""Compute galactic coordinates ( lat , lon , distance )""" | vector = _GALACTIC . dot ( self . position . au )
d , lat , lon = to_polar ( vector )
return ( Angle ( radians = lat , signed = True ) , Angle ( radians = lon ) , Distance ( au = d ) ) |
def dumps ( self , obj , many = None , * args , ** kwargs ) :
"""Same as : meth : ` dump ` , except return a JSON - encoded string .
: param obj : The object to serialize .
: param bool many : Whether to serialize ` obj ` as a collection . If ` None ` , the value
for ` self . many ` is used .
: return : A `... | serialized = self . dump ( obj , many = many )
return self . opts . render_module . dumps ( serialized , * args , ** kwargs ) |
def is_active ( self ) :
"""Determines whether this plugin is active .
This plugin is only active if any run has an embedding .
Returns :
Whether any run has embedding data to show in the projector .""" | if not self . multiplexer :
return False
if self . _is_active : # We have already determined that the projector plugin should be active .
# Do not re - compute that . We have no reason to later set this plugin to be
# inactive .
return True
if self . _thread_for_determining_is_active : # We are currently determ... |
def __handle_scale_rot ( self ) :
"""Handle scaling and rotation of the surface""" | if self . __is_rot_pending :
self . __execute_rot ( self . untransformed_image )
self . __is_rot_pending = False
# Scale the image using the recently rotated surface to keep the orientation correct
self . __execute_scale ( self . image , self . image . get_size ( ) )
self . __is_scale_pending = Fals... |
def _move ( self ) :
"""Called during a PUT request where the action specifies
a move operation . Returns resource URI of the destination file .""" | newpath = self . action [ 'newpath' ]
try :
self . fs . move ( self . fp , newpath )
except OSError :
raise tornado . web . HTTPError ( 400 )
return newpath |
def query ( song_name ) :
"""CLI :
$ iquery - l song _ name""" | r = requests_get ( SONG_SEARCH_URL . format ( song_name ) )
try : # Get the first result .
song_url = re . search ( r'(http://www.xiami.com/song/\d+)' , r . text ) . group ( 0 )
except AttributeError :
exit_after_echo ( SONG_NOT_FOUND )
return SongPage ( song_url ) |
def remove_item ( self , item ) :
"""Remove the specified item from the menu .
Args :
item ( MenuItem ) : the item to be removed .
Returns :
bool : True if the item was removed ; False otherwise .""" | for idx , _item in enumerate ( self . items ) :
if item == _item :
del self . items [ idx ]
return True
return False |
def signed_to_twos_comp ( val : int , n_bits : int ) -> int :
"""Convert a signed integer to its " two ' s complement " representation .
Args :
val : signed integer
n _ bits : number of bits ( which must reflect a whole number of bytes )
Returns :
unsigned integer : two ' s complement version""" | assert n_bits % 8 == 0 , "Must specify a whole number of bytes"
n_bytes = n_bits // 8
b = val . to_bytes ( n_bytes , byteorder = sys . byteorder , signed = True )
return int . from_bytes ( b , byteorder = sys . byteorder , signed = False ) |
def findattr ( self , name ) :
"""Search the vgroup for a given attribute .
Args : :
name attribute name
Returns : :
if found , VGAttr instance describing the attribute
None otherwise
C library equivalent : Vfindattr""" | try :
att = self . attr ( name )
if att . _index is None :
att = None
except HDF4Error :
att = None
return att |
def create_graphics ( self ) :
"""Create images related to this panel .""" | if len ( self . _svg_fns ) > 0 :
rnftools . utils . shell ( '"{}" "{}"' . format ( "gnuplot" , self . _gp_fn ) )
if self . render_pdf_method is not None :
for svg_fn in self . _svg_fns :
pdf_fn = re . sub ( r'\.svg$' , r'.pdf' , svg_fn )
svg42pdf ( svg_fn , pdf_fn , method = self... |
def is_theme ( self , name ) :
"""Return True if the theme * name * should be used .""" | return getattr ( self . args , 'theme_' + name ) or self . theme [ 'name' ] == name |
def _get_vrf_name ( self , ri ) :
"""overloaded method for generating a vrf _ name that supports
region _ id""" | router_id = ri . router_name ( ) [ : self . DEV_NAME_LEN ]
is_multi_region_enabled = cfg . CONF . multi_region . enable_multi_region
if is_multi_region_enabled :
region_id = cfg . CONF . multi_region . region_id
vrf_name = "%s-%s" % ( router_id , region_id )
else :
vrf_name = router_id
return vrf_name |
def compute_panel ( cls , data , scales , params ) :
"""Positions must override this function
Notes
Make necessary adjustments to the columns in the dataframe .
Create the position transformation functions and
use self . transform _ position ( ) do the rest .
See Also
position _ jitter . compute _ panel... | msg = '{} needs to implement this method'
raise NotImplementedError ( msg . format ( cls . __name__ ) ) |
def predict_proba ( self , L ) :
"""Returns the [ n , k ] matrix of label probabilities P ( Y | \ lambda )
Args :
L : An [ n , m ] scipy . sparse label matrix with values in { 0,1 , . . . , k }""" | self . _set_constants ( L )
L_aug = self . _get_augmented_label_matrix ( L )
mu = np . clip ( self . mu . detach ( ) . clone ( ) . numpy ( ) , 0.01 , 0.99 )
# Create a " junction tree mask " over the columns of L _ aug / mu
if len ( self . deps ) > 0 :
jtm = np . zeros ( L_aug . shape [ 1 ] )
# All maximal cliq... |
def prt_ntgos ( self , prt , ntgos ) :
"""Print the Grouper namedtuples .""" | for ntgo in ntgos :
key2val = ntgo . _asdict ( )
prt . write ( "{GO_LINE}\n" . format ( GO_LINE = self . prtfmt . format ( ** key2val ) ) ) |
def put ( self , key , value ) :
"""Associate key and value in the cache .
@ param key : the key
@ type key : ( dns . name . Name , int , int ) tuple whose values are the
query name , rdtype , and rdclass .
@ param value : The answer being cached
@ type value : dns . resolver . Answer object""" | self . maybe_clean ( )
self . data [ key ] = value |
def project ( num = None , * args , ** kwargs ) :
"""Create a new main project
Parameters
num : int
The number of the project
% ( Project . parameters . no _ num ) s
Returns
Project
The with the given ` num ` ( if it does not already exist , it is created )
See Also
scp : Sets the current project ... | numbers = [ project . num for project in _open_projects ]
if num in numbers :
return _open_projects [ numbers . index ( num ) ]
if num is None :
num = max ( numbers ) + 1 if numbers else 1
project = PROJECT_CLS . new ( num , * args , ** kwargs )
_open_projects . append ( project )
return project |
def has_suffix ( path_name , suffix ) :
"""Determines if path _ name has a suffix of at least ' suffix '""" | if isinstance ( suffix , str ) :
suffix = disintegrate ( suffix )
components = disintegrate ( path_name )
for i in range ( - 1 , - ( len ( suffix ) + 1 ) , - 1 ) :
if components [ i ] != suffix [ i ] :
break
else :
return True
return False |
def getpreferredencoding ( ) :
"""Return preferred encoding for text I / O .""" | encoding = locale . getpreferredencoding ( False )
if sys . platform == 'darwin' and encoding . startswith ( 'mac-' ) : # Upgrade ancient MacOS encodings in Python < 2.7
encoding = 'utf-8'
return encoding |
def extract_element ( self , vector , idx , name = '' ) :
"""Returns the value at position idx .""" | instr = instructions . ExtractElement ( self . block , vector , idx , name = name )
self . _insert ( instr )
return instr |
def Concat ( self : Iterable , * others ) :
"""' self ' : [ 1 , 2 , 3 ] ,
' : args ' : [ [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ,
' assert ' : lambda ret : list ( ret ) = = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9]""" | return concat_generator ( self , * [ unbox_if_flow ( other ) for other in others ] ) |
def _get_all_field_names ( model ) :
"""100 % compatible version of the old API of model . _ meta . get _ all _ field _ names ( )
From : https : / / docs . djangoproject . com / en / 1.9 / ref / models / meta / # migrating - from - the - old - api""" | return list ( set ( chain . from_iterable ( ( field . name , field . attname ) if hasattr ( field , 'attname' ) else ( field . name , ) for field in model . _meta . get_fields ( ) # For complete backwards compatibility , you may want to exclude
# GenericForeignKey from the results .
if not ( field . many_to_one and fie... |
def export ( gandi , resource , output , force , intermediate ) :
"""Write the certificate to < output > or < fqdn > . crt .
Resource can be a CN or an ID""" | ids = [ ]
for res in resource :
ids . extend ( gandi . certificate . usable_ids ( res ) )
if output and len ( ids ) > 1 :
gandi . echo ( 'Too many certs found, you must specify which cert you ' 'want to export' )
return
for id_ in set ( ids ) :
cert = gandi . certificate . info ( id_ )
if 'cert' not... |
def _lease_owned ( self , lease , current_uuid_path ) :
"""Checks if the given lease is owned by the prefix whose uuid is in
the given path
Note :
The prefix must be also in the same path it was when it took the
lease
Args :
path ( str ) : Path to the lease
current _ uuid _ path ( str ) : Path to the ... | prev_uuid_path , prev_uuid = lease . metadata
with open ( current_uuid_path ) as f :
current_uuid = f . read ( )
return current_uuid_path == prev_uuid_path and prev_uuid == current_uuid |
def parse_values ( self , query ) :
"""extract values from query""" | values = { }
for name , filt in self . filters . items ( ) :
val = filt . parse_value ( query )
if val is None :
continue
values [ name ] = val
return values |
def print_formatted ( datas ) :
"""Pretty print JSON DATA
Argument :
datas : dictionary of data""" | if not datas :
print ( "No data" )
exit ( 1 )
if isinstance ( datas , list ) : # get all zones
# API / zone without : identifier
hr ( )
print ( '%-20s %-8s %-12s' % ( 'name' , 'type' , 'notified_serial' ) )
hr ( )
for record in datas : # print ' NAME '
utils . print_inline ( "%(name)-20s... |
def extract_path ( prec , v ) :
"""extracts a path in form of vertex list from source to vertex v
given a precedence table prec leading to the source
: param prec : precedence table of a tree
: param v : vertex on the tree
: returns : path from root to v , in form of a list
: complexity : linear""" | L = [ ]
while v is not None :
L . append ( v )
v = prec [ v ]
assert v not in L
# prevent infinite loops for a bad formed table prec
return L [ : : - 1 ] |
def add ( self , key , value = None ) :
"""Adds the new key to this enumerated type .
: param key | < str >""" | if value is None :
value = 2 ** ( len ( self ) )
self [ key ] = value
setattr ( self , key , self [ key ] )
return value |
def _from_inferred_categories ( cls , inferred_categories , inferred_codes , dtype , true_values = None ) :
"""Construct a Categorical from inferred values .
For inferred categories ( ` dtype ` is None ) the categories are sorted .
For explicit ` dtype ` , the ` inferred _ categories ` are cast to the
appropr... | from pandas import Index , to_numeric , to_datetime , to_timedelta
cats = Index ( inferred_categories )
known_categories = ( isinstance ( dtype , CategoricalDtype ) and dtype . categories is not None )
if known_categories : # Convert to a specialized type with ` dtype ` if specified .
if dtype . categories . is_num... |
def isOpen ( self ) :
"""Returns whether all analyses from this Analysis Request are open
( their status is either " assigned " or " unassigned " )""" | for analysis in self . getAnalyses ( ) :
if not api . get_object ( analysis ) . isOpen ( ) :
return False
return True |
def plugins ( self , typ = None , group = None ) :
"""Returns the plugins used for this dialog .
: param typ | < str > | | None
group | < str > | | None
: return [ < XWizardPlugin > , . . ]""" | if ( typ is None ) :
output = [ ]
for wlang in self . _plugins . values ( ) :
for wgrp in wlang . values ( ) :
output += wgrp
return output
elif ( group is None ) :
output = [ ]
for wgrp in self . _plugins . get ( nativestring ( typ ) , { } ) . values ( ) :
output += wgrp... |
def status ( DomainName , region = None , key = None , keyid = None , profile = None ) :
'''Given a domain name describe its status .
Returns a dictionary of interesting properties .
CLI Example :
. . code - block : : bash
salt myminion boto _ elasticsearch _ domain . status mydomain''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
try :
domain = conn . describe_elasticsearch_domain ( DomainName = DomainName )
if domain and 'DomainStatus' in domain :
domain = domain . get ( 'DomainStatus' , { } )
keys = ( 'Endpoint' , 'Created' , 'Deleted'... |
def get_data ( model , instance_id , kind = '' ) :
"""Get instance data by id .
: param model : a string , model name in rio . models
: param id : an integer , instance id .
: param kind : a string specified which kind of dict tranformer should be called .
: return : data .""" | instance = get_instance ( model , instance_id )
if not instance :
return
return ins2dict ( instance , kind ) |
def get_dates ( self , request ) :
"""Get available Sentinel - 2 acquisitions at least time _ difference apart
List of all available Sentinel - 2 acquisitions for given bbox with max cloud coverage and the specified
time interval . When a single time is specified the request will return that specific date , if ... | if DataSource . is_timeless ( request . data_source ) :
return [ None ]
date_interval = parse_time_interval ( request . time )
LOGGER . debug ( 'date_interval=%s' , date_interval )
if request . wfs_iterator is None :
self . wfs_iterator = WebFeatureService ( request . bbox , date_interval , data_source = reques... |
def content_negotiation ( formats , default_type = 'text/html' ) :
"""Provides basic content negotiation and returns a view method based on the
best match of content types as indicated in formats .
: param formats : dictionary of content types and corresponding methods
: param default _ type : string the deco... | def _decorator ( view_method ) :
@ wraps ( view_method )
def _wrapped ( request , * args , ** kwargs ) : # Changed this to be a value passed as a method argument defaulting
# to text / html instead so it ' s more flexible .
# default _ type = ' text / html ' # If not specificied assume HTML request .
... |
def run ( paths , output = _I_STILL_HATE_EVERYTHING , recurse = core . flat , sort_by = None , ls = core . ls , stdout = stdout , ) :
"""Project - oriented directory and file information lister .""" | if output is _I_STILL_HATE_EVERYTHING :
output = core . columnized if stdout . isatty ( ) else core . one_per_line
if sort_by is None :
if output == core . as_tree :
def sort_by ( thing ) :
return ( thing . parent ( ) , thing . basename ( ) . lstrip ( string . punctuation ) . lower ( ) , )
... |
def make_fileitem_streamlist_stream_name ( stream_name , condition = 'is' , negate = False , preserve_case = False ) :
"""Create a node for FileItem / StreamList / Stream / Name
: return : A IndicatorItem represented as an Element node""" | document = 'FileItem'
search = 'FileItem/StreamList/Stream/Name'
content_type = 'string'
content = stream_name
ii_node = ioc_api . make_indicatoritem_node ( condition , document , search , content_type , content , negate = negate , preserve_case = preserve_case )
return ii_node |
def get_prepopulated_value ( field , instance ) :
"""Returns preliminary value based on ` populate _ from ` .""" | if hasattr ( field . populate_from , '__call__' ) : # AutoSlugField ( populate _ from = lambda instance : . . . )
return field . populate_from ( instance )
else : # AutoSlugField ( populate _ from = ' foo ' )
attr = getattr ( instance , field . populate_from )
return callable ( attr ) and attr ( ) or attr |
def upcoming_shabbat ( self ) :
"""Return the HDate for either the upcoming or current Shabbat .
If it is currently Shabbat , returns the HDate of the Saturday .""" | if self . is_shabbat :
return self
# If it ' s Sunday , fast forward to the next Shabbat .
saturday = self . gdate + datetime . timedelta ( ( 12 - self . gdate . weekday ( ) ) % 7 )
return HDate ( saturday , diaspora = self . diaspora , hebrew = self . hebrew ) |
def _get_bb_addr_from_instr ( self , instr ) :
"""Returns the address of the methods basic block that contains the given
instruction .
: param instr : The index of the instruction ( within the current method ) .
: rtype : SootAddressDescriptor""" | current_method = self . state . addr . method
try :
bb = current_method . block_by_label [ instr ]
except KeyError :
l . error ( "Possible jump to a non-existing bb %s --> %d" , self . state . addr , instr )
raise IncorrectLocationException ( )
return SootAddressDescriptor ( current_method , bb . idx , 0 ) |
def link_reads ( self , analysistype ) :
"""Create folders with relative symlinks to the desired simulated / sampled reads . These folders will contain all
the reads created for each sample , and will be processed with GeneSippr and COWBAT pipelines
: param analysistype : Current analysis type . Will either be ... | logging . info ( 'Linking {at} reads' . format ( at = analysistype ) )
for sample in self . metadata : # Create the output directories
genesippr_dir = os . path . join ( self . path , 'genesippr' , sample . name )
sample . genesippr_dir = genesippr_dir
make_path ( genesippr_dir )
cowbat_dir = os . path ... |
def update ( self , reference , field_updates , option = None ) :
"""Add a " change " to update a document .
See
: meth : ` ~ . firestore _ v1beta1 . document . DocumentReference . update ` for
more information on ` ` field _ updates ` ` and ` ` option ` ` .
Args :
reference ( ~ . firestore _ v1beta1 . do... | if option . __class__ . __name__ == "ExistsOption" :
raise ValueError ( "you must not pass an explicit write option to " "update." )
write_pbs = _helpers . pbs_for_update ( reference . _document_path , field_updates , option )
self . _add_write_pbs ( write_pbs ) |
def _InitializeGraph ( self , os_name , artifact_list ) :
"""Creates the nodes and directed edges of the dependency graph .
Args :
os _ name : String specifying the OS name .
artifact _ list : List of requested artifact names .""" | dependencies = artifact_registry . REGISTRY . SearchDependencies ( os_name , artifact_list )
artifact_names , attribute_names = dependencies
self . _AddAttributeNodes ( attribute_names )
self . _AddArtifactNodesAndEdges ( artifact_names ) |
def delete_zombie_checks ( self ) :
"""Remove checks that have a zombie status ( usually timeouts )
: return : None""" | id_to_del = [ ]
for chk in list ( self . checks . values ( ) ) :
if chk . status == ACT_STATUS_ZOMBIE :
id_to_del . append ( chk . uuid )
# une petite tape dans le dos et tu t ' en vas , merci . . .
# * pat pat * GFTO , thks : )
for c_id in id_to_del :
del self . checks [ c_id ] |
def status ( self , s = None ) :
"""Set / Get the status of the button .""" | if s is None :
return self . states [ self . _status ]
if isinstance ( s , str ) :
s = self . states . index ( s )
self . _status = s
self . textproperty . SetLineOffset ( self . offset )
self . actor . SetInput ( self . spacer + self . states [ s ] + self . spacer )
s = s % len ( self . colors )
# to avoid mis... |
def on_remove ( self , callable_ ) :
"""Add a remove observer to this entity .""" | self . model . add_observer ( callable_ , self . entity_type , 'remove' , self . entity_id ) |
def setTransducer ( self , edfsignal , transducer ) :
"""Sets the transducer of signal edfsignal
: param edfsignal : int
: param transducer : str
Notes
This function is optional for every signal and can be called only after opening a file in writemode and before the first sample write action .""" | if ( edfsignal < 0 or edfsignal > self . n_channels ) :
raise ChannelDoesNotExist ( edfsignal )
self . channels [ edfsignal ] [ 'transducer' ] = transducer
self . update_header ( ) |
def load_pdb ( self , pdb_id , mapped_chains = None , pdb_file = None , file_type = None , is_experimental = True , set_as_representative = False , representative_chain = None , force_rerun = False ) :
"""Load a structure ID and optional structure file into the structures attribute .
Args :
pdb _ id ( str ) : P... | if self . structures . has_id ( pdb_id ) : # Remove the structure if set to force rerun
if force_rerun :
existing = self . structures . get_by_id ( pdb_id )
self . structures . remove ( existing )
# Otherwise just retrieve it
else :
log . debug ( '{}: PDB ID already present in list o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.