signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def uv_to_Rz ( u , v , delta = 1. , oblate = False ) : """NAME : uv _ to _ Rz PURPOSE : calculate R and z from prolate confocal u and v coordinates INPUT : u - confocal u v - confocal v delta = focus oblate = ( False ) if True , compute oblate confocal coordinates instead of prolate OUTPUT : ( R...
if oblate : R = delta * sc . cosh ( u ) * sc . sin ( v ) z = delta * sc . sinh ( u ) * sc . cos ( v ) else : R = delta * sc . sinh ( u ) * sc . sin ( v ) z = delta * sc . cosh ( u ) * sc . cos ( v ) return ( R , z )
def get_route_to ( self , destination = "" , protocol = "" ) : """Return route details to a specific destination , learned from a certain protocol ."""
routes = { } if not isinstance ( destination , py23_compat . string_types ) : raise TypeError ( "Please specify a valid destination!" ) if protocol and isinstance ( destination , py23_compat . string_types ) : protocol = protocol . lower ( ) if protocol == "connected" : protocol = "direct" # this is how is ...
def coerce ( self , value , resource ) : """Coerce the value to an acceptable one . Only these kinds of values are returned as is : - str - int - float - True - False - None For all others values , it will be coerced using ` ` self . coerce _ default ` ` ( with convert the value to a string in the...
if value in ( True , False , None ) : return value if isinstance ( value , ( int , float ) ) : return value if isinstance ( value , str ) : return value return self . coerce_default ( value , resource )
def remove ( self , name_or_klass ) : """Remove a extension from the editor . : param name _ or _ klass : The name ( or class ) of the extension to remove . : returns : The removed extension ."""
logger . debug ( 'removing extension {}' . format ( name_or_klass ) ) extension = self . get ( name_or_klass ) extension . on_uninstall ( ) self . _extensions . pop ( extension . name ) return extension
def upsert ( queryset , model_objs , unique_fields , update_fields = None , returning = False , sync = False , ignore_duplicate_updates = True , return_untouched = False ) : """Perform a bulk upsert on a table , optionally syncing the results . Args : queryset ( Model | QuerySet ) : A model or a queryset that d...
queryset = queryset if isinstance ( queryset , models . QuerySet ) else queryset . objects . all ( ) model = queryset . model # Populate automatically generated fields in the rows like date times _fill_auto_fields ( model , model_objs ) # Sort the rows to reduce the chances of deadlock during concurrent upserts model_o...
def query ( cls , project = None , status = None , batch = None , parent = None , created_from = None , created_to = None , started_from = None , started_to = None , ended_from = None , ended_to = None , offset = None , limit = None , order_by = None , order = None , api = None ) : """Query ( List ) tasks . Date pa...
api = api or cls . _API if parent : parent = Transform . to_task ( parent ) if project : project = Transform . to_project ( project ) if created_from : created_from = Transform . to_datestring ( created_from ) if created_to : created_to = Transform . to_datestring ( created_to ) if started_from : st...
def strip_msa_100 ( msa , threshold , plot = False ) : """strip out columns of a MSA that represent gaps for X percent ( threshold ) of sequences"""
msa = [ seq for seq in parse_fasta ( msa ) ] columns = [ [ 0 , 0 ] for pos in msa [ 0 ] [ 1 ] ] # [ [ # bases , # gaps ] , [ # bases , # gaps ] , . . . ] for seq in msa : for position , base in enumerate ( seq [ 1 ] ) : if base == '-' or base == '.' : columns [ position ] [ 1 ] += 1 else...
def get_path ( self , wd ) : """Returns the path associated to WD , if WD is unknown it returns None . @ param wd : Watch descriptor . @ type wd : int @ return : Path or None . @ rtype : string or None"""
watch_ = self . _wmd . get ( wd ) if watch_ is not None : return watch_ . path
def update_search_window ( self , search_window , x_center , y_center ) : """update the search area for the lens equation solver : param search _ window : search _ window : window size of the image position search with the lens equation solver . : param x _ center : center of search window : param y _ center ...
self . _search_window , self . _x_center , self . _y_center = search_window , x_center , y_center
def construct_eventstore ( config , section = None ) : """Construct the event store to write and write from / to . The event store is constructed from an optionally given configuration file and / or command line arguments . Command line arguments has higher presendence over configuration file attributes . I...
ESTORE_CLASS_ATTRIBUTE = 'class' if config is None : _logger . warn ( "Using InMemoryEventStore. Events are not persisted." " See example config file on how to persist them." ) # XXX : This is to evade circular dependency between config and # eventstores . import rewind . server . eventstores as eventst...
def get_pending_transfer_pairs ( transfers_pair : List [ MediationPairState ] , ) -> List [ MediationPairState ] : """Return the transfer pairs that are not at a final state ."""
pending_pairs = list ( pair for pair in transfers_pair if pair . payee_state not in STATE_TRANSFER_FINAL or pair . payer_state not in STATE_TRANSFER_FINAL ) return pending_pairs
def copy ( self , ** kwargs ) : """: param kwargs : : return : copy of this object modifying the kwargs"""
for k in kwargs : assert k in self . _keys , 'Invalid key: %s' % k d = self . values ( ) d . update ( kwargs ) return self . __class__ ( ** d )
def _flush ( self ) : """Flush all caches Might be used after classes , methods or fields are added ."""
self . classes_names = None self . __cache_methods = None self . __cached_methods_idx = None self . __cache_fields = None # cache methods and fields as well , otherwise the decompiler is quite slow self . __cache_all_methods = None self . __cache_all_fields = None
def add_firewall_rule ( self , direction , action , src = None , dst = None ) : """Adds a firewall rule to the router . The TunTap router includes a very simple firewall for governing vassal ' s traffic . The first matching rule stops the chain , if no rule applies , the policy is " allow " . : param str | un...
value = [ action ] if src : value . extend ( ( src , dst ) ) self . _set_aliased ( 'router-firewall-%s' % direction . lower ( ) , ' ' . join ( value ) , multi = True ) return self
def seat_button_count ( self ) : """The total number of buttons pressed on all devices on the associated seat after the the event was triggered . For events that are not of type : attr : ` ~ libinput . constant . EventType . TABLET _ TOOL _ BUTTON ` , this property raises : exc : ` AttributeError ` . Retu...
if self . type != EventType . TABLET_TOOL_BUTTON : raise AttributeError ( _wrong_prop . format ( self . type ) ) return self . _libinput . libinput_event_tablet_tool_get_seat_button_count ( self . _handle )
def walk ( self , cli ) : """Walk through children ."""
yield self for c in self . children : for i in c . walk ( cli ) : yield i
def export_comps ( request ) : """Returns a zipfile of the rendered HTML templates in the COMPS _ DIR"""
in_memory = BytesIO ( ) zip = ZipFile ( in_memory , "a" ) comps = settings . COMPS_DIR static = settings . STATIC_ROOT or "" context = RequestContext ( request , { } ) context [ 'debug' ] = False # dump static resources # TODO : inspect each template and only pull in resources that are used for dirname , dirs , filenam...
def add ( self , txt , indent = 0 ) : """Adds some text , no newline will be appended . The text can be indented with the optional argument ' indent ' ."""
if isinstance ( txt , unicode ) : try : txt = str ( txt ) except UnicodeEncodeError : s = [ ] for c in txt : try : s . append ( str ( c ) ) except UnicodeEncodeError : s . append ( repr ( c ) ) txt = '' . join ( s ) self . t...
def getSensorData ( self , name , channel = None ) : """Returns a sensor node"""
return self . _getNodeData ( name , self . _SENSORNODE , channel )
def split_and_load ( arrs , ctx ) : """split and load arrays to a list of contexts"""
assert isinstance ( arrs , ( list , tuple ) ) # split and load loaded_arrs = [ mx . gluon . utils . split_and_load ( arr , ctx , even_split = False ) for arr in arrs ] return zip ( * loaded_arrs )
def rewrite_file_imports ( item , vendored_libs , vendor_dir ) : """Rewrite ' import xxx ' and ' from xxx import ' for vendored _ libs"""
text = item . read_text ( encoding = 'utf-8' ) renames = LIBRARY_RENAMES for k in LIBRARY_RENAMES . keys ( ) : if k not in vendored_libs : vendored_libs . append ( k ) for lib in vendored_libs : to_lib = lib if lib in renames : to_lib = renames [ lib ] text = re . sub ( r'([\n\s]*)import...
def get_main_activities ( self ) : """Return names of the main activities These values are read from the AndroidManifest . xml : rtype : a set of str"""
x = set ( ) y = set ( ) for i in self . xml : if self . xml [ i ] is None : continue activities_and_aliases = self . xml [ i ] . findall ( ".//activity" ) + self . xml [ i ] . findall ( ".//activity-alias" ) for item in activities_and_aliases : # Some applications have more than one MAIN activity . ...
def _handle_double_click ( self , event ) : """Double click with left mouse button focuses the state and toggles the collapse status"""
if event . get_button ( ) [ 1 ] == 1 : # Left mouse button path_info = self . view . tree_view . get_path_at_pos ( int ( event . x ) , int ( event . y ) ) if path_info : # Valid entry was clicked on path = path_info [ 0 ] item_iter = self . tree_store . get_iter ( path ) # Toggle collaps...
def instance ( self , instance_id , display_name = None , instance_type = None , labels = None ) : """Factory to create a instance associated with this client . For example : . . literalinclude : : snippets . py : start - after : [ START bigtable _ create _ prod _ instance ] : end - before : [ END bigtable ...
return Instance ( instance_id , self , display_name = display_name , instance_type = instance_type , labels = labels , )
def _scan_for_tokens ( contents ) : """Scan a string for tokens and return immediate form tokens ."""
# Regexes are in priority order . Changing the order may alter the # behavior of the lexer scanner = re . Scanner ( [ # Things inside quotes ( r"(?<![^\s\(])([\"\'])(?:(?=(\\?))\2.)*?\1(?![^\s\)])" , lambda s , t : ( TokenType . QuotedLiteral , t ) ) , # Numbers on their own ( r"(?<![^\s\(])-?[0-9]+(?![^\s\)\(])" , lam...
def _message ( self ) : """get the message payload"""
filepath = self . _record . file_path try : return load_message ( filepath ) except FileNotFoundError : expire_file ( filepath ) empty = email . message . Message ( ) empty . set_payload ( '' ) return empty
def register_filter_builder ( self , function , ** kwargs ) : """Register a filter function with this : class : ` ~ . Filters ` instance . This function is curried with : class : ` ~ okcupyd . util . currying . curry ` - - that is , it can be invoked partially before it is fully evaluated . This allows us to ...
kwargs [ 'transform' ] = function if kwargs . get ( 'decider' ) : kwargs [ 'decide' ] = kwargs . get ( 'decider' ) return type ( 'filter' , ( self . filter_class , ) , kwargs )
def clone ( self , path = None , * , with_contents = True , ** options ) : """Clone the file ."""
file = File ( path if path else self . path , cwd = options . get ( "cwd" , self . cwd ) ) file . base = options . get ( "base" , self . base ) if with_contents : file . contents = options . get ( "contents" , self . contents ) return file
def parse_global_args ( argv ) : """Parse all global iotile tool arguments . Any flag based argument at the start of the command line is considered as a global flag and parsed . The first non flag argument starts the commands that are passed to the underlying hierarchical shell . Args : argv ( list ) : Th...
parser = create_parser ( ) args = parser . parse_args ( argv ) should_log = args . include or args . exclude or ( args . verbose > 0 ) verbosity = args . verbose root = logging . getLogger ( ) if should_log : formatter = logging . Formatter ( '%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s' , '%y-%m-%...
def _make_grid_of_axes ( self , bounding_rect = cfg . bounding_rect_default , num_rows = cfg . num_rows_per_view_default , num_cols = cfg . num_cols_grid_default , axis_pad = cfg . axis_pad_default , commn_annot = None , ** axis_kwargs ) : """Creates a grid of axes bounded within a given rectangle ."""
axes_in_grid = list ( ) extents = self . _compute_cell_extents_grid ( bounding_rect = bounding_rect , num_cols = num_cols , num_rows = num_rows , axis_pad = axis_pad ) for cell_ext in extents : ax_cell = self . fig . add_axes ( cell_ext , frameon = False , visible = False , ** axis_kwargs ) if commn_annot is no...
def execute_action_list ( obj , target , kw ) : """Actually execute the action list ."""
env = obj . get_build_env ( ) kw = obj . get_kw ( kw ) status = 0 for act in obj . get_action_list ( ) : args = ( [ ] , [ ] , env ) status = act ( * args , ** kw ) if isinstance ( status , SCons . Errors . BuildError ) : status . executor = obj raise status elif status : msg = "E...
async def on_raw_375 ( self , message ) : """Start message of the day ."""
await self . _registration_completed ( message ) self . motd = message . params [ 1 ] + '\n'
def list_domains ( ) : '''Return a list of virtual machine names on the minion CLI Example : . . code - block : : bash salt ' * ' virt . list _ domains'''
with _get_xapi_session ( ) as xapi : hosts = xapi . VM . get_all ( ) ret = [ ] for _host in hosts : if xapi . VM . get_record ( _host ) [ 'is_control_domain' ] is False : ret . append ( xapi . VM . get_name_label ( _host ) ) return ret
def as4_capability ( self , ** kwargs ) : """Set Spanning Tree state . Args : enabled ( bool ) : Is AS4 Capability enabled ? ( True , False ) callback ( function ) : A function executed upon completion of the method . The only parameter passed to ` callback ` will be the ` ` ElementTree ` ` ` config ` . ...
enabled = kwargs . pop ( 'enabled' , True ) callback = kwargs . pop ( 'callback' , self . _callback ) if not isinstance ( enabled , bool ) : raise ValueError ( '%s must be `True` or `False`.' % repr ( enabled ) ) as4_capability_args = dict ( vrf_name = kwargs . pop ( 'vrf' , 'default' ) , rbridge_id = kwargs . pop ...
def bitset ( name , members , base = bases . BitSet , list = False , tuple = False ) : """Return a new bitset class with given name and members . Args : name : Name of the class to be created . members : Hashable sequence of allowed bitset members . base : Base class to derive the returned class from . li...
if not name : raise ValueError ( 'empty bitset name: %r' % name ) if not hasattr ( members , '__getitem__' ) or not hasattr ( members , '__len__' ) : raise ValueError ( 'non-sequence bitset members: %r' % members ) if not len ( members ) : raise ValueError ( 'less than one bitset member: %r' % ( members , )...
def _create_tokens_for_next_line_dent ( self , newline_token ) : """Starting from a newline token that isn ' t followed by another newline token , returns any indent or dedent tokens that immediately follow . If indentation doesn ' t change , returns None ."""
indent_delta = self . _get_next_line_indent_delta ( newline_token ) if indent_delta is None or indent_delta == 0 : # Next line ' s indent isn ' t relevant OR there was no change in # indentation . return None dent_type = 'INDENT' if indent_delta > 0 else 'DEDENT' dent_token = _create_token ( dent_type , '\t' , newl...
def scrape_file ( self , file , encoding = None , base_url = None ) : '''Scrape a file for links . See : meth : ` scrape ` for the return value .'''
elements = self . iter_elements ( file , encoding = encoding ) link_contexts = set ( ) link_infos = self . _element_walker . iter_links ( elements ) for link_info in link_infos : element_base_url = base_url if link_info . base_link : clean_base_url = clean_link_soup ( link_info . base_link ) if ...
def virt_env ( self ) : """Getter for this instance ' s virt env , creates it if needed Returns : lago . virt . VirtEnv : virt env instance used by this prefix"""
if self . _virt_env is None : self . _virt_env = self . _create_virt_env ( ) return self . _virt_env
def get_monitors ( self ) -> List [ Monitor ] : """Get a list of Monitors from the ZoneMinder API ."""
raw_monitors = self . _zm_request ( 'get' , ZoneMinder . MONITOR_URL ) if not raw_monitors : _LOGGER . warning ( "Could not fetch monitors from ZoneMinder" ) return [ ] monitors = [ ] for raw_result in raw_monitors [ 'monitors' ] : _LOGGER . debug ( "Initializing camera %s" , raw_result [ 'Monitor' ] [ 'Id'...
def export_mesh ( vertices , triangles , filename , mesh_name = "mcubes_mesh" ) : """Exports a mesh in the COLLADA ( . dae ) format . Needs PyCollada ( https : / / github . com / pycollada / pycollada ) ."""
import collada mesh = collada . Collada ( ) vert_src = collada . source . FloatSource ( "verts-array" , vertices , ( 'X' , 'Y' , 'Z' ) ) geom = collada . geometry . Geometry ( mesh , "geometry0" , mesh_name , [ vert_src ] ) input_list = collada . source . InputList ( ) input_list . addInput ( 0 , 'VERTEX' , "#verts-arr...
def _inject ( self , value , settings ) : """Inject ` ` settings ` ` into ` ` value ` ` . Go through ` ` value ` ` looking for ` ` { { NAME } } ` ` groups and replace each group with the value of the named item from ` ` settings ` ` . Args : value ( str ) : The value to inject settings into settings : An ...
assert isinstance ( value , string_types ) , 'Expected str; got {0.__class__}' . format ( value ) begin , end = '{{' , '}}' if begin not in value : return value , False new_value = value begin_pos , end_pos = 0 , None len_begin , len_end = len ( begin ) , len ( end ) len_value = len ( new_value ) while begin_pos < ...
def bipartition ( seq ) : """Return a list of bipartitions for a sequence . Args : a ( Iterable ) : The sequence to partition . Returns : list [ tuple [ tuple ] ] : A list of tuples containing each of the two partitions . Example : > > > bipartition ( ( 1,2,3 ) ) [ ( ( ) , ( 1 , 2 , 3 ) ) , ( ( 1 , ...
return [ ( tuple ( seq [ i ] for i in part0_idx ) , tuple ( seq [ j ] for j in part1_idx ) ) for part0_idx , part1_idx in bipartition_indices ( len ( seq ) ) ]
def request_restart ( self , req , msg ) : """Restart the device server . Returns success : { ' ok ' , ' fail ' } Whether scheduling the restart succeeded . Examples ? restart ! restart ok"""
if self . _restart_queue is None : raise FailReply ( "No restart queue registered -- cannot restart." ) f = tornado_Future ( ) @ gen . coroutine def _restart ( ) : # . put should never block because queue should have no size limit self . _restart_queue . put_nowait ( self ) req . reply ( 'ok' ) raise As...
def repair_duplicate_names ( self ) : """Prior to 1101.1.1 , pmxbot would incorrectly create new karma records for individuals with multiple names . This routine corrects those records ."""
for name in self . _all_names ( ) : cur = self . db . find ( { 'names' : name } ) main_doc = next ( cur ) for duplicate in cur : query = { '_id' : main_doc [ '_id' ] } update = { '$inc' : { 'value' : duplicate [ 'value' ] } , '$push' : { 'names' : { '$each' : duplicate [ 'names' ] } } , } ...
def loads_config ( s , parser_params = JSONParserParams ( ) , string_to_scalar_converter = DefaultStringToScalarConverter ( ) ) : """Works similar to the loads ( ) function but this one returns a json object hierarchy that wraps all json objects , arrays and scalars to provide a nice config query syntax . For e...
parser = JSONParser ( parser_params ) object_builder_params = ConfigObjectBuilderParams ( string_to_scalar_converter = string_to_scalar_converter ) listener = ObjectBuilderParserListener ( object_builder_params ) parser . parse ( s , listener ) return listener . result
def context_chunks ( self , context ) : """Retrieves all tokens , divided into the chunks in context ` ` context ` ` . Parameters context : str Context name . Returns chunks : list Each item in ` ` chunks ` ` is a list of tokens ."""
N_chunks = len ( self . contexts [ context ] ) chunks = [ ] for j in xrange ( N_chunks ) : chunks . append ( self . context_chunk ( context , j ) ) return chunks
def Presentation ( pptx = None ) : """Return a | Presentation | object loaded from * pptx * , where * pptx * can be either a path to a ` ` . pptx ` ` file ( a string ) or a file - like object . If * pptx * is missing or ` ` None ` ` , the built - in default presentation " template " is loaded ."""
if pptx is None : pptx = _default_pptx_path ( ) presentation_part = Package . open ( pptx ) . main_document_part if not _is_pptx_package ( presentation_part ) : tmpl = "file '%s' is not a PowerPoint file, content type is '%s'" raise ValueError ( tmpl % ( pptx , presentation_part . content_type ) ) return pr...
def parse ( station : str , txt : str ) -> ( MetarData , Units ) : # type : ignore """Returns MetarData and Units dataclasses with parsed data and their associated units"""
core . valid_station ( station ) return parse_na ( txt ) if core . uses_na_format ( station [ : 2 ] ) else parse_in ( txt )
def ICCdecode ( s ) : """Take an ICC encoded tag , and dispatch on its type signature ( first 4 bytes ) to decode it into a Python value . Pair ( * sig * , * value * ) is returned , where * sig * is a 4 byte string , and * value * is some Python value determined by the content and type ."""
sig = s [ 0 : 4 ] . strip ( ) f = dict ( text = RDtext , XYZ = RDXYZ , curv = RDcurv , vcgt = RDvcgt , sf32 = RDsf32 , ) if sig not in f : return None return ( sig , f [ sig ] ( s ) )
def first_child_found_in ( self , * tagnames ) : """Return the first child found with tag in * tagnames * , or None if not found ."""
for tagname in tagnames : child = self . find ( qn ( tagname ) ) if child is not None : return child return None
def time_to_hhmmssmmm ( time_value , decimal_separator = "." ) : """Format the given time value into a ` ` HH : MM : SS . mmm ` ` string . Examples : : : 12 = > 00:00:12.000 12.345 = > 00:00:12.345 12.345432 = > 00:00:12.345 12.345678 = > 00:00:12.346 83 = > 00:01:23.000 83.456 = > 00:01:23.456 83.4...
if time_value is None : time_value = 0 tmp = time_value hours = int ( math . floor ( tmp / 3600 ) ) tmp -= ( hours * 3600 ) minutes = int ( math . floor ( tmp / 60 ) ) tmp -= minutes * 60 seconds = int ( math . floor ( tmp ) ) tmp -= seconds milliseconds = int ( math . floor ( tmp * 1000 ) ) return "%02d:%02d:%02d%...
def dependencies_of ( self , address ) : """Returns the dependencies of the Target at ` address ` . This method asserts that the address given is actually in the BuildGraph . : API : public"""
assert address in self . _target_by_address , ( 'Cannot retrieve dependencies of {address} because it is not in the BuildGraph.' . format ( address = address ) ) return self . _target_dependencies_by_address [ address ]
def _listFilesPosix ( self ) -> [ 'File' ] : """List Files for POSIX Search and list the files and folder in the current directory for the POSIX file system . @ return : List of directory files and folders ."""
find = "find %s -type f" % self . _path output = check_output ( args = find . split ( ) ) . strip ( ) . decode ( ) . split ( '\n' ) return output
def _select_ontology ( self , line ) : """try to select an ontology NP : the actual load from FS is in < _ load _ ontology >"""
try : var = int ( line ) # it ' s a string if var in range ( 1 , len ( self . all_ontologies ) + 1 ) : self . _load_ontology ( self . all_ontologies [ var - 1 ] ) except ValueError : out = [ ] for each in self . all_ontologies : if line in each : out += [ each ] choic...
def value_to_string ( self , obj ) : """Ensure data is serialized correctly ."""
value = self . value_from_object ( obj ) return self . get_prep_value ( value )
def mk_nested_dic ( path , val , seps = PATH_SEPS ) : """Make a nested dict iteratively . : param path : Path expression to make a nested dict : param val : Value to set : param seps : Separator char candidates > > > mk _ nested _ dic ( " a . b . c " , 1) { ' a ' : { ' b ' : { ' c ' : 1 } } } > > > mk _...
ret = None for key in reversed ( _split_path ( path , seps ) ) : ret = { key : val if ret is None else ret . copy ( ) } return ret
def number ( items ) : """Maps numbering onto given values"""
n = len ( items ) if n == 0 : return items places = str ( int ( math . log10 ( n ) // 1 + 1 ) ) format = '[{0[0]:' + str ( int ( places ) ) + 'd}] {0[1]}' return map ( lambda x : format . format ( x ) , enumerate ( items ) )
def __get_sigmas ( self ) : """will populate the stack _ sigma dictionary with the energy and sigma array for all the compound / element and isotopes"""
stack_sigma = { } _stack = self . stack _file_path = os . path . abspath ( os . path . dirname ( __file__ ) ) _database_folder = os . path . join ( _file_path , 'reference_data' , self . database ) _list_compounds = _stack . keys ( ) for _compound in _list_compounds : _list_element = _stack [ _compound ] [ 'element...
def get ( self ) : """API endpoint to retrieve a list of links to transaction outputs . Returns : A : obj : ` list ` of : cls : ` str ` of links to outputs ."""
parser = reqparse . RequestParser ( ) parser . add_argument ( 'public_key' , type = parameters . valid_ed25519 , required = True ) parser . add_argument ( 'spent' , type = parameters . valid_bool ) args = parser . parse_args ( strict = True ) pool = current_app . config [ 'bigchain_pool' ] with pool ( ) as bigchain : ...
def cache_nodes ( gir_root , all_girs ) : '''Identify and store all the gir symbols the symbols we will document may link to , or be typed with'''
ns_node = gir_root . find ( './{%s}namespace' % NS_MAP [ 'core' ] ) id_prefixes = ns_node . attrib [ '{%s}identifier-prefixes' % NS_MAP [ 'c' ] ] sym_prefixes = ns_node . attrib [ '{%s}symbol-prefixes' % NS_MAP [ 'c' ] ] id_key = '{%s}identifier' % NS_MAP [ 'c' ] for node in gir_root . xpath ( './/*[@c:identifier]' , n...
def get_alert_log ( self , current = 0 , minimum = 0 , maximum = 100 , header = "" , action_key = None ) : """Get the alert log ."""
return self . get_alert ( current = current , minimum = minimum , maximum = maximum , header = header , action_key = action_key , log = True )
def _get_names ( dirs ) : """Get alphabet and label names , union across all dirs ."""
alphabets = set ( ) label_names = { } for d in dirs : for example in _walk_omniglot_dir ( d ) : alphabet , alphabet_char_id , label , _ = example alphabets . add ( alphabet ) label_name = "%s_%d" % ( alphabet , alphabet_char_id ) if label in label_names : assert label_nam...
def get_value ( self ) : """Return memory usage ."""
from spyder . utils . system import memory_usage text = '%d%%' % memory_usage ( ) return 'Mem ' + text . rjust ( 3 )
def project_clone ( object_id , input_params = { } , always_retry = False , ** kwargs ) : """Invokes the / project - xxxx / clone API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Cloning # API - method % 3A - % 2Fclass - xxxx % 2Fclone"""
return DXHTTPRequest ( '/%s/clone' % object_id , input_params , always_retry = always_retry , ** kwargs )
def parse_modes ( modes , current , behaviour ) : """Parse mode change string ( s ) and return updated dictionary ."""
current = current . copy ( ) modes = modes [ : ] # Iterate in a somewhat odd way over the list because we want to modify it during iteration . i = 0 while i < len ( modes ) : piece = modes [ i ] add = True sigiled = False for mode in piece : # Set mode to addition or deletion of modes . if mode ...
def add_resource_types ( resource_i , types ) : """Save a reference to the types used for this resource . @ returns a list of type _ ids representing the type ids on the resource ."""
if types is None : return [ ] existing_type_ids = [ ] if resource_i . types : for t in resource_i . types : existing_type_ids . append ( t . type_id ) new_type_ids = [ ] for templatetype in types : if templatetype . id in existing_type_ids : continue rt_i = ResourceType ( ) rt_i . ty...
def wash_url_argument ( var , new_type ) : """Wash argument into ' new _ type ' , that can be ' list ' , ' str ' , ' int ' , ' tuple ' or ' dict ' . If needed , the check ' type ( var ) is not None ' should be done before calling this function . @ param var : variable value @ param new _ type : variable t...
out = [ ] if new_type == 'list' : # return lst if isinstance ( var , list ) : out = var else : out = [ var ] elif new_type == 'str' : # return str if isinstance ( var , list ) : try : out = "%s" % var [ 0 ] except : out = "" elif isinstance ( var ,...
def get_branches ( path ) : """获取当前所有分支名称的列表 。 : param str path : git 仓库文件夹路径 。 : return : 分支名称列表 。 当前分支位于列表第一项 。 : rtype : list"""
code , output = call ( path , 'branch' , '--list' ) if code > 0 : return None branches = output . split ( '\n' ) newbr = [ None ] for br in branches : if br : if br [ 0 ] == '*' : newbr [ 0 ] = br [ 2 : ] else : newbr . append ( br [ 2 : ] ) return newbr
async def create_link ( project , nodes ) : """Create all possible link of a node"""
node1 = random . choice ( list ( nodes . values ( ) ) ) for port in range ( 0 , 8 ) : node2 = random . choice ( list ( nodes . values ( ) ) ) if node1 == node2 : continue data = { "nodes" : [ { "adapter_number" : 0 , "node_id" : node1 [ "node_id" ] , "port_number" : port } , { "adapter_number" : 0 ,...
def on_event_pre ( self , e : Event ) -> None : """Set values set on browser before calling event listeners ."""
super ( ) . on_event_pre ( e ) ct_msg = e . init . get ( 'currentTarget' , dict ( ) ) if e . type in ( 'input' , 'change' ) : # Update user inputs self . _set_text_content ( ct_msg . get ( 'value' ) or '' )
def transport_closed ( self , ** kwargs ) : """Called by Transports when they close unexpectedly , not as a result of Connection . disconnect ( ) . TODO : document args"""
msg = 'unknown cause' self . logger . warning ( 'transport to %s closed : %s' % ( self . _host , kwargs . get ( 'msg' , msg ) ) ) self . _close_info = { 'reply_code' : kwargs . get ( 'reply_code' , 0 ) , 'reply_text' : kwargs . get ( 'msg' , msg ) , 'class_id' : kwargs . get ( 'class_id' , 0 ) , 'method_id' : kwargs . ...
def align_transcriptome ( fastq_file , pair_file , ref_file , data ) : """bwa mem with settings for aligning to the transcriptome for eXpress / RSEM / etc"""
work_bam = dd . get_work_bam ( data ) base , ext = os . path . splitext ( work_bam ) out_file = base + ".transcriptome" + ext if utils . file_exists ( out_file ) : data = dd . set_transcriptome_bam ( data , out_file ) return data # bwa mem needs phred + 33 quality , so convert if it is Illumina if dd . get_qual...
def create ( curve , data ) : """Creates EC keypair from the just secret key and curve name @ param curve - name of elliptic curve @ param num - byte array or long number representing key"""
ec_key = libcrypto . EC_KEY_new_by_curve_name ( curve . nid ) if ec_key is None : raise PKeyError ( "EC_KEY_new_by_curvename" ) group = libcrypto . EC_KEY_get0_group ( ec_key ) if group is None : raise PKeyError ( "EC_KEY_get0_group" ) libcrypto . EC_GROUP_set_asn1_flag ( group , 1 ) raw_key = libcrypto . BN_ne...
def get_SCAT_points ( x_Arai_segment , y_Arai_segment , tmin , tmax , ptrm_checks_temperatures , ptrm_checks_starting_temperatures , x_ptrm_check , y_ptrm_check , tail_checks_temperatures , tail_checks_starting_temperatures , x_tail_check , y_tail_check ) : """returns relevant points for a SCAT test"""
points = [ ] points_arai = [ ] points_ptrm = [ ] points_tail = [ ] for i in range ( len ( x_Arai_segment ) ) : # uses only the best _ fit segment , so no need for further selection x = x_Arai_segment [ i ] y = y_Arai_segment [ i ] points . append ( ( x , y ) ) points_arai . append ( ( x , y ) ) for num ...
def _new_initial_request ( self , with_body : bool = True ) : '''Return a new Request to be passed to the Web Client .'''
url_record = self . _item_session . url_record url_info = url_record . url_info request = self . _item_session . app_session . factory [ 'WebClient' ] . request_factory ( url_info . url ) self . _populate_common_request ( request ) if with_body : if url_record . post_data or self . _processor . fetch_params . post_...
def two_point_attempts ( self ) : """Returns an ` ` int ` ` of the total number of two point field goals the player attempted during the season ."""
if self . field_goal_attempts and self . three_point_attempts : return int ( self . field_goal_attempts - self . three_point_attempts ) # Occurs when the player didn ' t take any three pointers , so the number # of two pointers the player took is equal to the total number of field # goals the player took . if self ...
def boundary_stawiaski ( graph , label_image , gradient_image ) : # label image is not required to hold continuous ids or to start from 1 r"""Boundary term based on the sum of border voxel pairs differences . An implementation of the boundary term in [ 1 ] _ , suitable to be used with the ` ~ medpy . graphcut . g...
# convert to arrays if necessary label_image = scipy . asarray ( label_image ) gradient_image = scipy . asarray ( gradient_image ) if label_image . flags [ 'F_CONTIGUOUS' ] : # strangely , this one is required to be ctype ordering label_image = scipy . ascontiguousarray ( label_image ) __check_label_image ( label_i...
def bowtie ( self ) : """Create threads and commands for performing reference mapping for qualimap analyses"""
for i in range ( self . cpus ) : # Send the threads to the merge method . : args is empty as I ' m using threads = Thread ( target = self . align , args = ( ) ) # Set the daemon to true - something to do with thread management threads . setDaemon ( True ) # Start the threading threads . start ( ) wi...
def multi_future ( children , quiet_exceptions = ( ) ) : """Wait for multiple asynchronous futures in parallel . This function is similar to ` multi ` , but does not support ` YieldPoints < YieldPoint > ` . . . versionadded : : 4.0 . . versionchanged : : 4.2 If multiple ` ` Futures ` ` fail , any exceptio...
if isinstance ( children , dict ) : keys = list ( children . keys ( ) ) children = children . values ( ) else : keys = None children = list ( map ( convert_yielded , children ) ) assert all ( is_future ( i ) for i in children ) unfinished_children = set ( children ) future = Future ( ) if not children : ...
def applyFilter ( normalized_uri , xrd_data , flt = None ) : """Generate an iterable of endpoint objects given this input data , presumably from the result of performing the Yadis protocol . @ param normalized _ uri : The input URL , after following redirects , as in the Yadis protocol . @ param xrd _ data ...
flt = mkFilter ( flt ) et = parseXRDS ( xrd_data ) endpoints = [ ] for service_element in iterServices ( et ) : endpoints . extend ( flt . getServiceEndpoints ( normalized_uri , service_element ) ) return endpoints
def list_files ( tag = '' , sat_id = None , data_path = None , format_str = None ) : """Return a Pandas Series of every file for chosen satellite data Parameters tag : ( string or NoneType ) Denotes type of file to load . Accepted types are ' ' and ' ascii ' . If ' ' is specified , the primary data type ( a...
if format_str is None and tag is not None : if tag == '' or tag == 'ascii' : ascii_fmt = 'Density_3deg_{year:02d}_{doy:03d}.ascii' return pysat . Files . from_os ( data_path = data_path , format_str = ascii_fmt ) else : raise ValueError ( 'Unrecognized tag name for CHAMP STAR' ) elif for...
def set_field ( self , state , field_name , field_type , value ) : """Sets an instance field ."""
field_ref = SimSootValue_InstanceFieldRef . get_ref ( state = state , obj_alloc_id = self . heap_alloc_id , field_class_name = self . type , field_name = field_name , field_type = field_type ) # store value in java memory state . memory . store ( field_ref , value )
def i2m ( self , pkt , i ) : """" Internal " ( IP as bytes , mask as int ) to " machine " representation ."""
# noqa : E501 mask , ip = i ip = pton_ntop . inet_pton ( socket . AF_INET6 , ip ) return struct . pack ( ">B" , mask ) + ip [ : self . mask2iplen ( mask ) ]
def read_plain_boolean ( file_obj , count ) : """Read ` count ` booleans using the plain encoding ."""
# for bit packed , the count is stored shifted up . But we want to pass in a count , # so we shift up . # bit width is 1 for a single - bit boolean . return read_bitpacked ( file_obj , count << 1 , 1 , logger . isEnabledFor ( logging . DEBUG ) )
def reset ( self ) : """Clears all entries . : return : None"""
for i in range ( len ( self . values ) ) : self . values [ i ] . delete ( 0 , tk . END ) if self . defaults [ i ] is not None : self . values [ i ] . insert ( 0 , self . defaults [ i ] )
def get_stories ( self , * args , ** kwargs ) : """Fetches lists of stories . get / v1 / public / stories : returns : StoryDataWrapper > > > # Find all the stories that involved both Hulk and Wolverine > > > # hulk ' s id : 1009351 > > > # wolverine ' s id : 1009718 > > > m = Marvel ( public _ key , pri...
response = json . loads ( self . _call ( Story . resource_url ( ) , self . _params ( kwargs ) ) . text ) return StoryDataWrapper ( self , response )
def get ( self , * args , ** kwargs ) : """Perform a get request ."""
if 'convert' in kwargs : conversion = kwargs . pop ( 'convert' ) else : conversion = True kwargs = self . _get_keywords ( ** kwargs ) url = self . _create_path ( * args ) request = self . session . get ( url , params = kwargs ) content = request . content self . _request = request return self . convert ( conten...
def _recv_keys ( self , keyids , keyserver = None ) : """Import keys from a keyserver . : param str keyids : A space - delimited string containing the keyids to request . : param str keyserver : The keyserver to request the ` ` keyids ` ` from ; defaults to ` gnupg . GPG . keyserver ` ."""
if not keyserver : keyserver = self . keyserver args = [ '--keyserver {0}' . format ( keyserver ) , '--recv-keys {0}' . format ( keyids ) ] log . info ( 'Requesting keys from %s: %s' % ( keyserver , keyids ) ) result = self . _result_map [ 'import' ] ( self ) proc = self . _open_subprocess ( args ) self . _collect_...
def _group ( self , obj , val , behavior ) : """An internal function used for aggregate " group by " operations ."""
ns = self . Namespace ( ) ns . result = { } iterator = self . _lookupIterator ( val ) def e ( value , index , * args ) : key = iterator ( value , index ) behavior ( ns . result , key , value ) _ . each ( obj , e ) if len ( ns . result ) == 1 : try : return ns . result [ 0 ] except KeyError : ...
def getLayerIndex ( self , layer ) : """Given a reference to a layer , returns the index of that layer in self . layers ."""
for i in range ( len ( self . layers ) ) : if layer == self . layers [ i ] : # shallow cmp return i return - 1 # not in list
def by_pdb ( self , pdb_id , take_top_percentile = 30.0 , cut_off = None , matrix = None , sequence_identity_cut_off = None , silent = None ) : '''Returns a list of all PDB files which contain protein sequences similar to the protein sequences of pdb _ id . Only protein chains are considered in the matching so e ...
self . log ( 'BLASTing {0}' . format ( pdb_id ) , silent , colortext . pcyan ) # Preamble matrix = matrix or self . matrix cut_off = cut_off or self . cut_off sequence_identity_cut_off = sequence_identity_cut_off or self . sequence_identity_cut_off # Parse PDB file p = self . bio_cache . get_pdb_object ( pdb_id ) chain...
def set_level ( self , level = 1 ) : """Set the logging level Parameters level : ` int ` or ` bool ` ( optional , default : 1) If False or 0 , prints WARNING and higher messages . If True or 1 , prints INFO and higher messages . If 2 or higher , prints all messages ."""
if level is True or level == 1 : level = logging . INFO level_name = "INFO" elif level is False or level <= 0 : level = logging . WARNING level_name = "WARNING" elif level >= 2 : level = logging . DEBUG level_name = "DEBUG" if not self . logger . handlers : self . logger . tasklogger = self ...
def _set_ca ( self , v , load = False ) : """Setter method for ca , mapped from YANG variable / rbridge _ id / crypto / ca ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ ca is considered as a private method . Backends looking to populate this variable should...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "trustpoint" , ca . ca , yang_name = "ca" , rest_name = "ca" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'trustpoint' , extensions = { u'tail...
def get_sequence_rule_lookup_session_for_bank ( self , bank_id , proxy ) : """Gets the ` ` OsidSession ` ` associated with the sequence rule lookup service for the given bank . arg : bank _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Bank ` ` arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osi...
if not self . supports_sequence_rule_lookup ( ) : raise errors . Unimplemented ( ) # Also include check to see if the catalog Id is found otherwise raise errors . NotFound # pylint : disable = no - member return sessions . SequenceRuleLookupSession ( bank_id , proxy , self . _runtime )
def shot_chart_jointplot ( x , y , data = None , kind = "scatter" , title = "" , color = "b" , cmap = None , xlim = ( - 250 , 250 ) , ylim = ( 422.5 , - 47.5 ) , court_color = "gray" , court_lw = 1 , outer_lines = False , flip_court = False , size = ( 12 , 11 ) , space = 0 , despine = False , joint_kws = None , margina...
# If a colormap is not provided , then it is based off of the color if cmap is None : cmap = sns . light_palette ( color , as_cmap = True ) if kind not in [ "scatter" , "kde" , "hex" ] : raise ValueError ( "kind must be 'scatter', 'kde', or 'hex'." ) grid = sns . jointplot ( x = x , y = y , data = data , stat_f...
def list_ifd ( self ) : """Return the list of IFDs in the header ."""
i = self . _first_ifd ( ) ifds = [ ] while i : ifds . append ( i ) i = self . _next_ifd ( i ) return ifds
def regex_check ( equation_str ) : """A quick regular expression check to see that the input is sane Args : equation _ str ( str ) : String of equation to be parsed by sympify function . Expected to be valid Python . Raises : BadInputError : If input does not look safe to parse as an equation ."""
match1 = re . match ( r'^(([xy+\-*/()0-9. ]+|sin\(|cos\(|exp\(|log\()?)+$' , equation_str ) match2 = re . match ( r'^.*([xy]) *([xy]).*$' , equation_str ) if match1 and not match2 : return True raise BadInputError ( 'Cannot parse entered equation' )
def get_information ( self ) : """Return information about the connected bank . Note : Can only be filled after the first communication with the bank . If in doubt , use a construction like : : f = FinTS3Client ( . . . ) with f : info = f . get _ information ( ) Returns a nested dictionary : : bank : ...
retval = { 'bank' : { } , 'accounts' : [ ] , 'auth' : { } , } if self . bpa : retval [ 'bank' ] [ 'name' ] = self . bpa . bank_name if self . bpd . segments : retval [ 'bank' ] [ 'supported_operations' ] = { op : any ( self . bpd . find_segment_first ( cmd [ 0 ] + 'I' + cmd [ 2 : ] + 'S' ) for cmd in op . value...
def do_hdr ( self , line , hdrs_usr ) : """Initialize self . h2i ."""
# If there is no header hint , consider the first line the header . if self . hdr_ex is None : self . _init_hdr ( line , hdrs_usr ) return True # If there is a header hint , examine each beginning line until header hint is found . elif self . hdr_ex in line : self . _init_hdr ( line , hdrs_usr ) return ...
def router_fabric_virtual_gateway_address_family_ipv4_gratuitous_arp_timer ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) router = ET . SubElement ( config , "router" , xmlns = "urn:brocade.com:mgmt:brocade-common-def" ) fabric_virtual_gateway = ET . SubElement ( router , "fabric-virtual-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-anycast-gateway" ) address_family = ET . SubElement ( fabric_virtual_...