signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _decode_embedded_list ( src ) : '''Convert enbedded bytes to strings if possible . List helper .'''
output = [ ] for elem in src : if isinstance ( elem , dict ) : elem = _decode_embedded_dict ( elem ) elif isinstance ( elem , list ) : elem = _decode_embedded_list ( elem ) # pylint : disable = redefined - variable - type elif isinstance ( elem , bytes ) : try : e...
def get_git_ref ( self , ref ) : """: calls : ` GET / repos / : owner / : repo / git / refs / : ref < http : / / developer . github . com / v3 / git / refs > ` _ : param ref : string : rtype : : class : ` github . GitRef . GitRef `"""
prefix = "/git/refs/" if not self . _requester . FIX_REPO_GET_GIT_REF : prefix = "/git/" assert isinstance ( ref , ( str , unicode ) ) , ref headers , data = self . _requester . requestJsonAndCheck ( "GET" , self . url + prefix + ref ) return github . GitRef . GitRef ( self . _requester , headers , data , completed...
def process ( self , model = None , context = None ) : """Perform validation and filtering at the same time , return a validation result object . : param model : object or dict : param context : object , dict or None : return : shiftschema . result . Result"""
self . filter ( model , context ) return self . validate ( model , context )
def cleandata ( inputlist ) : """Helper function for parse . getdata . Remove empty variables , convert strings to float args : inputlist : list List of Variables Returns : ouput : Cleaned list"""
output = [ ] for e in inputlist : new = [ ] for f in e : if f == "--" : new . append ( None ) else : new . append ( float ( f ) ) output . append ( new ) return output
def dynamic_content_item_variants ( self , id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / dynamic _ content # list - variants"
api_path = "/api/v2/dynamic_content/items/{id}/variants.json" api_path = api_path . format ( id = id ) return self . call ( api_path , ** kwargs )
def patch_namespaced_replication_controller_dummy_scale ( self , name , namespace , body , ** kwargs ) : # noqa : E501 """patch _ namespaced _ replication _ controller _ dummy _ scale # noqa : E501 partially update scale of the specified ReplicationControllerDummy # noqa : E501 This method makes a synchronous H...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . patch_namespaced_replication_controller_dummy_scale_with_http_info ( name , namespace , body , ** kwargs ) # noqa : E501 else : ( data ) = self . patch_namespaced_replication_controller_dummy_scale_with_http_info ( na...
def ogrn ( self ) -> str : """Generate random valid ` ` OGRN ` ` . : return : OGRN . : Example : 4715113303725."""
numbers = [ ] for _ in range ( 0 , 12 ) : numbers . append ( self . random . randint ( 1 if _ == 0 else 0 , 9 ) ) ogrn = '' . join ( [ str ( x ) for x in numbers ] ) check_sum = str ( int ( ogrn ) % 11 % 10 ) return '{}{}' . format ( ogrn , check_sum )
def refresh ( self ) : '''Refresh this item from data on the server . Will save any unsaved data first .'''
if not self . _item_path : raise AttributeError ( 'refresh is not available for %s' % self . _type ) if not self . id : raise RedmineError ( '%s did not come from the Redmine server - no link.' % self . _type ) try : self . save ( ) except : pass # Mimic the Redmine _ Item _ Manager . get command target...
def p_fragment_definition1 ( self , p ) : """fragment _ definition : FRAGMENT fragment _ name ON type _ condition directives selection _ set"""
p [ 0 ] = FragmentDefinition ( name = p [ 2 ] , type_condition = p [ 4 ] , selections = p [ 6 ] , directives = p [ 5 ] )
def description ( self ) : """Get the textual description of the category"""
if self . _meta and self . _meta . get_payload ( ) : return utils . TrueCallableProxy ( self . _description ) return utils . CallableProxy ( None )
def _construct_operation_id ( self , service_name , protorpc_method_name ) : """Return an operation id for a service method . Args : service _ name : The name of the service . protorpc _ method _ name : The ProtoRPC method name . Returns : A string representing the operation id ."""
# camelCase the ProtoRPC method name method_name_camel = util . snake_case_to_headless_camel_case ( protorpc_method_name ) return '{0}_{1}' . format ( service_name , method_name_camel )
def slugify ( value ) : """Converts to lowercase , removes non - word characters ( alphanumerics and underscores ) and converts spaces to hyphens . Also strips leading and trailing whitespace ."""
if six . PY3 : value = str ( value ) else : value = unicode ( value ) value = unicodedata . normalize ( 'NFKD' , value ) . encode ( 'ascii' , 'ignore' ) . decode ( 'ascii' ) value = to_remove . sub ( '' , value ) . strip ( ) . lower ( ) return remove_dup . sub ( '-' , value )
def run_from_command_line ( ) : """Run Firenado ' s management commands from a command line"""
for commands_conf in firenado . conf . management [ 'commands' ] : logger . debug ( "Loading %s commands from %s." % ( commands_conf [ 'name' ] , commands_conf [ 'module' ] ) ) exec ( 'import %s' % commands_conf [ 'module' ] ) command_index = 1 for arg in sys . argv [ 1 : ] : command_index += 1 if arg [...
def interp_like ( self , other , method = 'linear' , assume_sorted = False , kwargs = { } ) : """Interpolate this object onto the coordinates of another object , filling out of range values with NaN . Parameters other : Dataset or DataArray Object with an ' indexes ' attribute giving a mapping from dimensio...
if self . dtype . kind not in 'uifc' : raise TypeError ( 'interp only works for a numeric type array. ' 'Given {}.' . format ( self . dtype ) ) ds = self . _to_temp_dataset ( ) . interp_like ( other , method = method , kwargs = kwargs , assume_sorted = assume_sorted ) return self . _from_temp_dataset ( ds )
def index ( args ) : """% prog index samfile / bamfile If SAM file , convert to BAM , sort and then index , using SAMTOOLS"""
p = OptionParser ( index . __doc__ ) p . add_option ( "--fasta" , dest = "fasta" , default = None , help = "add @SQ header to the BAM file [default: %default]" ) p . add_option ( "--unique" , default = False , action = "store_true" , help = "only retain uniquely mapped reads [default: %default]" ) p . set_cpus ( ) opts...
def create_osd_keyring ( conn , cluster , key ) : """Run on osd node , writes the bootstrap key if not there yet ."""
logger = conn . logger path = '/var/lib/ceph/bootstrap-osd/{cluster}.keyring' . format ( cluster = cluster , ) if not conn . remote_module . path_exists ( path ) : logger . warning ( 'osd keyring does not exist yet, creating one' ) conn . remote_module . write_keyring ( path , key )
def _validate ( self ) : '''Validate the mappings .'''
self . _validate_fasta_vs_seqres ( ) self . _validate_mapping_signature ( ) self . _validate_id_types ( ) self . _validate_residue_types ( )
def sequence_prep ( self ) : """Create metadata objects for all PacBio assembly FASTA files in the sequencepath . Create individual subdirectories for each sample . Relative symlink the original FASTA file to the appropriate subdirectory"""
# Create a sorted list of all the FASTA files in the sequence path strains = sorted ( glob ( os . path . join ( self . fastapath , '*.fa*' . format ( self . fastapath ) ) ) ) for sample in strains : # Create the object metadata = MetadataObject ( ) # Set the sample name to be the file name of the sequence by re...
def get_provider_metadata ( self ) : """Gets the metadata for a provider . return : ( osid . Metadata ) - metadata for the provider * compliance : mandatory - - This method must be implemented . *"""
metadata = dict ( self . _mdata [ 'provider' ] ) metadata . update ( { 'existing_id_values' : self . _my_map [ 'providerId' ] } ) return Metadata ( ** metadata )
def save_features_and_arrays ( features , arrays , prefix , compressed = False , link_features = False , overwrite = False ) : """Saves NumPy arrays of processed data , along with the features that correspond to each row , to files for later use . Two files will be saved , both starting with ` prefix ` : pref...
if link_features : if isinstance ( features , pybedtools . BedTool ) : assert isinstance ( features . fn , basestring ) features_filename = features . fn else : assert isinstance ( features , basestring ) features_filename = features if overwrite : force_flag = '-f' ...
def get_error ( self , errstr ) : '''Parse out an error and return a targeted error string'''
for line in errstr . split ( '\n' ) : if line . startswith ( 'ssh:' ) : return line if line . startswith ( 'Pseudo-terminal' ) : continue if 'to the list of known hosts.' in line : continue return line return errstr
def project_get ( project_id = None , name = None , profile = None , ** connection_args ) : '''Return a specific projects ( keystone project - get ) Overrides keystone tenant - get form api V2. For keystone api V3 only . . . versionadded : : 2016.11.0 project _ id The project id . name The project nam...
auth ( profile , ** connection_args ) if _OS_IDENTITY_API_VERSION > 2 : return tenant_get ( tenant_id = project_id , name = name , profile = None , ** connection_args ) else : return False
def ReliefF_compute_scores ( inst , attr , nan_entries , num_attributes , mcmap , NN , headers , class_type , X , y , labels_std , data_type ) : """Unique scoring procedure for ReliefF algorithm . Scoring based on k nearest hits and misses of current target instance ."""
scores = np . zeros ( num_attributes ) for feature_num in range ( num_attributes ) : scores [ feature_num ] += compute_score ( attr , mcmap , NN , feature_num , inst , nan_entries , headers , class_type , X , y , labels_std , data_type ) return scores
def _run_forever ( self ) : """Run configured jobs until termination request ."""
while True : try : tick = time . time ( ) asyncore . loop ( timeout = self . POLL_TIMEOUT , use_poll = True ) # Sleep for remaining poll cycle time tick += self . POLL_TIMEOUT - time . time ( ) if tick > 0 : # wait POLL _ TIMEOUT at most ( robust against time shifts ) ...
def cummax ( self , axis = 0 , ** kwargs ) : """Cumulative max for each group ."""
if axis != 0 : return self . apply ( lambda x : np . maximum . accumulate ( x , axis ) ) return self . _cython_transform ( 'cummax' , numeric_only = False )
def create ( self , unique_name , domain_suffix = values . unset ) : """Create a new EnvironmentInstance : param unicode unique _ name : The unique _ name : param unicode domain _ suffix : The domain _ suffix : returns : Newly created EnvironmentInstance : rtype : twilio . rest . serverless . v1 . service ....
data = values . of ( { 'UniqueName' : unique_name , 'DomainSuffix' : domain_suffix , } ) payload = self . _version . create ( 'POST' , self . _uri , data = data , ) return EnvironmentInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , )
def query_nvidia_smi ( device_ids : List [ int ] , result_queue : multiprocessing . Queue ) -> None : """Runs nvidia - smi to determine the memory usage . : param device _ ids : A list of devices for which the the memory usage will be queried . : param result _ queue : The queue to which the result dictionary o...
device_id_strs = [ str ( device_id ) for device_id in device_ids ] query = "--query-gpu=index,memory.used,memory.total" format_arg = "--format=csv,noheader,nounits" try : sp = subprocess . Popen ( [ 'nvidia-smi' , query , format_arg , "-i" , "," . join ( device_id_strs ) ] , stdout = subprocess . PIPE , stderr = su...
def list ( ) : """Use this function to display all of the stored URLs . This command is used for displaying all of the URLs and their names from the stored list ."""
for name , url in get_all_data ( ) . items ( ) : echo ( '{}: {}' . format ( style ( name , fg = 'blue' ) , style ( url , fg = 'green' ) ) )
def get_observation ( observation_id : int ) -> Dict [ str , Any ] : """Get details about an observation . : param observation _ id : : returns : a dict with details on the observation : raises : ObservationNotFound"""
r = get_observations ( params = { 'id' : observation_id } ) if r [ 'results' ] : return r [ 'results' ] [ 0 ] raise ObservationNotFound ( )
def get_param_type_indexes ( self , data , name = None , prev = None ) : """Get from a docstring a parameter type indexes . In javadoc style it is after @ type . : param data : string to parse : param name : the name of the parameter ( Default value = None ) : param prev : index after the previous element (...
start , end = - 1 , - 1 stl_type = self . opt [ 'type' ] [ self . style [ 'in' ] ] [ 'name' ] if not prev : _ , prev = self . get_param_description_indexes ( data ) if prev >= 0 : if self . style [ 'in' ] in self . tagstyles + [ 'unknown' ] : idx = self . get_elem_index ( data [ prev : ] ) if id...
def run ( self ) : """Executes the experiment ."""
logger . info ( "Initializing..." ) javabridge . call ( self . jobject , "initialize" , "()V" ) logger . info ( "Running..." ) javabridge . call ( self . jobject , "runExperiment" , "()V" ) logger . info ( "Finished..." ) javabridge . call ( self . jobject , "postProcess" , "()V" )
def request ( self ) : """Returns a callable and an iterable respectively . Those can be used to both transmit a message and / or iterate over incoming messages , that were replied by a reply socket . Note that the iterable returns as many parts as sent by repliers . Also , the sender function has a ` ` pri...
sock = self . __sock ( zmq . REQ ) return self . __send_function ( sock ) , self . __recv_generator ( sock )
def revoke_sudo_privileges ( request ) : """Revoke sudo privileges from a request explicitly"""
request . _sudo = False if COOKIE_NAME in request . session : del request . session [ COOKIE_NAME ]
def simxGetUISlider ( clientID , uiHandle , uiButtonID , operationMode ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
position = ct . c_int ( ) return c_GetUISlider ( clientID , uiHandle , uiButtonID , ct . byref ( position ) , operationMode ) , position . value
def write ( self , path = None , * args , ** kwargs ) : """Perform formatting and write the formatted string to a file or stdout . Optional arguments can be used to format the editor ' s contents . If no file path is given , prints to standard output . Args : path ( str ) : Full file path ( default None , p...
if path is None : print ( self . format ( * args , ** kwargs ) ) else : with io . open ( path , 'w' , newline = "" ) as f : f . write ( self . format ( * args , ** kwargs ) )
def color_map_data ( self , data : numpy . ndarray ) -> None : """Set the data and mark the canvas item for updating . Data should be an ndarray of shape ( 256 , 3 ) with type uint8"""
self . __color_map_data = data self . update ( )
def aa3_to_aa1 ( seq ) : """convert string of 3 - letter amino acids to 1 - letter amino acids > > > aa3 _ to _ aa1 ( " CysAlaThrSerAlaArgGluLeuAlaMetGlu " ) ' CATSARELAME ' > > > aa3 _ to _ aa1 ( None )"""
if seq is None : return None return "" . join ( aa3_to_aa1_lut [ aa3 ] for aa3 in [ seq [ i : i + 3 ] for i in range ( 0 , len ( seq ) , 3 ) ] )
def fill_dataset_tree ( self , tree , data_sets ) : """fills the tree with data sets where datasets is a dictionary of the form Args : tree : data _ sets : a dataset Returns :"""
tree . model ( ) . removeRows ( 0 , tree . model ( ) . rowCount ( ) ) for index , ( time , script ) in enumerate ( data_sets . items ( ) ) : name = script . settings [ 'tag' ] type = script . name item_time = QtGui . QStandardItem ( str ( time ) ) item_name = QtGui . QStandardItem ( str ( name ) ) i...
def stream_header ( self , f ) : """Stream the block header in the standard way to the file - like object f ."""
stream_struct ( "L##LLL" , f , self . version , self . previous_block_hash , self . merkle_root , self . timestamp , self . difficulty , self . nonce )
def plaintext ( self , result ) : """Converts the image object into an ascii representation . Code taken from http : / / a - eter . blogspot . com / 2010/04 / image - to - ascii - art - in - python . html"""
from PIL import Image ascii_chars = [ '#' , 'A' , '@' , '%' , 'S' , '+' , '<' , '*' , ':' , ',' , '.' ] def image_to_ascii ( image ) : image_as_ascii = [ ] all_pixels = list ( image . getdata ( ) ) for pixel_value in all_pixels : index = pixel_value / 25 # 0 - 10 image_as_ascii . app...
def removeAxis ( self , axis ) : """Removes an axis from this chart either by direct reference or by name . : param axis | < projexui . widgets . XChartAxis > | | < str >"""
if not isinstance ( axis , XChartAxis ) : axis = self . axis ( nativestring ( axis ) ) try : self . _axes . remove ( axis ) except ValueError : pass
def _collapse_root ( master , current , dsn , pc ) : """Collapse the root items of the current time series entry : param dict master : LiPD data ( so far ) : param dict current : Current time series entry : param str dsn : Dataset name : param str pc : paleoData or chronData ( mode ) : return dict master ...
logger_ts . info ( "enter collapse_root" ) _tmp_fund = { } _tmp_pub = { } # The tmp lipd data that we ' ll place in master later _tmp_master = { 'pub' : [ ] , 'geo' : { 'geometry' : { 'coordinates' : [ ] } , 'properties' : { } } , 'funding' : [ ] , 'paleoData' : { } , "chronData" : { } } # _ raw = _ switch [ pc ] _c_ke...
def init_with_context ( self , context ) : """Please refer to : meth : ` ~ admin _ tools . menu . items . MenuItem . init _ with _ context ` documentation from : class : ` ~ admin _ tools . menu . items . MenuItem ` class ."""
items = self . _visible_models ( context [ 'request' ] ) for model , perms in items : if not ( perms [ 'change' ] or perms . get ( 'view' , False ) ) : continue title = model . _meta . verbose_name_plural url = self . _get_admin_change_url ( model , context ) item = MenuItem ( title = title , ur...
def parse_value ( self , text : str ) -> Optional [ bool ] : """Parse boolean value . Args : text : String representation of the value ."""
if text == "true" : return True if text == "false" : return False
def __set_revlookup_auth_string ( self , username , password ) : '''Creates and sets the authentication string for accessing the reverse lookup servlet . No return , the string is set as an attribute to the client instance . : param username : Username . : param password : Password .'''
auth = b2handle . utilhandle . create_authentication_string ( username , password ) self . __revlookup_auth_string = auth
def to_representation ( self , value ) : """List of object instances - > List of dicts of primitive datatypes ."""
return { six . text_type ( key ) : self . child . to_representation ( val ) for key , val in value . items ( ) }
def predict_without_uncertainties ( self , mjd , complain = True ) : """Predict the object position at a given MJD . The return value is a tuple ` ` ( ra , dec ) ` ` , in radians , giving the predicted position of the object at * mjd * . Unlike : meth : ` predict ` , the astrometric uncertainties are ignored ...
import sys self . verify ( complain = complain ) planets , ts = load_skyfield_data ( ) # might download stuff from the internet earth = planets [ 'earth' ] t = ts . tdb ( jd = mjd + 2400000.5 ) # " Best " position . The implementation here is a bit weird to keep # parallelism with predict ( ) . args = { 'ra_hours' : se...
def _retrieve ( self ) : """Query Apache Tomcat Server Status Page in XML format and return the result as an ElementTree object . @ return : ElementTree object of Status Page XML ."""
url = "%s://%s:%d/manager/status" % ( self . _proto , self . _host , self . _port ) params = { } params [ 'XML' ] = 'true' response = util . get_url ( url , self . _user , self . _password , params ) tree = ElementTree . XML ( response ) return tree
def schedule ( self ) : """Initiate distribution of the test collection . Initiate scheduling of the items across the nodes . If this gets called again later it behaves the same as calling ` ` . _ reschedule ( ) ` ` on all nodes so that newly added nodes will start to be used . If ` ` . collection _ is _ co...
assert self . collection_is_completed # Initial distribution already happened , reschedule on all nodes if self . collection is not None : for node in self . nodes : self . _reschedule ( node ) return # Check that all nodes collected the same tests if not self . _check_nodes_have_same_collection ( ) : ...
def instance_admin_api ( self ) : """Helper for session - related API calls ."""
if self . _instance_admin_api is None : self . _instance_admin_api = InstanceAdminClient ( credentials = self . credentials , client_info = _CLIENT_INFO ) return self . _instance_admin_api
def decompress_messages ( self , partitions_offmsgs ) : """Decompress pre - defined compressed fields for each message ."""
for pomsg in partitions_offmsgs : if pomsg [ 'message' ] : pomsg [ 'message' ] = self . decompress_fun ( pomsg [ 'message' ] ) yield pomsg
def proxy_fetch ( self , env , url ) : """Proxy mode only endpoint that handles OPTIONS requests and COR fetches for Preservation Worker . Due to normal cross - origin browser restrictions in proxy mode , auto fetch worker cannot access the CSS rules of cross - origin style sheets and must re - fetch them in a ...
if not self . is_proxy_enabled ( env ) : # we are not in proxy mode so just respond with forbidden return WbResponse . text_response ( 'proxy mode must be enabled to use this endpoint' , status = '403 Forbidden' ) if env . get ( 'REQUEST_METHOD' ) == 'OPTIONS' : return WbResponse . options_response ( env ) # en...
def unique ( ar ) : r"""Find the unique elements of an array . It uses ` ` dask . array . unique ` ` if necessary . Args : ar ( array _ like ) : Input array . Returns : array _ like : the sorted unique elements ."""
import dask . array as da if isinstance ( ar , da . core . Array ) : return da . unique ( ar ) return _unique ( ar )
def performance_view ( dstore ) : """Returns the performance view as a numpy array ."""
data = sorted ( dstore [ 'performance_data' ] , key = operator . itemgetter ( 0 ) ) out = [ ] for operation , group in itertools . groupby ( data , operator . itemgetter ( 0 ) ) : counts = 0 time = 0 mem = 0 for _operation , time_sec , memory_mb , counts_ in group : counts += counts_ tim...
def contributors ( self , sr , limit = None ) : """Login required . GETs list of contributors to subreddit ` ` sr ` ` . Returns : class : ` things . ListBlob ` object . * * NOTE * * : The : class : ` things . Account ` objects in the returned ListBlob * only * have ` ` id ` ` and ` ` name ` ` set . This is becaus...
userlist = self . _limit_get ( 'r' , sr , 'about' , 'contributors' , limit = limit ) return _process_userlist ( userlist )
def _define_array_view ( data_type ) : """Define a new view object for a ` Array ` type ."""
element_type = data_type . element_type element_view = _resolve_view ( element_type ) if element_view is None : mixins = ( _DirectArrayViewMixin , ) attributes = _get_mixin_attributes ( mixins ) elif isinstance ( element_type , _ATOMIC ) : mixins = ( _IndirectAtomicArrayViewMixin , ) attributes = _get_m...
def from_string ( cls , s ) : """Instantiate Relations from a relations string ."""
tables = [ ] seen = set ( ) current_table = None lines = list ( reversed ( s . splitlines ( ) ) ) # to pop ( ) in right order while lines : line = lines . pop ( ) . strip ( ) table_m = re . match ( r'^(?P<table>\w.+):$' , line ) field_m = re . match ( r'\s*(?P<name>\S+)' r'(\s+(?P<attrs>[^#]+))?' r'(\s*#\s*...
def create_response ( self , request , content , content_type ) : """Returns a response object for the request . Can be overridden to return different responses ."""
return HttpResponse ( content = content , content_type = content_type )
def _status_query ( query , hostname , enumerate = None , service = None ) : '''Send query along to Nagios .'''
config = _config ( ) data = None params = { 'hostname' : hostname , 'query' : query , } ret = { 'result' : False } if enumerate : params [ 'formatoptions' ] = 'enumerate' if service : params [ 'servicedescription' ] = service if config [ 'username' ] and config [ 'password' ] is not None : auth = ( config [...
def fixed_length ( cls , l , allow_empty = False ) : """Create a sedes for text data with exactly ` l ` encoded characters ."""
return cls ( l , l , allow_empty = allow_empty )
def listmetadataformats ( ** kwargs ) : """Create OAI - PMH response for ListMetadataFormats verb ."""
cfg = current_app . config e_tree , e_listmetadataformats = verb ( ** kwargs ) if 'identifier' in kwargs : # test if record exists OAIIDProvider . get ( pid_value = kwargs [ 'identifier' ] ) for prefix , metadata in cfg . get ( 'OAISERVER_METADATA_FORMATS' , { } ) . items ( ) : e_metadataformat = SubElement ( e...
def cast_to_str ( obj ) : """Return a string representation of a Seq or SeqRecord . Args : obj ( str , Seq , SeqRecord ) : Biopython Seq or SeqRecord Returns : str : String representation of the sequence"""
if isinstance ( obj , str ) : return obj if isinstance ( obj , Seq ) : return str ( obj ) if isinstance ( obj , SeqRecord ) : return str ( obj . seq ) else : raise ValueError ( 'Must provide a string, Seq, or SeqRecord object.' )
def hexraw ( self , lfilter = None ) : """Same as nsummary ( ) , except that if a packet has a Raw layer , it will be hexdumped # noqa : E501 lfilter : a truth function that decides whether a packet must be displayed"""
# noqa : E501 for i , res in enumerate ( self . res ) : p = self . _elt2pkt ( res ) if lfilter is not None and not lfilter ( p ) : continue print ( "%s %s %s" % ( conf . color_theme . id ( i , fmt = "%04i" ) , p . sprintf ( "%.time%" ) , self . _elt2sum ( res ) ) ) if p . haslayer ( conf . raw_l...
def select_distinct ( self , table , cols = '*' , execute = True ) : """Query distinct values from a table ."""
return self . select ( table , cols , execute , select_type = 'SELECT DISTINCT' )
def create_user ( self , name , password ) : """Create user with hashed password ."""
hashed_password = self . _password_hasher ( password ) return dict ( name = name , password = hashed_password )
def _int_size ( x ) : """Return the smallest size int that can store the value"""
if - 0x80 <= x <= 0x7F : return 1 elif - 0x8000 <= x <= 0x7FFF : return 2 elif - 0x80000000 <= x <= 0x7FFFFFFF : return 4 elif long ( - 0x8000000000000000 ) <= x <= long ( 0x7FFFFFFFFFFFFFFF ) : return 8 else : raise RuntimeError ( "Cannot represent value: " + str ( x ) )
def sign ( self , keypair ) : """Sign this transaction envelope with a given keypair . Note that the signature must not already be in this instance ' s list of signatures . : param keypair : The keypair to use for signing this transaction envelope . : type keypair : : class : ` Keypair < stellar _ base . ...
assert isinstance ( keypair , Keypair ) tx_hash = self . hash_meta ( ) sig = keypair . sign_decorated ( tx_hash ) sig_dict = [ signature . __dict__ for signature in self . signatures ] if sig . __dict__ in sig_dict : raise SignatureExistError ( 'The keypair has already signed' ) else : self . signatures . appen...
def process_input ( self , encoded_stream , value ) : """Process or drop a graph input . This method asynchronously queued an item to be processed by the sensorgraph worker task in _ reset _ vector . It must be called from inside the emulation loop and returns immediately before the input is processed ."""
if not self . enabled : return if isinstance ( encoded_stream , str ) : stream = DataStream . FromString ( encoded_stream ) encoded_stream = stream . encode ( ) elif isinstance ( encoded_stream , DataStream ) : stream = encoded_stream encoded_stream = stream . encode ( ) else : stream = DataStre...
from typing import List def compute_parentheses_depth ( parens_str : str ) -> List [ int ] : """Function evaluates a string consisting of multiple groups of nested parentheses separated by spaces . For each group , the function output is the deepest level of parentheses nesting . For instance , ( ( ) ( ) ) has ...
def max_parentheses_depth ( paren_group ) : current_depth = 0 maximum_depth = 0 for char in paren_group : if char == '(' : current_depth += 1 maximum_depth = max ( current_depth , maximum_depth ) else : current_depth -= 1 return maximum_depth return [ ...
def safe_pow ( base , exp ) : """safe version of pow"""
if exp > MAX_EXPONENT : raise RuntimeError ( "Invalid exponent, max exponent is {}" . format ( MAX_EXPONENT ) ) return base ** exp
def restrict_input_to_index ( df_or_dict , column_id , index ) : """Restrict df _ or _ dict to those ids contained in index . : param df _ or _ dict : a pandas DataFrame or a dictionary . : type df _ or _ dict : pandas . DataFrame or dict : param column _ id : it must be present in the pandas DataFrame or in ...
if isinstance ( df_or_dict , pd . DataFrame ) : df_or_dict_restricted = df_or_dict [ df_or_dict [ column_id ] . isin ( index ) ] elif isinstance ( df_or_dict , dict ) : df_or_dict_restricted = { kind : df [ df [ column_id ] . isin ( index ) ] for kind , df in df_or_dict . items ( ) } else : raise TypeError ...
def any_path_path ( cls , project , database , document , any_path ) : """Return a fully - qualified any _ path string ."""
return google . api_core . path_template . expand ( "projects/{project}/databases/{database}/documents/{document}/{any_path=**}" , project = project , database = database , document = document , any_path = any_path , )
def _run_rtg_eval ( vrn_file , rm_file , rm_interval_file , base_dir , data , validate_method ) : """Run evaluation of a caller against the truth set using rtg vcfeval ."""
out_dir = os . path . join ( base_dir , "rtg" ) if not utils . file_exists ( os . path . join ( out_dir , "done" ) ) : if os . path . exists ( out_dir ) : shutil . rmtree ( out_dir ) vrn_file , rm_file , interval_bed = _prepare_inputs ( vrn_file , rm_file , rm_interval_file , base_dir , data ) rtg_r...
def map_drawn_samples ( selected_pairs_by_state , trajectories , top = None ) : """Lookup trajectory frames using pairs of ( trajectory , frame ) indices . Parameters selected _ pairs _ by _ state : array , dtype = int , shape = ( n _ states , n _ samples , 2) selected _ pairs _ by _ state [ state , sample ] ...
frames_by_state = [ ] for state , pairs in enumerate ( selected_pairs_by_state ) : if isinstance ( trajectories [ 0 ] , str ) : if top : process = lambda x , frame : md . load_frame ( x , frame , top = top ) else : process = lambda x , frame : md . load_frame ( x , frame ) ...
def run_supernova ( ctx , executable , debug , quiet , environment , command , conf , echo , dashboard ) : """You can use supernova with many OpenStack clients and avoid the pain of managing multiple sets of environment variables . Getting started is easy and there ' s some documentation that can help : http ...
# Retrieve our credentials from the configuration file try : nova_creds = config . run_config ( config_file_override = conf ) except Exception as e : msg = ( "\n There's an error in your configuration file:\n\n" " {0}\n" ) . format ( e ) click . echo ( msg ) ctx . exit ( 1 ) # Warn the user if there...
def rel_humid_from_db_dpt ( db_temp , dew_pt ) : """Relative Humidity ( % ) at db _ temp ( C ) , and dew _ pt ( C ) ."""
pws_ta = saturated_vapor_pressure ( db_temp + 273.15 ) pws_td = saturated_vapor_pressure ( dew_pt + 273.15 ) rh = 100 * ( pws_td / pws_ta ) return rh
def filesFromHere_explore ( self , astr_startPath = '/' ) : """Return a list of path / files from " here " in the stree , using the child explore access . : param astr _ startPath : path from which to start : return :"""
self . l_fwd = [ ] self . treeExplore ( startPath = astr_startPath , f = self . fwd ) self . l_allFiles = [ f . split ( '/' ) for f in self . l_fwd ] for i in range ( 0 , len ( self . l_allFiles ) ) : self . l_allFiles [ i ] [ 0 ] = '/' return self . l_fwd
def _map_channel_row_to_dict ( self , row ) : """Convert dictionary keys from raw csv format ( see CHANNEL _ INFO _ HEADER ) , to ricecooker - like keys , e . g . , ' ' Source ID ' - - > ' source _ id '"""
channel_cleaned = _clean_dict ( row ) channel_dict = dict ( title = channel_cleaned [ CHANNEL_TITLE_KEY ] , description = channel_cleaned [ CHANNEL_DESCRIPTION_KEY ] , source_domain = channel_cleaned [ CHANNEL_DOMAIN_KEY ] , source_id = channel_cleaned [ CHANNEL_SOURCEID_KEY ] , language = channel_cleaned [ CHANNEL_LAN...
def preprocess_section ( self , section ) : """Preprocessors a given section into it ' s components ."""
lines = [ ] in_codeblock = False keyword = None components = { } for line in section . content . split ( '\n' ) : line = line . strip ( ) if line . startswith ( "```" ) : in_codeblock = not in_codeblock if not in_codeblock : match = re . match ( r':(?:param|parameter)\s+(\w+)\s*:(.*)?$' , li...
def _process_model_dict ( self , d ) : """Remove redundant items from a model ' s configuration dict . Parameters d : dict Modified in place . Returns dict Modified ` d ` ."""
del d [ 'model_type' ] del d [ 'fit_filters' ] del d [ 'predict_filters' ] if d [ 'model_expression' ] == self . default_model_expr : del d [ 'model_expression' ] if YTRANSFORM_MAPPING [ d [ 'ytransform' ] ] == self . default_ytransform : del d [ 'ytransform' ] d [ "name" ] = yamlio . to_scalar_safe ( d [ "name...
def get_version_string ( check_name ) : """Get the version string for the given check ."""
version = VERSION . search ( read_version_file ( check_name ) ) if version : return version . group ( 1 )
def _check_flood_protection ( self , component , action , clientuuid ) : """Checks if any clients have been flooding the node"""
if clientuuid not in self . _flood_counter : self . _flood_counter [ clientuuid ] = 0 self . _flood_counter [ clientuuid ] += 1 if self . _flood_counter [ clientuuid ] > 100 : packet = { 'component' : 'hfos.ui.clientmanager' , 'action' : 'Flooding' , 'data' : True } self . fireEvent ( send ( clientuuid , pa...
def change_vartype ( self , vartype , inplace = True ) : """Create a binary quadratic model with the specified vartype . Args : vartype ( : class : ` . Vartype ` / str / set , optional ) : Variable type for the changed model . Accepted input values : * : class : ` . Vartype . SPIN ` , ` ` ' SPIN ' ` ` , ` `...
if not inplace : # create a new model of the appropriate type , then add self ' s biases to it new_model = BinaryQuadraticModel ( { } , { } , 0.0 , vartype ) new_model . add_variables_from ( self . linear , vartype = self . vartype ) new_model . add_interactions_from ( self . quadratic , vartype = self . va...
def get_last_user ( self , refresh = False ) : """Get the last used PIN user id"""
if refresh : self . refresh_complex_value ( 'sl_UserCode' ) val = self . get_complex_value ( "sl_UserCode" ) # Syntax string : UserID = " < pin _ slot > " UserName = " < pin _ code _ name > " # See http : / / wiki . micasaverde . com / index . php / Luup _ UPnP _ Variables _ and _ Actions # DoorLock1 try : # Get th...
def list_race_details ( self , meeting_ids = None , race_ids = None , session = None , lightweight = None ) : """Search for races to get their details . : param dict meeting _ ids : Optionally restricts the results to the specified meeting IDs . The unique Id for the meeting equivalent to the eventId for that s...
params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'listRaceDetails' ) ( response , elapsed_time ) = self . request ( method , params , session ) return self . process_response ( response , resources . RaceDetails , elapsed_time , lightweight )
def get_frequency_dict ( lang , wordlist = 'best' , match_cutoff = 30 ) : """Get a word frequency list as a dictionary , mapping tokens to frequencies as floating - point probabilities ."""
freqs = { } pack = get_frequency_list ( lang , wordlist , match_cutoff ) for index , bucket in enumerate ( pack ) : freq = cB_to_freq ( - index ) for word in bucket : freqs [ word ] = freq return freqs
def parse_value ( val , parsebool = False ) : """Parse input string and return int , float or str depending on format . @ param val : Input string . @ param parsebool : If True parse yes / no , on / off as boolean . @ return : Value of type int , float or str ."""
try : return int ( val ) except ValueError : pass try : return float ( val ) except : pass if parsebool : if re . match ( 'yes|on' , str ( val ) , re . IGNORECASE ) : return True elif re . match ( 'no|off' , str ( val ) , re . IGNORECASE ) : return False return val
def circularize ( self ) : '''Circularize linear DNA . : returns : A circularized version of the current sequence . : rtype : coral . DNA'''
if self . top [ - 1 ] . seq == '-' and self . bottom [ 0 ] . seq == '-' : raise ValueError ( 'Cannot circularize - termini disconnected.' ) if self . bottom [ - 1 ] . seq == '-' and self . top [ 0 ] . seq == '-' : raise ValueError ( 'Cannot circularize - termini disconnected.' ) copy = self . copy ( ) copy . ci...
def map_new ( w : int , h : int ) -> tcod . map . Map : """Return a : any : ` tcod . map . Map ` with a width and height . . . deprecated : : 4.5 Use the : any : ` tcod . map ` module for working with field - of - view , or : any : ` tcod . path ` for working with path - finding ."""
return tcod . map . Map ( w , h )
def step_indices ( group_idx ) : """Get the edges of areas within group _ idx , which are filled with the same value"""
ilen = step_count ( group_idx ) + 1 indices = np . empty ( ilen , int ) indices [ 0 ] = 0 indices [ - 1 ] = group_idx . size inline ( c_step_indices , [ 'group_idx' , 'indices' ] , define_macros = c_macros , extra_compile_args = c_args ) return indices
def coerce ( self , value , resource ) : """Convert a list of objects in a list of dicts . Arguments value : iterable The list ( or other iterable ) to get values to get some resources from . resource : dataql . resources . List The ` ` List ` ` object used to obtain this value from the original one . R...
if not isinstance ( value , Iterable ) : raise NotIterable ( resource , self . registry [ value ] ) # Case # 1 : we only have one sub - resource , so we return a list with this item for # each iteration if len ( resource . resources ) == 1 : res = resource . resources [ 0 ] return [ self . registry . solve_...
def modify_access ( src , dst = 'any' , port = None , proto = None , action = 'allow' , index = None ) : """Grant access to an address or subnet : param src : address ( e . g . 192.168.1.234 ) or subnet ( e . g . 192.168.1.0/24 ) . : param dst : destiny of the connection , if the machine has multiple IPs and ...
if not is_enabled ( ) : hookenv . log ( 'ufw is disabled, skipping modify_access()' , level = 'WARN' ) return if action == 'delete' : cmd = [ 'ufw' , 'delete' , 'allow' ] elif index is not None : cmd = [ 'ufw' , 'insert' , str ( index ) , action ] else : cmd = [ 'ufw' , action ] if src is not None :...
def serialize_object ( self , obj ) : """Write one item to the object stream"""
self . start_object ( obj ) for field in obj . _meta . local_fields : if field . serialize and getattr ( field , 'include_in_xml' , True ) : if field . rel is None : if self . selected_fields is None or field . attname in self . selected_fields : self . handle_field ( obj , field...
def converged_electronic ( self ) : """Checks that electronic step convergence has been reached in the final ionic step"""
final_esteps = self . ionic_steps [ - 1 ] [ "electronic_steps" ] if 'LEPSILON' in self . incar and self . incar [ 'LEPSILON' ] : i = 1 to_check = set ( [ 'e_wo_entrp' , 'e_fr_energy' , 'e_0_energy' ] ) while set ( final_esteps [ i ] . keys ( ) ) == to_check : i += 1 return i + 1 != self . parame...
def to_dict ( self , include_args = True , include_kwargs = True ) : """Converts this object to a dictionary . : param include _ args : boolean indicating whether to include the exception args in the output . : param include _ kwargs : boolean indicating whether to include the exception kwargs in the output...
data = { 'exception_str' : self . exception_str , 'traceback_str' : self . traceback_str , 'exc_type_names' : self . exception_type_names , 'exc_args' : self . exception_args if include_args else tuple ( ) , 'exc_kwargs' : self . exception_kwargs if include_kwargs else { } , 'generated_on' : self . generated_on , } if ...
def snmp_server_user_priv_password ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) snmp_server = ET . SubElement ( config , "snmp-server" , xmlns = "urn:brocade.com:mgmt:brocade-snmp" ) user = ET . SubElement ( snmp_server , "user" ) username_key = ET . SubElement ( user , "username" ) username_key . text = kwargs . pop ( 'username' ) priv_password = ET . SubElement...
def delete ( self , resource , ** params ) : """Generic TeleSign REST API DELETE handler . : param resource : The partial resource URI to perform the request against , as a string . : param params : Body params to perform the DELETE request with , as a dictionary . : return : The RestClient Response object ."...
return self . _execute ( self . session . delete , 'DELETE' , resource , ** params )
def _import_sub_module ( module , name ) : """import _ sub _ module will mimic the function of importlib . import _ module"""
module = __import__ ( module . __name__ + "." + name ) for level in name . split ( "." ) : module = getattr ( module , level ) return module
def _smartos_zone_pkgsrc_data ( ) : '''SmartOS zone pkgsrc information'''
# Provides : # pkgsrcversion # pkgsrcpath grains = { 'pkgsrcversion' : 'Unknown' , 'pkgsrcpath' : 'Unknown' , } pkgsrcversion = re . compile ( '^release:\\s(.+)' ) if os . path . isfile ( '/etc/pkgsrc_version' ) : with salt . utils . files . fopen ( '/etc/pkgsrc_version' , 'r' ) as fp_ : for line in fp_ : ...
def create_subscription ( self , subscription ) : """Create a new subscription : param subscription : the new subscription the client wants to create"""
if subscription . subscription_id is not None : self . _validate_uuid ( subscription . subscription_id ) if subscription . endpoint is not None : if subscription . endpoint . subscriber_id is not None : self . _validate_subscriber_id ( subscription . endpoint . subscriber_id ) if subscription . endp...