signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def to_internal_filter ( self , attribute_profile , external_attribute_names ) :
"""Converts attribute names from external " type " to internal
: type attribute _ profile : str
: type external _ attribute _ names : list [ str ]
: type case _ insensitive : bool
: rtype : list [ str ]
: param attribute _ pr... | try :
profile_mapping = self . to_internal_attributes [ attribute_profile ]
except KeyError :
logger . warn ( "no attribute mapping found for the given attribute profile '%s'" , attribute_profile )
# no attributes since the given profile is not configured
return [ ]
internal_attribute_names = set ( )
# ... |
def imap ( requests , stream = False , size = 2 , exception_handler = None ) :
"""Concurrently converts a generator object of Requests to
a generator of Responses .
: param requests : a generator of Request objects .
: param stream : If True , the content will not be downloaded immediately .
: param size : ... | pool = Pool ( size )
def send ( r ) :
return r . send ( stream = stream )
for request in pool . imap_unordered ( send , requests ) :
if request . response is not None :
yield request . response
elif exception_handler :
ex_result = exception_handler ( request , request . exception )
i... |
def _computeAsymptoticCovarianceMatrix ( self , W , N_k , method = None ) :
"""Compute estimate of the asymptotic covariance matrix .
Parameters
W : np . ndarray , shape = ( N , K ) , dtype = ' float '
The normalized weight matrix for snapshots and states .
W [ n , k ] is the weight of snapshot n in state k... | # Set ' svd - ew ' as default if uncertainty method specified as None .
if method == None :
method = 'svd-ew'
# Get dimensions of weight matrix .
[ N , K ] = W . shape
# Check dimensions
if ( K != N_k . size ) :
raise ParameterError ( 'W must be NxK, where N_k is a K-dimensional array.' )
if ( np . sum ( N_k ) ... |
def singleton ( * args , ** kwargs ) :
'''a lazy init singleton pattern .
usage :
` ` ` py
@ singleton ( )
class X : . . .
` args ` and ` kwargs ` will pass to ctor of ` X ` as args .''' | def decorator ( cls : type ) -> Callable [ [ ] , object ] :
if issubclass ( type ( cls ) , _SingletonMetaClassBase ) :
raise TypeError ( 'cannot inherit from another singleton class.' )
box = _Box ( )
factory = None
lock = Lock ( )
def metaclass_call ( _ ) :
if box . value is None :
... |
def _send_message ( self , method , endpoint , params = None , data = None ) :
"""Send API request .
Args :
method ( str ) : HTTP method ( get , post , delete , etc . )
endpoint ( str ) : Endpoint ( to be added to base URL )
params ( Optional [ dict ] ) : HTTP request parameters
data ( Optional [ str ] ) ... | url = self . url + endpoint
r = self . session . request ( method , url , params = params , data = data , auth = self . auth , timeout = 30 )
return r . json ( ) |
def to_file_async ( self , destination , format = 'csv' , csv_delimiter = ',' , csv_header = True ) :
"""Start saving the results to a local file in CSV format and return a Job for completion .
Args :
destination : path on the local filesystem for the saved results .
format : the format to use for the exporte... | self . to_file ( destination , format = format , csv_delimiter = csv_delimiter , csv_header = csv_header ) |
def list_subdirs ( self , container , marker = None , limit = None , prefix = None , delimiter = None , full_listing = False ) :
"""Returns a list of StorageObjects representing the pseudo - subdirectories
in the specified container . You can use the marker and limit params to
handle pagination , and the prefix... | mthd = container . list_all if full_listing else container . list
objs = mthd ( marker = marker , limit = limit , prefix = prefix , delimiter = "/" , return_raw = True )
sdirs = [ obj for obj in objs if "subdir" in obj ]
mgr = container . object_manager
return [ StorageObject ( mgr , sdir ) for sdir in sdirs ] |
def unwrap_or_else ( self , callback : Callable [ [ ] , U ] ) -> Union [ T , U ] :
"""Returns the contained value or computes it from ` ` callback ` ` .
Args :
callback : The the default callback .
Returns :
The contained value if the : py : class : ` Option ` is ` ` Some ` ` ,
otherwise ` ` callback ( ) ... | return self . _val if self . _is_some else callback ( ) |
def trim_shared_prefix ( ref , alt ) :
"""Sometimes mutations are given with a shared prefix between the reference
and alternate strings . Examples : C > CT ( nucleotides ) or GYFP > G ( amino acids ) .
This function trims the common prefix and returns the disjoint ref
and alt strings , along with the shared ... | n_ref = len ( ref )
n_alt = len ( alt )
n_min = min ( n_ref , n_alt )
i = 0
while i < n_min and ref [ i ] == alt [ i ] :
i += 1
# guaranteed that ref and alt agree on all the characters
# up to i ' th position , so it doesn ' t matter which one we pull
# the prefix out of
prefix = ref [ : i ]
ref_suffix = ref [ i :... |
def get_all_file_report_pages ( self , query ) :
"""Get File Report ( All Pages ) .
: param query : a VirusTotal Intelligence search string in accordance with the file search documentation .
: return : All JSON responses appended together .""" | responses = [ ]
r = self . get_hashes_from_search ( query )
responses . append ( r )
if ( 'results' in r . keys ( ) ) and ( 'next_page' in r [ 'results' ] . keys ( ) ) :
next_page = r [ 'results' ] [ 'next_page' ]
else :
next_page = None
while next_page :
r = self . get_hashes_from_search ( query , next_pag... |
def argmin ( iterable , key = None , both = False ) :
"""See ` argmax ` .""" | if key is not None :
it = imap ( key , iterable )
else :
it = iter ( iterable )
score , argmin = reduce ( min , izip ( it , count ( ) ) )
if both :
return argmin , score
return argmin |
def get_elastic_items_search ( elastic , search_after = None , size = None ) :
"""Get the items from the index using search after scrolling""" | if not size :
size = DEFAULT_LIMIT
url = elastic . index_url + "/_search"
search_after_query = ''
if search_after :
logging . debug ( "Search after: %s" , search_after )
# timestamp uuid
search_after_query = ', "search_after": [%i, "%s"] ' % ( search_after [ 0 ] , search_after [ 1 ] )
query = """
{
... |
def importRemoteSNPs ( name ) :
"""Import a SNP set available from http : / / pygeno . iric . ca ( might work ) .""" | try :
dw = listRemoteDatawraps ( ) [ "Flat" ] [ "SNPs" ]
except AttributeError :
raise AttributeError ( "There's no remote genome datawrap by the name of: '%s'" % name )
finalFile = _DW ( name , dw [ "url" ] )
PS . importSNPs ( finalFile ) |
def open_image ( fname_or_instance : Union [ str , IO [ bytes ] ] ) :
"""Opens a Image and returns it .
: param fname _ or _ instance : Can either be the location of the image as a
string or the Image . Image instance itself .""" | if isinstance ( fname_or_instance , Image . Image ) :
return fname_or_instance
return Image . open ( fname_or_instance ) |
def parseTextModeTimeStr ( timeStr ) :
"""Parses the specified SMS text mode time string
The time stamp format is " yy / MM / dd , hh : mm : ss ± zz "
( yy = year , MM = month , dd = day , hh = hour , mm = minute , ss = second , zz = time zone
[ Note : the unit of time zone is a quarter of an hour ] )
: par... | msgTime = timeStr [ : - 3 ]
tzOffsetHours = int ( int ( timeStr [ - 3 : ] ) * 0.25 )
return datetime . strptime ( msgTime , '%y/%m/%d,%H:%M:%S' ) . replace ( tzinfo = SimpleOffsetTzInfo ( tzOffsetHours ) ) |
def read ( self ) :
"""Reads the contents of the GPFile and returns the contents as a string ( assumes UTF - 8)""" | with closing ( self . open ( ) ) as f :
data = f . read ( )
return data . decode ( "utf-8" ) or None |
def is_conflicting ( self ) :
"""If installed version conflicts with required version""" | # unknown installed version is also considered conflicting
if self . installed_version == self . UNKNOWN_VERSION :
return True
ver_spec = ( self . version_spec if self . version_spec else '' )
req_version_str = '{0}{1}' . format ( self . project_name , ver_spec )
req_obj = pkg_resources . Requirement . parse ( req_... |
def add_entry ( self , net_type , cn , addresses ) :
"""Add a request to the batch
: param net _ type : str netwrok space name request is for
: param cn : str Canonical Name for certificate
: param addresses : [ ] List of addresses to be used as SANs""" | self . entries . append ( { 'cn' : cn , 'addresses' : addresses } ) |
def client_factory ( self ) :
"""Custom client factory to set proxy options .""" | if self . _service . production :
url = self . production_url
else :
url = self . testing_url
proxy_options = dict ( )
https_proxy_setting = os . environ . get ( 'PAYEX_HTTPS_PROXY' ) or os . environ . get ( 'https_proxy' )
http_proxy_setting = os . environ . get ( 'PAYEX_HTTP_PROXY' ) or os . environ . get ( '... |
def all ( self , count = 500 , offset = 0 , type = None , inactive = None , emailFilter = None , tag = None , messageID = None , fromdate = None , todate = None , ) :
"""Returns many bounces .
: param int count : Number of bounces to return per request .
: param int offset : Number of bounces to skip .
: para... | responses = self . call_many ( "GET" , "/bounces/" , count = count , offset = offset , type = type , inactive = inactive , emailFilter = emailFilter , tag = tag , messageID = messageID , fromdate = fromdate , todate = todate , )
return self . expand_responses ( responses , "Bounces" ) |
def delete_fastqs ( job , fastqs ) :
"""This module will delete the fastqs from teh job Store once their purpose has been achieved ( i . e .
after all mapping steps )
ARGUMENTS
1 . fastqs : Dict of list of input fastqs
fastqs
+ - ' tumor _ rna ' : [ < JSid for 1 . fastq > , < JSid for 2 . fastq > ]
+ - ... | for fq_type in [ 'tumor_rna' , 'tumor_dna' , 'normal_dna' ] :
for i in xrange ( 0 , 2 ) :
job . fileStore . deleteGlobalFile ( fastqs [ fq_type ] [ i ] )
return None |
def histogram ( n_traces = 1 , n = 500 , dispersion = 2 , mode = None ) :
"""Returns a DataFrame with the required format for
a histogram plot
Parameters :
n _ traces : int
Number of traces
n : int
Number of points for each trace
mode : string
Format for each item
' abc ' for alphabet columns
' ... | df = pd . DataFrame ( np . transpose ( [ np . random . randn ( n ) + np . random . randint ( - 1 * dispersion , dispersion ) for _ in range ( n_traces ) ] ) , columns = getName ( n_traces , mode = mode ) )
return df |
def migrate ( vm_ , target , live = 1 , port = 0 , node = - 1 , ssl = None , change_home_server = 0 ) :
'''Migrates the virtual machine to another hypervisor
CLI Example :
. . code - block : : bash
salt ' * ' virt . migrate < vm name > < target hypervisor > [ live ] [ port ] [ node ] [ ssl ] [ change _ home _... | with _get_xapi_session ( ) as xapi :
vm_uuid = _get_label_uuid ( xapi , 'VM' , vm_ )
if vm_uuid is False :
return False
other_config = { 'port' : port , 'node' : node , 'ssl' : ssl , 'change_home_server' : change_home_server }
try :
xapi . VM . migrate ( vm_uuid , target , bool ( live ) ... |
def _nodes ( output , parent = None ) :
"""Yield nodes from entities .""" | # NOTE refactor so all outputs behave the same
entity = getattr ( output , 'entity' , output )
if isinstance ( entity , Collection ) :
for member in entity . members :
if parent is not None :
member = attr . evolve ( member , parent = parent )
yield from _nodes ( member )
yield outpu... |
def set_params ( self , ** params ) :
"""Set parameters on this object
Safe setter method - attributes should not be modified directly as some
changes are not valid .
Valid parameters :
- n _ landmark
- n _ svd
Parameters
params : key - value pairs of parameter name and new values
Returns
self""" | # update parameters
reset_landmarks = False
if 'n_landmark' in params and params [ 'n_landmark' ] != self . n_landmark :
self . n_landmark = params [ 'n_landmark' ]
reset_landmarks = True
if 'n_svd' in params and params [ 'n_svd' ] != self . n_svd :
self . n_svd = params [ 'n_svd' ]
reset_landmarks = Tr... |
def _recursive_url_find ( self , item , image_list ) :
"""Recursively traverses a dictionary - like data structure for Khan Academy
assessment items in order to search for image links in ` url ` data attributes ,
and if it finds any it adds them to ` image _ list ` and rewrites ` url ` attribute .
Use cases :... | recursive_fn = partial ( self . _recursive_url_find , image_list = image_list )
if isinstance ( item , list ) :
list ( map ( recursive_fn , item ) )
elif isinstance ( item , dict ) :
if 'url' in item :
if item [ 'url' ] :
item [ 'url' ] , image_file = self . set_image ( item [ 'url' ] )
... |
def UGT ( a : BitVec , b : BitVec ) -> Bool :
"""Create an unsigned greater than expression .
: param a :
: param b :
: return :""" | return _comparison_helper ( a , b , z3 . UGT , default_value = False , inputs_equal = False ) |
def argument_run ( self , sp_r ) :
""". . _ argument _ run :
Converts Arguments according to ` ` to _ int ` `""" | arg_run = [ ]
for line in sp_r :
logging . debug ( "argument run: handling: " + str ( line ) )
if ( line [ 1 ] == "data" ) :
arg_run . append ( ( line [ 0 ] , line [ 1 ] , line [ 2 ] , line [ 2 ] . get_words ( line [ 3 ] ) ) )
continue
if ( line [ 1 ] == "command" ) :
self . checkarg... |
async def fetchall ( self ) :
"""Fetch all , as per MySQLdb . Pretty useless for large queries , as
it is buffered .""" | rows = [ ]
while True :
row = await self . fetchone ( )
if row is None :
break
rows . append ( row )
return rows |
def check_dependencies ( req , indent = 1 , history = None ) :
"""Given a setuptools package requirement ( e . g . ' gryphon = = 2.42 ' or just
' gryphon ' ) , print a tree of dependencies as they resolve in this
environment .""" | # keep a history to avoid infinite loops
if history is None :
history = set ( )
if req in history :
return
history . add ( req )
d = pkg_resources . get_distribution ( req )
extras = parse_extras ( req )
if indent == 1 :
print_package ( req , 0 )
for r in d . requires ( extras = extras ) :
print_package... |
def on_number ( self , ctx , value ) :
'''Since this is defined both integer and double callbacks are useless''' | value = int ( value ) if value . isdigit ( ) else float ( value )
top = self . _stack [ - 1 ]
if top is JSONCompositeType . OBJECT :
self . fire ( JSONStreamer . VALUE_EVENT , value )
elif top is JSONCompositeType . ARRAY :
self . fire ( JSONStreamer . ELEMENT_EVENT , value )
else :
raise RuntimeError ( 'In... |
def to_split ( val , split_on_comma = True ) :
"""Try to split a string with comma separator .
If val is already a list return it
If we don ' t have to split just return [ val ]
If split gives only [ ' ' ] empty it
: param val : value to split
: type val :
: param split _ on _ comma :
: type split _ o... | if isinstance ( val , list ) :
return val
if not split_on_comma :
return [ val ]
val = val . split ( ',' )
if val == [ '' ] :
val = [ ]
return val |
def get_config ( self , key , default = None ) :
'''Lookup a config field and return its value , first checking the
route . config , then route . app . config .''' | for conf in ( self . config , self . app . conifg ) :
if key in conf :
return conf [ key ]
return default |
def register_method ( self , func ) :
"""Register a function to be available as RPC method .
The given function will be inspected to find external _ name , protocol and entry _ point values set by the decorator
@ rpc _ method .
: param func : A function previously decorated using @ rpc _ method
: return : T... | if not getattr ( func , 'modernrpc_enabled' , False ) :
raise ImproperlyConfigured ( 'Error: trying to register {} as RPC method, but it has not been decorated.' . format ( func . __name__ ) )
# Define the external name of the function
name = getattr ( func , 'modernrpc_name' , func . __name__ )
logger . debug ( 'R... |
def stop ( self , timeout = None ) :
"""Stop the producer ( async mode ) . Blocks until async thread completes .""" | if timeout is not None :
log . warning ( 'timeout argument to stop() is deprecated - ' 'it will be removed in future release' )
if not self . async_send :
log . warning ( 'producer.stop() called, but producer is not async' )
return
if self . stopped :
log . warning ( 'producer.stop() called, but produce... |
async def reboot ( self ) :
"""Reboot the device .""" | endpoint = '/setup/reboot'
url = API . format ( ip = self . _ipaddress , endpoint = endpoint )
data = { 'params' : 'now' }
returnvalue = False
try :
async with async_timeout . timeout ( 5 , loop = self . _loop ) :
result = await self . _session . post ( url , json = data , headers = HEADERS )
if res... |
def auto_start_vm ( self ) :
"""Auto start the GNS3 VM if require""" | if self . enable :
try :
yield from self . start ( )
except GNS3VMError as e : # User will receive the error later when they will try to use the node
try :
yield from self . _controller . add_compute ( compute_id = "vm" , name = "GNS3 VM ({})" . format ( self . current_engine ( ) . v... |
def get_file ( self , file_id ) :
"""Use this method to get basic info about a file and prepare it for downloading . For the moment , bots can download files of up to 20MB in size . On success , a File object is returned . The file can then be downloaded via the link https : / / api . telegram . org / file / bot < ... | assert_type_or_raise ( file_id , unicode_type , parameter_name = "file_id" )
result = self . do ( "getFile" , file_id = file_id )
if self . return_python_objects :
logger . debug ( "Trying to parse {data}" . format ( data = repr ( result ) ) )
from pytgbot . api_types . receivable . media import File
try :
... |
def list_and_add ( a , b ) :
"""Concatenate anything into a list .
Args :
a : the first thing
b : the second thing
Returns :
list . All the things in a list .""" | if not isinstance ( b , list ) :
b = [ b ]
if not isinstance ( a , list ) :
a = [ a ]
return a + b |
def keep_frameshifts ( mut_df , indel_len_col = True ) :
"""Filters out all mutations that are not frameshift indels .
Requires that one of the alleles have ' - ' indicating either an insertion
or deletion depending if found in reference allele or somatic allele
columns , respectively .
Parameters
mut _ d... | # keep only frameshifts
mut_df = mut_df [ is_frameshift_annotation ( mut_df ) ]
if indel_len_col : # calculate length
mut_df . loc [ : , 'indel len' ] = compute_indel_length ( mut_df )
return mut_df |
def shift_or_mirror_into_invertible_domain ( self , solution_genotype , copy = False ) :
"""Details : input ` ` solution _ genotype ` ` is changed . The domain is
[ lb - al , ub + au ] and in [ lb - 2 * al - ( ub - lb ) / 2 , lb - al ]
mirroring is applied .""" | assert solution_genotype is not None
if copy :
y = [ val for val in solution_genotype ]
else :
y = solution_genotype
if isinstance ( y , np . ndarray ) and not isinstance ( y [ 0 ] , float ) :
y = array ( y , dtype = float )
for i in rglen ( y ) :
lb = self . _lb [ self . _index ( i ) ]
ub = self . ... |
def vi_pos_matching ( line , index = 0 ) :
'''find matching < ( [ { } ] ) >''' | anchor = None
target = None
delta = 1
count = 0
try :
while 1 :
if anchor is None : # first find anchor
try :
target , delta = _vi_dct_matching [ line [ index ] ]
anchor = line [ index ]
count = 1
except KeyError :
index... |
def encode ( self , text , encoding , defaultchar = '?' ) :
"""Encode text under the given encoding
: param text : Text to encode
: param encoding : Encoding name to use ( must be defined in capabilities )
: param defaultchar : Fallback for non - encodable characters""" | codepage_char_map = self . _get_codepage_char_map ( encoding )
output_bytes = bytes ( [ self . _encode_char ( char , codepage_char_map , defaultchar ) for char in text ] )
return output_bytes |
def _do_bgread ( stream , blockSizeLimit , pollTime , closeStream , results ) :
'''_ do _ bgread - Worker functon for the background read thread .
@ param stream < object > - Stream to read until closed
@ param results < BackgroundReadData >''' | # Put the whole function in a try instead of just the read portion for performance reasons .
try :
while True :
nextData = nonblock_read ( stream , limit = blockSizeLimit )
if nextData is None :
break
elif nextData :
results . addBlock ( nextData )
time . slee... |
def citedReferencesRetrieve ( self , queryId , count = 100 , offset = 1 , retrieveParameters = None ) :
"""The citedReferencesRetrieve operation submits a query returned by a
previous citedReferences operation .
This operation is useful for overcoming the retrieval limit of 100
records per query . For example... | return self . _search . service . citedReferencesRetrieve ( queryId = queryId , retrieveParameters = ( retrieveParameters or self . make_retrieveParameters ( offset , count ) ) ) |
def parse_reports ( self ) :
"""Find Picard RrbsSummaryMetrics reports and parse their data""" | # Set up vars
self . picard_rrbs_metrics = dict ( )
# Go through logs and find Metrics
for f in self . find_log_files ( 'picard/rrbs_metrics' , filehandles = True ) :
parsed_data = dict ( )
s_name = None
keys = None
for l in f [ 'f' ] : # New log starting
if 'CollectRrbsMetrics' in l and 'INPUT'... |
def get_volume ( self , channel = None ) :
"""Gets the current sound volume by parsing the output of
` ` amixer get < channel > ` ` .
If the channel is not specified , it tries to determine the default one
by running ` ` amixer scontrols ` ` . If that fails as well , it uses the
` ` Playback ` ` channel , a... | if channel is None :
channel = self . _get_channel ( )
out = check_output ( [ 'amixer' , 'get' , channel ] ) . decode ( )
m = re . search ( r'\[(?P<volume>\d+)%\]' , out )
if m :
return int ( m . group ( 'volume' ) )
else :
raise Exception ( 'Failed to parse output of `amixer get {}`' . format ( channel ) ) |
def prepare_sort_key ( self ) :
'''Triggered by view _ function . _ sort _ converters when our sort key should be created .
This can ' t be called in the constructor because Django models might not be ready yet .''' | if isinstance ( self . convert_type , str ) :
try :
app_name , model_name = self . convert_type . split ( '.' )
except ValueError :
raise ImproperlyConfigured ( '"{}" is not a valid converter type. String-based converter types must be specified in "app.Model" format.' . format ( self . convert_t... |
def get_vmpolicy_macaddr_input_vcenter ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vmpolicy_macaddr = ET . Element ( "get_vmpolicy_macaddr" )
config = get_vmpolicy_macaddr
input = ET . SubElement ( get_vmpolicy_macaddr , "input" )
vcenter = ET . SubElement ( input , "vcenter" )
vcenter . text = kwargs . pop ( 'vcenter' )
callback = kwargs . pop ( 'callback' , se... |
def invite_other_parties ( self , possible_owners ) :
"""Invites the next lane ' s ( possible ) owner ( s ) to participate""" | signals . lane_user_change . send ( sender = self . user , current = self , old_lane = self . old_lane , possible_owners = possible_owners ) |
def new_cast_status ( self , status ) :
"""Called when a new status received from the Chromecast .""" | self . status = status
if status :
self . status_event . set ( ) |
def is_modified_field ( self , name ) :
"""Returns whether a field is modified or not""" | name = self . get_real_name ( name )
if name in self . __modified_data__ or name in self . __deleted_fields__ :
return True
try :
return self . get_field_value ( name ) . is_modified ( )
except Exception :
return False |
def notify_server_ready ( self , language , config ) :
"""Notify language server availability to code editors .""" | for index in range ( self . get_stack_count ( ) ) :
editor = self . tabs . widget ( index )
if editor . language . lower ( ) == language :
editor . start_lsp_services ( config ) |
def on_each ( self , * targets : raw_types . Qid ) -> op_tree . OP_TREE :
"""Returns a list of operations apply this gate to each of the targets .
Args :
* targets : The qubits to apply this gate to .
Returns :
Operations applying this gate to the target qubits .
Raises :
ValueError if targets are not i... | return [ self . on ( target ) for target in targets ] |
def setup_signing ( self , secret_key , sign_outgoing = True , allow_unsigned_callback = None , initial_timestamp = None , link_id = None ) :
'''setup for MAVLink2 signing''' | self . mav . signing . secret_key = secret_key
self . mav . signing . sign_outgoing = sign_outgoing
self . mav . signing . allow_unsigned_callback = allow_unsigned_callback
if link_id is None : # auto - increment the link _ id for each link
global global_link_id
link_id = global_link_id
global_link_id = min... |
def parse_node ( node ) :
"""Input : a serialized node""" | if node is None or node == b'' :
raise InvalidNode ( "Blank node is not a valid node type in Binary Trie" )
elif node [ 0 ] == BRANCH_TYPE :
if len ( node ) != 65 :
raise InvalidNode ( "Invalid branch node, both child node should be 32 bytes long each" )
# Output : node type , left child , right chi... |
def calculate_offset ( cls , labels ) :
'''Return the maximum length of the provided strings that have a nice
variant in DapFormatter . _ nice _ strings''' | used_strings = set ( cls . _nice_strings . keys ( ) ) & set ( labels )
return max ( [ len ( cls . _nice_strings [ s ] ) for s in used_strings ] ) |
def remove_import_statements ( code ) :
"""Removes lines with import statements from the code .
Args :
code : The code to be stripped .
Returns :
The code without import statements .""" | new_code = [ ]
for line in code . splitlines ( ) :
if not line . lstrip ( ) . startswith ( 'import ' ) and not line . lstrip ( ) . startswith ( 'from ' ) :
new_code . append ( line )
while new_code and new_code [ 0 ] == '' :
new_code . pop ( 0 )
while new_code and new_code [ - 1 ] == '' :
new_code .... |
def run ( self , args ) :
"""Main entry point of script""" | logging . basicConfig ( stream = sys . stdout , level = logging . INFO )
configuration = self . configuration
configuration . locale_dir . parent . makedirs_p ( )
# pylint : disable = attribute - defined - outside - init
self . source_msgs_dir = configuration . source_messages_dir
# The extraction process clobbers djan... |
def batch_get_item ( self , batch_list ) :
"""Return a set of attributes for a multiple items in
multiple tables using their primary keys .
: type batch _ list : : class : ` boto . dynamodb . batch . BatchList `
: param batch _ list : A BatchList object which consists of a
list of : class : ` boto . dynamod... | request_items = self . dynamize_request_items ( batch_list )
return self . layer1 . batch_get_item ( request_items , object_hook = item_object_hook ) |
def generate_calculus_integrate_sample ( vlist , ops , min_depth , max_depth , functions ) :
"""Randomly generate a symbolic integral dataset sample .
Given an input expression , produce the indefinite integral .
Args :
vlist : Variable list . List of chars that can be used in the expression .
ops : List of... | var_index = random . randrange ( len ( vlist ) )
var = vlist [ var_index ]
consts = vlist [ : var_index ] + vlist [ var_index + 1 : ]
depth = random . randrange ( min_depth , max_depth + 1 )
expr = random_expr_with_required_var ( depth , var , consts , ops )
expr_str = str ( expr )
sample = var + ":" + expr_str
target ... |
def list_namespaced_job ( self , namespace , ** kwargs ) : # noqa : E501
"""list _ namespaced _ job # noqa : E501
list or watch objects of kind Job # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . list_namespaced_job_with_http_info ( namespace , ** kwargs )
# noqa : E501
else :
( data ) = self . list_namespaced_job_with_http_info ( namespace , ** kwargs )
# noqa : E501
return data |
def expand_short_options ( self , argv ) :
"""Convert grouped short options like ` - abc ` to ` - a , - b , - c ` .
This is necessary because we set ` ` allow _ abbrev = False ` ` on the
` ` ArgumentParser ` ` in : prop : ` self . arg _ parser ` . The argparse docs
say ` ` allow _ abbrev ` ` applies only to l... | new_argv = [ ]
for arg in argv :
result = self . parse_multi_short_option ( arg )
new_argv . extend ( result )
return new_argv |
def start ( self ) :
"""Start listening to changes""" | self . running = True
self . thread = threading . Thread ( target = self . _main_loop )
self . thread . start ( ) |
def _process_inputs ( self , input_reader , shard_state , tstate , ctx ) :
"""Read inputs , process them , and write out outputs .
This is the core logic of MapReduce . It reads inputs from input reader ,
invokes user specified mapper function , and writes output with
output writer . It also updates shard _ s... | processing_limit = self . _processing_limit ( tstate . mapreduce_spec )
if processing_limit == 0 :
return
finished_shard = True
# Input reader may not be an iterator . It is only a container .
iterator = iter ( input_reader )
while True :
try :
entity = iterator . next ( )
except StopIteration :
... |
def calcValueAtBirth ( cLvlHist , BirthBool , PlvlHist , MrkvHist , DiscFac , CRRA ) :
'''Calculate expected value of being born in each Markov state using the realizations
of consumption for a history of many consumers . The histories should already be
trimmed of the " burn in " periods .
Parameters
cLvlHi... | J = np . max ( MrkvHist ) + 1
# Number of Markov states
T = MrkvHist . size
# Length of simulation
I = cLvlHist . shape [ 1 ]
# Number of agent indices in histories
u = lambda c : CRRAutility ( c , gam = CRRA )
# Initialize an array to hold each agent ' s lifetime utility
BirthsByPeriod = np . sum ( BirthBool , axis = ... |
def memory_enumerator ( buffer_ , * args , ** kwargs ) :
"""Return an enumerator that knows how to read raw memory .""" | _LOGGER . debug ( "Enumerating through (%d) bytes of archive data." , len ( buffer_ ) )
def opener ( archive_res ) :
_LOGGER . debug ( "Opening from (%d) bytes (memory_enumerator)." , len ( buffer_ ) )
_archive_read_open_memory ( archive_res , buffer_ )
if 'entry_cls' not in kwargs :
kwargs [ 'entry_cls' ] ... |
def sample ( self , observations_by_state ) :
"""Sample a new set of distribution parameters given a sample of observations from the given state .
The internal parameters are updated .
Parameters
observations : [ numpy . array with shape ( N _ k , ) ] with nstates elements
observations [ k ] are all observa... | from numpy . random import dirichlet
N , M = self . _output_probabilities . shape
# nstates , nsymbols
for i , obs_by_state in enumerate ( observations_by_state ) : # count symbols found in data
count = np . bincount ( obs_by_state , minlength = M ) . astype ( float )
# sample dirichlet distribution
count +... |
def json_based_stable_hash ( obj ) :
"""Computes a cross - kernel stable hash value for the given object .
The supported data structure are the built - in list , tuple and dict types .
Any included tuple or list , whether outer or nested , may only contain
values of the following built - in types : bool , int... | encoded_str = json . dumps ( obj = obj , skipkeys = False , ensure_ascii = False , check_circular = True , allow_nan = True , cls = None , indent = 0 , separators = ( ',' , ':' ) , default = None , sort_keys = True , ) . encode ( 'utf-8' )
return hashlib . sha256 ( encoded_str ) . hexdigest ( ) |
def install ( args ) :
"Install site from sources or module" | # Deactivate virtualenv
if 'VIRTUAL_ENV' in environ :
LOGGER . warning ( 'Virtualenv enabled: %s' % environ [ 'VIRTUAL_ENV' ] )
# Install from base modules
if args . module :
args . src = op . join ( settings . MOD_DIR , args . module )
assert op . exists ( args . src ) , "Not found module: %s" % args . mod... |
def get_category ( category_string , model = Category ) :
"""Convert a string , including a path , and return the Category object""" | model_class = get_cat_model ( model )
category = str ( category_string ) . strip ( "'\"" )
category = category . strip ( '/' )
cat_list = category . split ( '/' )
if len ( cat_list ) == 0 :
return None
try :
categories = model_class . objects . filter ( name = cat_list [ - 1 ] , level = len ( cat_list ) - 1 )
... |
def create_matrix_block_indices ( row_to_obs ) :
"""Parameters
row _ to _ obs : 2D ndarray .
There should be one row per observation per available alternative and
one column per observation . This matrix maps the rows of the design
matrix to the unique observations ( on the columns ) .
Returns
output _ ... | # Initialize the list of index arrays to be returned
output_indices = [ ]
# Determine the number of observations in the dataset
num_obs = row_to_obs . shape [ 1 ]
# Get the indices of the non - zero elements and their values
row_indices , col_indices , values = scipy . sparse . find ( row_to_obs )
# Iterate over each o... |
def _sound_settings ( area , setting , value , validate_value ) :
"""Will validate sound settings and values , returns data packet .""" | if validate_value :
if ( setting in CONST . VALID_SOUND_SETTINGS and value not in CONST . ALL_SETTING_SOUND ) :
raise AbodeException ( ERROR . INVALID_SETTING_VALUE , CONST . ALL_SETTING_SOUND )
elif ( setting == CONST . SETTING_ALARM_LENGTH and value not in CONST . ALL_SETTING_ALARM_LENGTH ) :
... |
def create ( gandi , datacenter , memory , cores , ip_version , bandwidth , login , password , hostname , image , run , background , sshkey , size , vlan , ip , script , script_args , ssh , gen_password ) :
"""Create a new virtual machine .
you can specify a configuration entry named ' sshkey ' containing
path ... | try :
gandi . datacenter . is_opened ( datacenter , 'iaas' )
except DatacenterLimited as exc :
if exc . date :
gandi . echo ( '/!\ Datacenter %s will be closed on %s, ' 'please consider using another datacenter.' % ( datacenter , exc . date ) )
if gandi . image . is_deprecated ( image , datacenter ) :
... |
def create ( cls , model , parent = None , uifile = '' , commit = True ) :
"""Prompts the user to create a new record for the inputed table .
: param model | < subclass of orb . Table >
parent | < QWidget >
: return < orb . Table > | | None / | instance of the inputed table class""" | # create the dialog
dlg = QDialog ( parent )
dlg . setWindowTitle ( 'Create %s' % model . schema ( ) . name ( ) )
# create the widget
cls = model . schema ( ) . property ( 'widgetClass' , cls )
widget = cls ( dlg )
if ( uifile ) :
widget . setUiFile ( uifile )
widget . setModel ( model )
widget . layout ( ) . setCo... |
def make_imshow_plot ( grid , name ) :
"""Takes a grid of RGB or RGBA values and a filename to save the figure into .
Generates a figure by coloring all grid cells appropriately .""" | plt . tick_params ( labelbottom = "off" , labeltop = "off" , labelleft = "off" , labelright = "off" , bottom = "off" , top = "off" , left = "off" , right = "off" )
plt . imshow ( grid , interpolation = "nearest" , aspect = 1 , zorder = 1 )
plt . tight_layout ( )
plt . savefig ( name , dpi = 1000 , bbox_inches = "tight"... |
def logspace_bins ( self , bins = None , units = None , conversion_function = convert_time , resolution = None ) :
"""Generates bin edges for a logspace tiling : there is one edge more than bins and each bin is between two edges""" | bins = self . logspace ( bins = bins , units = units , conversion_function = conversion_function , resolution = resolution , end_at_end = False )
resolution = np . mean ( ( bins [ : - 1 ] ) / ( bins [ 1 : ] ) )
bins = np . concatenate ( [ bins * np . sqrt ( resolution ) , bins [ - 1 : ] / np . sqrt ( resolution ) ] )
r... |
def get_product ( id = None , name = None ) :
"""Get a specific Product by name or ID""" | content = get_product_raw ( id , name )
if content :
return utils . format_json ( content ) |
def postprocess_keyevent ( self , event ) :
"""Post - process keypress event :
in InternalShell , this is method is called when shell is ready""" | event , text , key , ctrl , shift = restore_keyevent ( event )
# Is cursor on the last line ? and after prompt ?
if len ( text ) : # XXX : Shouldn ' t it be : ` if len ( unicode ( text ) . strip ( os . linesep ) ) ` ?
if self . has_selected_text ( ) :
self . check_selection ( )
self . restrict_cursor_po... |
def _show_details ( self ) :
"""Show traceback on its own dialog""" | if self . details . isVisible ( ) :
self . details . hide ( )
self . details_btn . setText ( _ ( 'Show details' ) )
else :
self . resize ( 570 , 700 )
self . details . document ( ) . setPlainText ( '' )
self . details . append_text_to_shell ( self . error_traceback , error = True , prompt = False )
... |
async def ack ( self , msg ) :
"""Used to manually acks a message .
: param msg : Message which is pending to be acked by client .""" | ack_proto = protocol . Ack ( )
ack_proto . subject = msg . proto . subject
ack_proto . sequence = msg . proto . sequence
await self . _nc . publish ( msg . sub . ack_inbox , ack_proto . SerializeToString ( ) ) |
def get_objective ( self ) :
"""Gets the related objective .
return : ( osid . learning . Objective ) - the related objective
raise : OperationFailed - unable to complete request
compliance : mandatory - This method must be implemented .""" | # Note that this makes the generic objectives call to Handcar
# without specifying the objectiveBank :
url_str = ( self . _base_url + '/objectives/' + self . _my_map [ 'objectiveId' ] )
return Objective ( self . _load_json ( url_str ) ) |
def up_to ( self , term : str ) -> str :
"""Parse and return segment terminated by the first occurence of a string .
Args :
term : Terminating string .
Raises :
EndOfInput : If ` term ` does not occur in the rest of the input text .""" | end = self . input . find ( term , self . offset )
if end < 0 :
raise EndOfInput ( self )
res = self . input [ self . offset : end ]
self . offset = end + 1
return res |
def pad ( args ) :
"""% prog pad blastfile cdtfile - - qbed q . pad . bed - - sbed s . pad . bed
Test and reconstruct candidate PADs .""" | from jcvi . formats . cdt import CDT
p = OptionParser ( pad . __doc__ )
p . set_beds ( )
p . add_option ( "--cutoff" , default = .3 , type = "float" , help = "The clustering cutoff to call similar [default: %default]" )
opts , args = p . parse_args ( args )
if len ( args ) != 2 :
sys . exit ( not p . print_help ( )... |
def process_multientry ( entry_list , prod_comp , coeff_threshold = 1e-4 ) :
"""Static method for finding a multientry based on
a list of entries and a product composition .
Essentially checks to see if a valid aqueous
reaction exists between the entries and the
product composition and returns a MultiEntry ... | dummy_oh = [ Composition ( "H" ) , Composition ( "O" ) ]
try : # Get balanced reaction coeffs , ensuring all < 0 or conc thresh
# Note that we get reduced compositions for solids and non - reduced
# compositions for ions because ions aren ' t normalized due to
# their charge state .
entry_comps = [ e . composition ... |
def encode ( self , pad = 106 ) :
"""Encodes this AIT command to binary .
If pad is specified , it indicates the maximum size of the encoded
command in bytes . If the encoded command is less than pad , the
remaining bytes are set to zero .
Commands sent to ISS payloads over 1553 are limited to 64 words
(1... | opcode = struct . pack ( '>H' , self . defn . opcode )
offset = len ( opcode )
size = max ( offset + self . defn . argsize , pad )
encoded = bytearray ( size )
encoded [ 0 : offset ] = opcode
encoded [ offset ] = self . defn . argsize
offset += 1
index = 0
for defn in self . defn . argdefns :
if defn . fixed :
... |
def _get_kind ( cls ) :
"""Override .
Make sure that the kind returned is the root class of the
polymorphic hierarchy .""" | bases = cls . _get_hierarchy ( )
if not bases : # We have to jump through some hoops to call the superclass '
# _ get _ kind ( ) method . First , this is called by the metaclass
# before the PolyModel name is defined , so it can ' t use
# super ( PolyModel , cls ) . _ get _ kind ( ) . Second , we can ' t just call
# Mo... |
import itertools
def deduplicate ( input_list ) :
"""Function to remove duplicates from a list of lists or list of elements .
Examples :
deduplicate ( [ [ 10 , 20 ] , [ 40 ] , [ 30 , 56 , 25 ] , [ 10 , 20 ] , [ 33 ] , [ 40 ] ] )
[ [ 10 , 20 ] , [ 30 , 56 , 25 ] , [ 33 ] , [ 40 ] ]
deduplicate ( [ ' a ' , ' ... | input_list . sort ( )
deduplicated = list ( item for item , _ in itertools . groupby ( input_list ) )
return deduplicated |
def listProcessingEras ( self , processing_version = '' ) :
"""Returns all processing eras in dbs""" | conn = self . dbi . connection ( )
try :
result = self . pelst . execute ( conn , processing_version )
return result
finally :
if conn :
conn . close ( ) |
def load_image ( self , file_path , redraw = True ) :
"""Accepts a path to an 8 x 8 image file and updates the LED matrix with
the image""" | if not os . path . exists ( file_path ) :
raise IOError ( '%s not found' % file_path )
img = Image . open ( file_path ) . convert ( 'RGB' )
pixel_list = list ( map ( list , img . getdata ( ) ) )
if redraw :
self . set_pixels ( pixel_list )
return pixel_list |
def noun ( self , plural : bool = False ) -> str :
"""Return a random noun in German .
: param plural : Return noun in plural .
: return : Noun .""" | key = 'plural' if plural else 'noun'
return self . random . choice ( self . _data [ key ] ) |
def to_pn ( self , sub_letter = None ) :
"""Returns the part number equivalent . For instance ,
a ' 1k ' would still be ' 1k ' , but a
'1.2k ' would , instead , be a ' 1k2'
: return :""" | string = str ( self )
if '.' not in string :
return string
# take care of the case of when there is no scaling unit
if not string [ - 1 ] . isalpha ( ) :
if sub_letter is not None :
return string . replace ( '.' , sub_letter )
return string
letter = string [ - 1 ]
return string . replace ( '.' , let... |
def get_access_token ( self , verifier = None ) :
"""Return the access token for this API . If we ' ve not fetched it yet ,
go out , request and memoize it .""" | if self . _access_token is None :
self . _access_token , self . _access_token_dict = self . _get_access_token ( verifier )
return self . _access_token |
def transformer_prepare_encoder ( inputs , target_space , hparams , features = None ) :
"""Prepare one shard of the model for the encoder .
Args :
inputs : a Tensor .
target _ space : a Tensor .
hparams : run hyperparameters
features : optionally pass the entire features dictionary as well .
This is nee... | ishape_static = inputs . shape . as_list ( )
encoder_input = inputs
if features and "inputs_segmentation" in features : # Packed dataset . Keep the examples from seeing each other .
inputs_segmentation = features [ "inputs_segmentation" ]
inputs_position = features [ "inputs_position" ]
targets_segmentation... |
def white_noise ( space , mean = 0 , stddev = 1 , seed = None ) :
"""Standard gaussian noise in space , pointwise ` ` N ( mean , stddev * * 2 ) ` ` .
Parameters
space : ` TensorSpace ` or ` ProductSpace `
The space in which the noise is created .
mean : ` ` space . field ` ` element or ` ` space ` ` ` eleme... | from odl . space import ProductSpace
with NumpyRandomSeed ( seed ) :
if isinstance ( space , ProductSpace ) :
values = [ white_noise ( subspace , mean , stddev ) for subspace in space ]
else :
if space . is_complex :
real = np . random . normal ( loc = mean . real , scale = stddev , ... |
def pip_list ( self , name = None , prefix = None , abspath = True ) :
"""Get list of pip installed packages .""" | if ( name and prefix ) or not ( name or prefix ) :
raise TypeError ( "conda pip: exactly one of 'name' " "or 'prefix' " "required." )
if name :
prefix = self . get_prefix_envname ( name )
pip_command = os . sep . join ( [ prefix , 'bin' , 'python' ] )
cmd_list = [ pip_command , PIP_LIST_SCRIPT ]
process_worker ... |
def cbow_batch ( centers , contexts , num_tokens , dtype , index_dtype ) :
"""Create a batch for CBOW training objective .""" | contexts_data , contexts_row , contexts_col = contexts
centers = mx . nd . array ( centers , dtype = index_dtype )
contexts = mx . nd . sparse . csr_matrix ( ( contexts_data , ( contexts_row , contexts_col ) ) , dtype = dtype , shape = ( len ( centers ) , num_tokens ) )
# yapf : disable
return centers , contexts |
def _clean_str ( self , s ) :
"""Returns a lowercase string with punctuation and bad chars removed
: param s : string to clean""" | return s . translate ( str . maketrans ( '' , '' , punctuation ) ) . replace ( '\u200b' , " " ) . strip ( ) . lower ( ) |
def _check_reliability ( self , old_value = None , new_value = None ) :
"""This function is called when the object is created and after
one of its configuration properties has changed . The new and old value
parameters are ignored , this is called after the property has been
changed and this is only concerned... | if _debug :
LocalScheduleObject . _debug ( "_check_reliability %r %r" , old_value , new_value )
try :
schedule_default = self . scheduleDefault
if schedule_default is None :
raise ValueError ( "scheduleDefault expected" )
if not isinstance ( schedule_default , Atomic ) :
raise TypeError ... |
def replace_by_etree ( self , root_el , el_idx = 0 ) :
"""Replace element .
Select element that has the same name as ` ` root _ el ` ` , then replace the selected
element with ` ` root _ el ` `
` ` root _ el ` ` can be a single element or the root of an element tree .
Args :
root _ el : element
New elem... | el = self . get_element_by_name ( root_el . tag , el_idx )
el [ : ] = list ( root_el )
el . attrib = root_el . attrib |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.