signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def toSolarDate ( self ) :
'''> > > LunarDate ( 1900 , 1 , 1 ) . toSolarDate ( )
datetime . date ( 1900 , 1 , 31)
> > > LunarDate ( 2008 , 9 , 4 ) . toSolarDate ( )
datetime . date ( 2008 , 10 , 2)
> > > LunarDate ( 1976 , 8 , 8 , 1 ) . toSolarDate ( )
datetime . date ( 1976 , 10 , 1)
> > > LunarDate ( ... | def _calcDays ( yearInfo , month , day , isLeapMonth ) :
isLeapMonth = int ( isLeapMonth )
res = 0
ok = False
for _month , _days , _isLeapMonth in self . _enumMonth ( yearInfo ) :
if ( _month , _isLeapMonth ) == ( month , isLeapMonth ) :
if 1 <= day <= _days :
res += ... |
def set_lacp_timeout ( self , name , value = None ) :
"""Configures the Port - Channel LACP fallback timeout
The fallback timeout configures the period an interface in
fallback mode remains in LACP mode without receiving a PDU .
Args :
name ( str ) : The Port - Channel interface name
value ( int ) : port ... | commands = [ 'interface %s' % name ]
string = 'port-channel lacp fallback timeout'
commands . append ( self . command_builder ( string , value = value ) )
return self . configure ( commands ) |
def update_bounds ( self , bounds ) :
'''Update cylinders start and end positions''' | starts = bounds [ : , 0 , : ]
ends = bounds [ : , 1 , : ]
self . bounds = bounds
self . lengths = np . sqrt ( ( ( ends - starts ) ** 2 ) . sum ( axis = 1 ) )
vertices , normals , colors = self . _process_reference ( )
self . tr . update_vertices ( vertices )
self . tr . update_normals ( normals ) |
def modify ( self , request , nodes , namespace , root_id , post_cut , breadcrumb ) :
"""Modify nodes of a menu""" | if breadcrumb :
return nodes
for node in nodes :
if node . attr . get ( 'hidden' ) :
node . visible = False
return nodes |
def reduce ( self , target_map , target_reduce , threads = 0 ) :
"""map / reduce this query among a bunch of processes
: param target _ map : callable , this function will be called once for each
row this query pulls out of the db , if you want something about the row
to be seen by the target _ reduce functio... | if not threads :
threads = multiprocessing . cpu_count ( )
# we subtract one for the main process
map_threads = threads - 1 if threads > 1 else 1
q = self . copy ( )
limit = q . bounds . limit
offset = q . bounds . offset
total_count = limit if limit else q . count ( )
limit_count = int ( math . ceil ( float ( tota... |
def list_metrics ( self , project , page_size = 0 , page_token = None ) :
"""List metrics for the project associated with this client .
: type project : str
: param project : ID of the project whose metrics are to be listed .
: type page _ size : int
: param page _ size : maximum number of metrics to return... | path = "projects/%s" % ( project , )
page_iter = self . _gapic_api . list_log_metrics ( path , page_size = page_size )
page_iter . client = self . _client
page_iter . next_page_token = page_token
page_iter . item_to_value = _item_to_metric
return page_iter |
def update_metadata ( self , key : str , msg : MaildirMessage ) -> None :
"""Uses : func : ` os . rename ` to atomically update the message filename
based on : meth : ` ~ mailbox . MaildirMessage . get _ info ` .""" | subpath = self . _lookup ( key )
subdir , name = os . path . split ( subpath )
new_subdir = msg . get_subdir ( )
new_name = key + self . colon + msg . get_info ( )
if subdir != new_subdir :
raise ValueError ( 'Message subdir may not be updated' )
elif name != new_name :
new_subpath = os . path . join ( msg . ge... |
def destroy ( self ) :
"""Cleanup the activty lifecycle listener""" | if self . widget :
self . set_active ( False )
super ( AndroidBarcodeView , self ) . destroy ( ) |
def line_type ( self , line_type ) :
"""Sets the line _ type of this ChartSettings .
Plot interpolation type . linear is default # noqa : E501
: param line _ type : The line _ type of this ChartSettings . # noqa : E501
: type : str""" | allowed_values = [ "linear" , "step-before" , "step-after" , "basis" , "cardinal" , "monotone" ]
# noqa : E501
if line_type not in allowed_values :
raise ValueError ( "Invalid value for `line_type` ({0}), must be one of {1}" # noqa : E501
. format ( line_type , allowed_values ) )
self . _line_type = line_type |
def as_constraint ( cls , constraint , model , constraint_type = None , ** init_kwargs ) :
"""Initiate a Model which should serve as a constraint . Such a
constraint - model should be initiated with knowledge of another
` ` BaseModel ` ` , from which it will take its parameters : :
model = Model ( { y : a * x... | allowed_types = [ sympy . Eq , sympy . Ge , sympy . Le ]
if isinstance ( constraint , Relational ) :
constraint_type = constraint . __class__
constraint = constraint . lhs - constraint . rhs
# Initiate the constraint model , in such a way that we take care
# of any dependencies
instance = cls . with_dependencie... |
def inject ( self ) :
"""inject code into sitecustomize . py that will inject pout into the builtins
so it will be available globally""" | if self . is_injected ( ) :
return False
with open ( self , mode = "a+" ) as fp :
fp . seek ( 0 )
fp . write ( "\n" . join ( [ "" , "try:" , " import pout" , "except ImportError:" , " pass" , "else:" , " pout.inject()" , "" , ] ) )
return True |
def limit ( self , value ) :
"""Allows for limiting number of results returned for query . Useful
for pagination .""" | self . _query = self . _query . limit ( value )
return self |
def message_to_objects ( message : str , sender : str , sender_key_fetcher : Callable [ [ str ] , str ] = None , user : UserType = None , ) -> List :
"""Takes in a message extracted by a protocol and maps it to entities .
: param message : XML payload
: type message : str
: param sender : Payload sender id
... | doc = etree . fromstring ( message )
if doc . tag in TAGS :
return element_to_objects ( doc , sender , sender_key_fetcher , user )
return [ ] |
def push ( self , cart , env = None , callback = None ) :
"""` cart ` - Release cart to push items from
` callback ` - Optional callback to call if juicer . utils . upload _ rpm succeeds
Pushes the items in a release cart to the pre - release environment .""" | juicer . utils . Log . log_debug ( "Initializing push of cart '%s'" % cart . cart_name )
if not env :
env = self . _defaults [ 'start_in' ]
cart . current_env = env
self . sign_cart_for_env_maybe ( cart , env )
self . upload ( env , cart , callback )
return True |
def changelog ( build ) :
"""create a changelog""" | build . packages . install ( "gitchangelog" )
changelog_text = subprocess . check_output ( [ "gitchangelog" , "HEAD...v0.2.9" ] )
with open ( os . path . join ( build . root , "CHANGELOG" ) , "wb+" ) as fh :
fh . write ( changelog_text ) |
def on_press ( callback , suppress = False ) :
"""Invokes ` callback ` for every KEY _ DOWN event . For details see ` hook ` .""" | return hook ( lambda e : e . event_type == KEY_UP or callback ( e ) , suppress = suppress ) |
def pollNextEvent ( self , pEvent ) :
"""Returns true and fills the event with the next event on the queue if there is one . If there are no events
this method returns false . uncbVREvent should be the size in bytes of the VREvent _ t struct""" | fn = self . function_table . pollNextEvent
result = fn ( byref ( pEvent ) , sizeof ( VREvent_t ) )
return result != 0 |
def parse_file_path ( cls , file_path ) :
"""Parse a file address path without the file specifier""" | address = None
pattern = cls . file_regex . match ( file_path )
if pattern :
address = pattern . group ( 1 )
return address |
def __update_filter ( self ) :
"""Create a combined filter . Set the resulting filter into the document controller .""" | filters = list ( )
if self . __date_filter :
filters . append ( self . __date_filter )
if self . __text_filter :
filters . append ( self . __text_filter )
self . document_controller . display_filter = ListModel . AndFilter ( filters ) |
def _update_estimate_and_sampler ( self , ell , ell_hat , weight , extra_info , ** kwargs ) :
"""Update the BB models and the estimates""" | stratum_idx = extra_info [ 'stratum' ]
self . _BB_TP . update ( ell * ell_hat , stratum_idx )
self . _BB_PP . update ( ell_hat , stratum_idx )
self . _BB_P . update ( ell , stratum_idx )
# Update model covariance matrix for stratum _ idx
self . _update_cov_model ( strata_to_update = [ stratum_idx ] )
# Update F - measu... |
def ensure_path_exists ( self ) : # type : ( LocalDestinationPath ) - > None
"""Ensure path exists
: param LocalDestinationPath self : this""" | if self . _is_dir is None :
raise RuntimeError ( 'is_dir not set' )
if self . _is_dir :
self . _path . mkdir ( mode = 0o750 , parents = True , exist_ok = True )
else :
if self . _path . exists ( ) and self . _path . is_dir ( ) :
raise RuntimeError ( ( 'destination path {} already exists and is a ' '... |
def generic_visit ( self , node ) :
"""Handle expressions we don ' t have custom code for .""" | assert isinstance ( node , ast . expr )
res = self . assign ( node )
return res , self . explanation_param ( self . display ( res ) ) |
def authenticate ( self , client_id , client_secret , use_cache = True ) :
"""Authenticate the given client against UAA . The resulting token
will be cached for reuse .""" | # We will reuse a token for as long as we have one cached
# and it hasn ' t expired .
if use_cache :
client = self . _get_client_from_cache ( client_id )
if ( client ) and ( not self . is_expired_token ( client ) ) :
self . authenticated = True
self . client = client
return
# Let ' s aut... |
def generate_empty_dicts ( size ) :
"""This function creates a list populated with empty dictionaries .
Examples :
generate _ empty _ dicts ( 5 ) - > [ { } , { } , { } , { } , { } ]
generate _ empty _ dicts ( 6 ) - > [ { } , { } , { } , { } , { } , { } ]
generate _ empty _ dicts ( 7 ) - > [ { } , { } , { } ... | return [ { } for _ in range ( size ) ] |
def commit_offsets_async ( self , offsets , callback = None ) :
"""Commit specific offsets asynchronously .
Arguments :
offsets ( dict { TopicPartition : OffsetAndMetadata } ) : what to commit
callback ( callable , optional ) : called as callback ( offsets , response )
response will be either an Exception o... | self . _invoke_completed_offset_commit_callbacks ( )
if not self . coordinator_unknown ( ) :
future = self . _do_commit_offsets_async ( offsets , callback )
else : # we don ' t know the current coordinator , so try to find it and then
# send the commit or fail ( we don ' t want recursive retries which can
# cause o... |
def fetch_messages ( self ) :
"""Sends FetchRequests for all topic / partitions set for consumption
Returns :
Generator that yields KafkaMessage structs
after deserializing with the configured ` deserializer _ class `
Note :
Refreshes metadata on errors , and resets fetch offset on
OffsetOutOfRange , pe... | max_bytes = self . _config [ 'fetch_message_max_bytes' ]
max_wait_time = self . _config [ 'fetch_wait_max_ms' ]
min_bytes = self . _config [ 'fetch_min_bytes' ]
if not self . _topics :
raise KafkaConfigurationError ( 'No topics or partitions configured' )
if not self . _offsets . fetch :
raise KafkaConfiguratio... |
def get_name_record ( name , include_history = False , include_expired = False , include_grace = True , proxy = None , hostport = None , history_page = None ) :
"""Get the record for a name or a subdomain . Optionally include its history , and optionally return an expired name or a name in its grace period .
Retu... | if isinstance ( name , ( str , unicode ) ) : # coerce string
name = str ( name )
assert proxy or hostport , 'Need either proxy handle or hostport string'
if proxy is None :
proxy = connect_hostport ( hostport )
# what do we expect ?
required = None
is_blockstack_id = False
is_blockstack_subdomain = False
if is_... |
def _einsum_equation ( input_shapes , output_shape ) :
"""Turn shapes into an einsum equation .
e . g . " ij , jk - > ik "
Args :
input _ shapes : a list of Shapes
output _ shape : a Shape
Returns :
a string""" | ret = [ ]
next_letter = ord ( "a" )
dim_to_letter = { }
for shape_num , shape in enumerate ( input_shapes + [ output_shape ] ) :
if shape_num == len ( input_shapes ) :
ret . append ( "->" )
elif shape_num > 0 :
ret . append ( "," )
for d in shape . dims :
if d not in dim_to_letter :
... |
def main ( ) :
"""NAME
vector _ mean . py
DESCRIPTION
calculates vector mean of vector data
INPUT FORMAT
takes dec , inc , int from an input file
SYNTAX
vector _ mean . py [ command line options ] [ < filename ]
OPTIONS
- h prints help message and quits
- f FILE , specify input file
- F FILE ,... | if '-h' in sys . argv : # check if help is needed
print ( main . __doc__ )
sys . exit ( )
# graceful quit
if '-f' in sys . argv :
dat = [ ]
ind = sys . argv . index ( '-f' )
file = sys . argv [ ind + 1 ]
else :
file = sys . stdin
# read from standard input
ofile = ""
if '-F' in sys . arg... |
def do_REMOTE ( self , target : str , remote_command : str , source : list , * args , ** kwargs ) -> None :
"""Send a remote command to a service . Used
Args :
target : The service that the command gets set to
remote _ command : The command to do remotely .
source : the binary source of the zmq _ socket . P... | if target == self . messaging . _service_name :
info = 'target for remote command is the bot itself! Returning the function'
self . logger . info ( info )
return self . _handle_command ( remote_command , source , * args , ** kwargs )
try :
target = self . messaging . _address_map [ target ]
except KeyEr... |
def clear_other_texts ( self , remove = False ) :
"""Make sure that no other text is a the same position as this one
This method clears all text instances in the figure that are at the
same position as the : attr : ` _ text ` attribute
Parameters
remove : bool
If True , the Text instances are permanently ... | fig = self . ax . get_figure ( )
# don ' t do anything if our figtitle is the only Text instance
if len ( fig . texts ) == 1 :
return
for i , text in enumerate ( fig . texts ) :
if text == self . _text :
continue
if text . get_position ( ) == self . _text . get_position ( ) :
if not remove :... |
def iter_points ( self ) :
"returns a list of tuples of names and values" | if not self . is_discrete ( ) :
raise ValueError ( "Patch is not discrete" )
names = sorted ( self . sets . keys ( ) )
icoords = [ self . sets [ name ] . iter_members ( ) for name in names ]
for coordinates in product ( * icoords ) :
yield tuple ( zip ( names , coordinates ) ) |
def decrypt ( receiver_prvhex : str , msg : bytes ) -> bytes :
"""Decrypt with eth private key
Parameters
receiver _ pubhex : str
Receiver ' s ethereum private key hex string
msg : bytes
Data to decrypt
Returns
bytes
Plain text""" | pubkey = msg [ 0 : 65 ]
# pubkey ' s length is 65 bytes
encrypted = msg [ 65 : ]
sender_public_key = hex2pub ( pubkey . hex ( ) )
private_key = hex2prv ( receiver_prvhex )
aes_key = derive ( private_key , sender_public_key )
return aes_decrypt ( aes_key , encrypted ) |
def parse_condition ( self , query , prev_key = None , last_prev_key = None ) :
"""Creates a recursive generator for parsing some types of Query ( )
conditions
: param query : Query object
: param prev _ key : The key at the next - higher level
: return : generator object , the last of which will be the com... | # use this to determine gt / lt / eq on prev _ query
logger . debug ( u'query: {} prev_query: {}' . format ( query , prev_key ) )
q = Query ( )
conditions = None
# deal with the { ' name ' : value } case by injecting a previous key
if not prev_key :
temp_query = copy . deepcopy ( query )
k , v = temp_query . po... |
def format_epilog ( self , ctx , formatter ) :
"""Writes the epilog into the formatter if it exists .""" | if self . epilog :
formatter . write_paragraph ( )
with formatter . indentation ( ) :
formatter . write_text ( self . epilog ) |
def register_run_plugins ( self , plugin_name , plugin_class ) :
"""Loads a plugin as a dictionary and attaches needed parts to correct Icetea run
global parts .
: param plugin _ name : Name of the plugins
: param plugin _ class : PluginBase
: return : Nothing""" | if plugin_name in self . registered_plugins :
raise PluginException ( "Plugin {} already registered! " "Duplicate plugins?" . format ( plugin_name ) )
self . logger . debug ( "Registering plugin %s" , plugin_name )
if plugin_class . get_allocators ( ) :
register_func = self . plugin_types [ PluginTypes . ALLOCA... |
async def ignore_list ( self , ctx ) :
"""Tells you what channels are currently ignored in this server .""" | ignored = self . config . get ( 'ignored' , [ ] )
channel_ids = set ( c . id for c in ctx . message . server . channels )
result = [ ]
for channel in ignored :
if channel in channel_ids :
result . append ( '<#{}>' . format ( channel ) )
if result :
await self . bot . responses . basic ( title = "Ignored... |
def get_pymata_version ( self ) :
"""This method retrieves the PyMata version number
: returns : PyMata version number .""" | task = asyncio . ensure_future ( self . core . get_pymata_version ( ) )
self . loop . run_until_complete ( task ) |
def pop ( self ) :
"""Pop dir off stack and change to it .""" | if len ( self . stack ) :
os . chdir ( self . stack . pop ( ) ) |
def _fit ( self , col ) :
"""Create a map of the empirical probability for each category .
Args :
col ( pandas . DataFrame ) : Data to transform .""" | column = col [ self . col_name ] . replace ( { np . nan : np . inf } )
frequencies = column . groupby ( column ) . count ( ) . rename ( { np . inf : None } ) . to_dict ( )
# next set probability ranges on interval [ 0,1]
start = 0
end = 0
num_vals = len ( col )
for val in frequencies :
prob = frequencies [ val ] / ... |
def timeout_at ( clock , coro = None , * args ) :
'''Execute the specified coroutine and return its result . However ,
issue a cancellation request to the calling task after seconds
have elapsed . When this happens , a TaskTimeout exception is
raised . If coro is None , the result of this function serves
as... | if coro :
return _timeout_after_func ( clock , True , coro , args )
return TimeoutAfter ( clock , absolute = True ) |
def makeAggShkHist ( self ) :
'''Make simulated histories of aggregate transitory and permanent shocks .
Histories are of length self . act _ T , for use in the general equilibrium
simulation . Draws on history of aggregate Markov states generated by
internal call to makeMrkvHist ( ) .
Parameters
None
R... | self . makeMrkvHist ( )
# Make a ( pseudo ) random sequence of Markov states
sim_periods = self . act_T
# For each Markov state in each simulated period , draw the aggregate shocks
# that would occur in that state in that period
StateCount = self . MrkvArray . shape [ 0 ]
PermShkAggHistAll = np . zeros ( ( StateCount ,... |
def unique_index ( df ) :
"""Assert that the index is unique
Parameters
df : DataFrame
Returns
df : DataFrame""" | try :
assert df . index . is_unique
except AssertionError as e :
e . args = df . index . get_duplicates ( )
raise
return df |
def my_log_message ( verbose , prio , msg ) :
"""Log to syslog , and possibly also to stderr .""" | syslog . syslog ( prio , msg )
if verbose or prio == syslog . LOG_ERR :
sys . stderr . write ( "%s\n" % ( msg ) ) |
def __version ( client ) :
'''Grab DRAC version''' | versions = { 9 : 'CMC' , 8 : 'iDRAC6' , 10 : 'iDRAC6' , 11 : 'iDRAC6' , 16 : 'iDRAC7' , 17 : 'iDRAC7' }
if isinstance ( client , paramiko . SSHClient ) :
( stdin , stdout , stderr ) = client . exec_command ( 'racadm getconfig -g idRacInfo' )
for i in stdout . readlines ( ) :
if i [ 2 : ] . startswith ( ... |
def to_dict ( self ) :
"""Convert the tree node to its dictionary representation .
: return : an expansion dictionary that represents the type and expansions of this tree node .
: rtype dict [ list [ union [ str , unicode ] ] ]""" | expansion_strings = [ ]
for expansion in self . expansions :
expansion_strings . extend ( expansion . to_strings ( ) )
return { self . type : expansion_strings , } |
def toLocalIterator ( self ) :
"""Returns an iterator that contains all of the rows in this : class : ` DataFrame ` .
The iterator will consume as much memory as the largest partition in this DataFrame .
> > > list ( df . toLocalIterator ( ) )
[ Row ( age = 2 , name = u ' Alice ' ) , Row ( age = 5 , name = u ... | with SCCallSiteSync ( self . _sc ) as css :
sock_info = self . _jdf . toPythonIterator ( )
return _load_from_socket ( sock_info , BatchedSerializer ( PickleSerializer ( ) ) ) |
def remove_action ( i ) :
"""Input : {
( repo _ uoa ) - repo UOA
module _ uoa - normally should be ' module ' already
data _ uoa - UOA of the module to be created
func - action
Output : {
return - return code = 0 , if successful
> 0 , if error
( error ) - error text if return > 0
Output of ' updat... | # Check if global writing is allowed
r = check_writing ( { } )
if r [ 'return' ] > 0 :
return r
o = i . get ( 'out' , '' )
ruoa = i . get ( 'repo_uoa' , '' )
muoa = i . get ( 'module_uoa' , '' )
duoa = i . get ( 'data_uoa' , '' )
func = i . get ( 'func' , '' )
if muoa == '' :
return { 'return' : 1 , 'error' : '... |
def upload_bam_to_s3 ( job , job_vars ) :
"""Upload bam to S3 . Requires S3AM and a ~ / . boto config file .""" | input_args , ids = job_vars
work_dir = job . fileStore . getLocalTempDir ( )
uuid = input_args [ 'uuid' ]
# I / O
job . fileStore . readGlobalFile ( ids [ 'alignments.bam' ] , os . path . join ( work_dir , 'alignments.bam' ) )
bam_path = os . path . join ( work_dir , 'alignments.bam' )
sample_name = uuid + '.bam'
# Par... |
def block ( self , ** kwargs ) :
"""Block the user .
Args :
* * kwargs : Extra options to send to the server ( e . g . sudo )
Raises :
GitlabAuthenticationError : If authentication is not correct
GitlabBlockError : If the user could not be blocked
Returns :
bool : Whether the user status has been chan... | path = '/users/%s/block' % self . id
server_data = self . manager . gitlab . http_post ( path , ** kwargs )
if server_data is True :
self . _attrs [ 'state' ] = 'blocked'
return server_data |
def _gen_sample ( self ) :
"""Generate a random captcha image sample
Returns
( numpy . ndarray , str )
Tuple of image ( numpy ndarray ) and character string of digits used to generate the image""" | num_str = self . get_rand ( self . num_digit_min , self . num_digit_max )
return self . captcha . image ( num_str ) , num_str |
def ip_info ( self , ip , repository_ids = None ) :
"""ip _ info
Returns information about the IP specified in the repository ids
defined .""" | if not repository_ids :
repository_ids = [ ]
repos = [ ]
for rid in repository_ids :
repos . append ( { 'id' : rid } )
return self . raw_query ( 'vuln' , 'getIP' , data = { 'ip' : ip , 'repositories' : repos } ) |
def get_process_definition_start ( fname , slug ) :
"""Find the first line of process definition .
The first line of process definition is the line with a slug .
: param str fname : Path to filename with processes
: param string slug : process slug
: return : line where the process definiton starts
: rtyp... | with open ( fname ) as file_ :
for i , line in enumerate ( file_ ) :
if re . search ( r'slug:\s*{}' . format ( slug ) , line ) :
return i + 1
# In case starting line is not found just return first line
return 1 |
def execPath ( self ) :
"""the executable application ' s path""" | vers = self . version . label if self . version else None
# executables in Versions folder are stored by baseVersion ( modified by game data patches )
return self . installedApp . exec_path ( vers ) |
def _create_producer ( self ) :
"""Tries to establish a Kafka consumer connection""" | if not self . closed :
try :
self . logger . debug ( "Creating new kafka producer using brokers: " + str ( self . settings [ 'KAFKA_HOSTS' ] ) )
return KafkaProducer ( bootstrap_servers = self . settings [ 'KAFKA_HOSTS' ] , value_serializer = lambda v : json . dumps ( v ) . encode ( 'utf-8' ) , retr... |
def redraw ( self , whence = 0 ) :
"""Redraw the canvas .
Parameters
whence
See : meth : ` get _ rgb _ object ` .""" | with self . _defer_lock :
whence = min ( self . _defer_whence , whence )
if not self . defer_redraw :
if self . _hold_redraw_cnt == 0 :
self . _defer_whence = self . _defer_whence_reset
self . redraw_now ( whence = whence )
else :
self . _defer_whence = whence... |
def draw_progress_bar ( cb , message , value , max_value ) :
""": type cb : cursebox . Cursebox""" | m_x = cb . width // 2
m_y = cb . height // 2
w = len ( message ) + 4
h = 3
draw_box ( cb , m_x - w // 2 , m_y - 1 , w , h )
message = " %s " % message
i = int ( ( value / max_value ) * ( len ( message ) + 2 ) )
message = "$" + message [ : i ] + "$" + message [ i : ]
draw_text ( cb , m_x - w // 2 + 1 , m_y , message ) |
def show_ver ( ** kwargs ) :
'''Shortcut to run ` show version ` on the NX - OS device .
. . code - block : : bash
salt ' * ' nxos . cmd show _ ver''' | command = 'show version'
info = ''
info = show ( command , ** kwargs )
if isinstance ( info , list ) :
info = info [ 0 ]
return info |
def name_history_merge ( h1 , h2 ) :
"""Given two name histories ( grouped by block ) , merge them .""" | ret = { }
blocks_1 = [ int ( b ) for b in h1 . keys ( ) ]
blocks_2 = [ int ( b ) for b in h2 . keys ( ) ]
# find overlapping blocks
overlap = list ( set ( blocks_1 ) . intersection ( set ( blocks_2 ) ) )
if len ( overlap ) > 0 :
for b in overlap :
h = h1 [ str ( b ) ] + h2 [ str ( b ) ]
h . sort ( l... |
def convert ( self , obj ) :
"""Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.0 . * type and
converts it to BY _ ID _ HONEY _ BADGERFISH version . The object is modified in place
and returned .""" | if self . pristine_if_invalid :
raise NotImplementedError ( 'pristine_if_invalid option is not supported yet' )
nex = get_nexml_el ( obj )
assert nex
self . _recursive_convert_dict ( nex )
nex [ '@nexml2json' ] = str ( BADGER_FISH_NEXSON_VERSION )
self . _single_el_list_to_dicts ( nex , 'otus' )
self . _single_el_l... |
def mod2pi ( ts ) :
"""For a timeseries where all variables represent phases ( in radians ) ,
return an equivalent timeseries where all values are in the range ( - pi , pi ]""" | return np . pi - np . mod ( np . pi - ts , 2 * np . pi ) |
def extract_spans ( html_string ) :
"""Creates a list of the spanned cell groups of [ row , column ] pairs .
Parameters
html _ string : str
Returns
list of lists of lists of int""" | try :
from bs4 import BeautifulSoup
except ImportError :
print ( "ERROR: You must have BeautifulSoup to use html2data" )
return
soup = BeautifulSoup ( html_string , 'html.parser' )
table = soup . find ( 'table' )
if not table :
return [ ]
trs = table . findAll ( 'tr' )
if len ( trs ) == 0 :
return [... |
def get_headers ( environ ) :
"""Returns only proper HTTP headers .""" | for key , value in environ . iteritems ( ) :
key = str ( key )
if key . startswith ( 'HTTP_' ) and key not in ( 'HTTP_CONTENT_TYPE' , 'HTTP_CONTENT_LENGTH' ) :
yield key [ 5 : ] . replace ( '_' , '-' ) . title ( ) , value
elif key in ( 'CONTENT_TYPE' , 'CONTENT_LENGTH' ) :
yield key . replac... |
def move_up ( self ) :
"""Move up one level in the hierarchy , unless already on top .""" | if self . current_item . parent is not None :
self . current_item = self . current_item . parent
for f in self . _hooks [ "up" ] :
f ( self )
if self . current_item is self . root :
for f in self . _hooks [ "top" ] :
f ( self )
return self |
def create_result ( self , local_path , container_path , permissions , meta , val , dividers ) :
"""Default permissions to rw""" | if permissions is NotSpecified :
permissions = 'rw'
return Mount ( local_path , container_path , permissions ) |
def verify_ocsp ( cls , certificate , issuer ) :
"""Runs OCSP verification and returns error code - 0 means success""" | return OCSPVerifier ( certificate , issuer , cls . get_ocsp_url ( ) , cls . get_ocsp_responder_certificate_path ( ) ) . verify ( ) |
def get_batches ( self , batch_size , shuffle = True ) :
"""Get batch iterator
Parameters
batch _ size : int
size of one batch
shuffle : bool
whether to shuffle batches . Don ' t set to True when evaluating on dev or test set .
Returns
tuple
word _ inputs , tag _ inputs , arc _ targets , rel _ targe... | batches = [ ]
for bkt_idx , bucket in enumerate ( self . _buckets ) :
bucket_size = bucket . shape [ 1 ]
n_tokens = bucket_size * self . _bucket_lengths [ bkt_idx ]
n_splits = min ( max ( n_tokens // batch_size , 1 ) , bucket_size )
range_func = np . random . permutation if shuffle else np . arange
... |
def _offset_subplot_ids ( fig , offsets ) :
"""Apply offsets to the subplot id numbers in a figure .
Note : This function mutates the input figure dict
Note : This function assumes that the normalize _ subplot _ ids function has
already been run on the figure , so that all layout subplot properties in
use a... | # Offset traces
for trace in fig . get ( 'data' , None ) :
trace_type = trace . get ( 'type' , 'scatter' )
subplot_types = _trace_to_subplot . get ( trace_type , [ ] )
for subplot_type in subplot_types :
subplot_prop_name = _get_subplot_prop_name ( subplot_type )
# Compute subplot value pref... |
def CredibleInterval ( self , percentage = 90 ) :
"""Computes the central credible interval .
If percentage = 90 , computes the 90 % CI .
Args :
percentage : float between 0 and 100
Returns :
sequence of two floats , low and high""" | prob = ( 1 - percentage / 100.0 ) / 2
interval = self . Value ( prob ) , self . Value ( 1 - prob )
return interval |
def convert ( gr , raw_node ) :
"""Convert raw node information to a Node or Leaf instance .
This is passed to the parser driver which calls it whenever a reduction of a
grammar rule produces a new complete node , so that the tree is build
strictly bottom - up .""" | type , value , context , children = raw_node
if children or type in gr . number2symbol : # If there ' s exactly one child , return that child instead of
# creating a new node .
if len ( children ) == 1 :
return children [ 0 ]
return Node ( type , children , context = context )
else :
return Leaf ( t... |
def assign_method ( stochastic , scale = None , verbose = - 1 ) :
"""Returns a step method instance to handle a
variable . If several methods have the same competence ,
it picks one arbitrarily ( using set . pop ( ) ) .""" | # Retrieve set of best candidates
best_candidates = pick_best_methods ( stochastic )
# Randomly grab and appropriate method
method = best_candidates . pop ( )
failure_header = """Failed attempting to automatically assign step method class %s
to stochastic variable %s. Try setting %s's competence method to return 0
and ... |
def main ( ) :
"""Zebrafish :
1 . Map ENSP to ZFIN Ids using Intermine
2 . Map deprecated ENSP IDs to ensembl genes
by querying the ensembl database then use
intermine to resolve to gene IDs
Mouse : Map deprecated ENSP IDs to ensembl genes
by querying the ensembl database then use
intermine to resolve... | parser = argparse . ArgumentParser ( usage = __doc__ )
parser . add_argument ( '--config' , '-c' , required = True , help = 'JSON configuration file' )
parser . add_argument ( '--out' , '-o' , required = False , help = 'output directory' , default = "./" )
parser . add_argument ( '--use_cache' , '-cached' , action = "s... |
def search_expression_levels ( self , rna_quantification_id = "" , names = [ ] , threshold = 0.0 ) :
"""Returns an iterator over the ExpressionLevel objects from the server
: param str feature _ ids : The IDs of the
: class : ` ga4gh . protocol . Feature ` of interest .
: param str rna _ quantification _ id :... | request = protocol . SearchExpressionLevelsRequest ( )
request . rna_quantification_id = rna_quantification_id
request . names . extend ( names )
request . threshold = threshold
request . page_size = pb . int ( self . _page_size )
return self . _run_search_request ( request , "expressionlevels" , protocol . SearchExpre... |
def factory ( name , desc , type , subtypes = None , required = True , default = None , ctor = None , hide = False , ) :
"""desc : >
Creates a DocStringArg and recursively includes child
docstrings if they are not JSON types .
args :
- name : name
desc : The name of the argument
type : str
- name : de... | if ctor :
type_assert ( ctor , str )
module_name , cls_name , method_name = ctor . rsplit ( '.' , 2 )
module = importlib . import_module ( module_name )
cls = getattr ( module , cls_name )
method = getattr ( cls , method_name )
docstring = DocString . from_ctor ( method )
else :
docstring = ... |
def send_exit_with_code ( cls , sock , code ) :
"""Send an Exit chunk over the specified socket , containing the specified return code .""" | encoded_exit_status = cls . encode_int ( code )
cls . send_exit ( sock , payload = encoded_exit_status ) |
def array ( a , dtype : type = None , ** kwargs ) -> np . ndarray :
"Same as ` np . array ` but also handles generators . ` kwargs ` are passed to ` np . array ` with ` dtype ` ." | if not isinstance ( a , collections . Sized ) and not getattr ( a , '__array_interface__' , False ) :
a = list ( a )
if np . int_ == np . int32 and dtype is None and is_listy ( a ) and len ( a ) and isinstance ( a [ 0 ] , int ) :
dtype = np . int64
return np . array ( a , dtype = dtype , ** kwargs ) |
def get_mappings_for_fit ( self , dense = False ) :
"""Parameters
dense : bool , optional .
Dictates if sparse matrices will be returned or dense numpy arrays .
Returns
mapping _ dict : OrderedDict .
Keys will be ` [ " rows _ to _ obs " , " rows _ to _ alts " , " chosen _ row _ to _ obs " ,
" rows _ to ... | return create_long_form_mappings ( self . data , self . obs_id_col , self . alt_id_col , choice_col = self . choice_col , nest_spec = self . nest_spec , mix_id_col = self . mixing_id_col , dense = dense ) |
def setValue ( self , value ) :
"""Sets the value that will be used for this query instance .
: param value < variant >""" | self . __value = projex . text . decoded ( value ) if isinstance ( value , ( str , unicode ) ) else value |
def build_query ( self ) :
'''Using the three graphs derived from self . _ diff _ graph ( ) , build a sparql update query in the format :
PREFIX foo : < http : / / foo . com >
PREFIX bar : < http : / / bar . com >
DELETE { . . . }
INSERT { . . . }
WHERE { . . . }
Args :
None : uses variables from self... | # derive namespaces to include prefixes in Sparql update query
self . _derive_namespaces ( )
sparql_query = ''
# add prefixes
for ns_prefix , ns_uri in self . update_prefixes . items ( ) :
sparql_query += "PREFIX %s: <%s>\n" % ( ns_prefix , str ( ns_uri ) )
# deletes
removed_serialized = self . diffs . removed . se... |
def set_schema_to_public ( self ) :
"""Instructs to stay in the common ' public ' schema .""" | self . tenant = FakeTenant ( schema_name = get_public_schema_name ( ) )
self . schema_name = get_public_schema_name ( )
self . set_settings_schema ( self . schema_name )
self . search_path_set = False |
def _AnyMessageToJsonObject ( self , message ) :
"""Converts Any message according to Proto3 JSON Specification .""" | if not message . ListFields ( ) :
return { }
# Must print @ type first , use OrderedDict instead of { }
js = OrderedDict ( )
type_url = message . type_url
js [ '@type' ] = type_url
sub_message = _CreateMessageFromTypeUrl ( type_url )
sub_message . ParseFromString ( message . value )
message_descriptor = sub_message... |
def delete_event ( self , id , ** data ) :
"""DELETE / events / : id /
Deletes an event if the delete is permitted . In order for a delete to be permitted , there must be no pending or
completed orders . Returns a boolean indicating success or failure of the delete .""" | return self . delete ( "/events/{0}/" . format ( id ) , data = data ) |
def delaunay_2d ( self , tol = 1e-05 , alpha = 0.0 , offset = 1.0 , bound = False , inplace = False ) :
"""Apply a delaunay 2D filter along the best fitting plane""" | alg = vtk . vtkDelaunay2D ( )
alg . SetProjectionPlaneMode ( vtk . VTK_BEST_FITTING_PLANE )
alg . SetInputDataObject ( self )
alg . SetTolerance ( tol )
alg . SetAlpha ( alpha )
alg . SetOffset ( offset )
alg . SetBoundingTriangulation ( bound )
alg . Update ( )
mesh = _get_output ( alg )
if inplace :
self . overwr... |
def register_lookup ( cls , lookup , lookup_name = None ) :
"""Register a Lookup to a class""" | if lookup_name is None :
lookup_name = lookup . lookup_name
if 'class_lookups' not in cls . __dict__ :
cls . class_lookups = { }
cls . class_lookups [ lookup_name ] = lookup
cls . _clear_cached_lookups ( )
return lookup |
def DefaultSelector ( ) :
"""This function serves as a first call for DefaultSelector to
detect if the select module is being monkey - patched incorrectly
by eventlet , greenlet , and preserve proper behavior .""" | global _DEFAULT_SELECTOR
if _DEFAULT_SELECTOR is None :
if platform . python_implementation ( ) == 'Jython' : # Platform - specific : Jython
_DEFAULT_SELECTOR = JythonSelectSelector
elif _can_allocate ( 'kqueue' ) :
_DEFAULT_SELECTOR = KqueueSelector
elif _can_allocate ( 'devpoll' ) :
... |
def _cosine ( a , b ) :
"""Return the len ( a & b ) / len ( a )""" | return 1. * len ( a & b ) / ( math . sqrt ( len ( a ) ) * math . sqrt ( len ( b ) ) ) |
def link_text ( self ) :
"""Get a text represention of the links node .
: return :""" | s = ''
links_node = self . metadata . find ( 'links' )
if links_node is None :
return s
links = links_node . getchildren ( )
if links is None :
return s
s += 'IOC Links\n'
for link in links :
rel = link . attrib . get ( 'rel' , 'No Rel' )
href = link . attrib . get ( 'href' )
text = link . text
... |
def customer_lifetime_value ( self , transaction_prediction_model , frequency , recency , T , monetary_value , time = 12 , discount_rate = 0.01 , freq = "D" ) :
"""Return customer lifetime value .
This method computes the average lifetime value for a group of one
or more customers .
Parameters
transaction _... | # use the Gamma - Gamma estimates for the monetary _ values
adjusted_monetary_value = self . conditional_expected_average_profit ( frequency , monetary_value )
return _customer_lifetime_value ( transaction_prediction_model , frequency , recency , T , adjusted_monetary_value , time , discount_rate , freq = freq ) |
def persist_perf ( run , session , svg_path ) :
"""Persist the flamegraph in the database .
The flamegraph exists as a SVG image on disk until we persist it in the
database .
Args :
run : The run we attach these perf measurements to .
session : The db transaction we belong to .
svg _ path : The path to ... | from benchbuild . utils import schema as s
with open ( svg_path , 'r' ) as svg_file :
svg_data = svg_file . read ( )
session . add ( s . Metadata ( name = "perf.flamegraph" , value = svg_data , run_id = run . id ) ) |
def sample_forecast_max_hail ( self , dist_model_name , condition_model_name , num_samples , condition_threshold = 0.5 , query = None ) :
"""Samples every forecast hail object and returns an empirical distribution of possible maximum hail sizes .
Hail sizes are sampled from each predicted gamma distribution . The... | if query is not None :
dist_forecasts = self . matched_forecasts [ "dist" ] [ dist_model_name ] . query ( query )
dist_forecasts = dist_forecasts . reset_index ( drop = True )
condition_forecasts = self . matched_forecasts [ "condition" ] [ condition_model_name ] . query ( query )
condition_forecasts = ... |
def parse_query_parms ( method , uri , query_str ) :
"""Parse the specified query parms string and return a dictionary of query
parameters . The key of each dict item is the query parameter name , and the
value of each dict item is the query parameter value . If a query parameter
shows up more than once , the... | if not query_str :
return None
query_parms = { }
for query_item in query_str . split ( '&' ) : # Example for these items : ' name = a % 20b '
if query_item == '' :
continue
items = query_item . split ( '=' )
if len ( items ) != 2 :
raise BadRequestError ( method , uri , reason = 1 , mess... |
def from_data ( data ) :
"""Create a chunk from data including header and length bytes .""" | header , length = struct . unpack ( '4s<I' , data [ : 8 ] )
data = data [ 8 : ]
return RiffDataChunk ( header , data ) |
def check_and_order_id_inputs ( rid , ridx , cid , cidx , row_meta_df , col_meta_df ) :
"""Makes sure that ( if entered ) id inputs entered are of one type ( string id or index )
Input :
- rid ( list or None ) : if not None , a list of rids
- ridx ( list or None ) : if not None , a list of indexes
- cid ( l... | ( row_type , row_ids ) = check_id_idx_exclusivity ( rid , ridx )
( col_type , col_ids ) = check_id_idx_exclusivity ( cid , cidx )
row_ids = check_and_convert_ids ( row_type , row_ids , row_meta_df )
ordered_ridx = get_ordered_idx ( row_type , row_ids , row_meta_df )
col_ids = check_and_convert_ids ( col_type , col_ids ... |
def transform_data ( self , data ) :
"""Apply pre - processing transformation to data , and add it to data
dict .
Parameters
data : instance of Segments
segments including ' data ' ( ChanTime )
Returns
instance of Segments
same object with transformed data as ' trans _ data ' ( ChanTime )""" | trans = self . trans
differ = trans [ 'diff' ] . get_value ( )
bandpass = trans [ 'bandpass' ] . get_value ( )
notch1 = trans [ 'notch1' ] . get_value ( )
notch2 = trans [ 'notch2' ] . get_value ( )
for seg in data :
dat = seg [ 'data' ]
if differ :
dat = math ( dat , operator = diff , axis = 'time' )
... |
def GetPresetsInformation ( cls ) :
"""Retrieves the presets information .
Returns :
list [ tuple ] : containing :
str : preset name
str : comma separated parser names that are defined by the preset""" | parser_presets_information = [ ]
for preset_definition in ParsersManager . GetPresets ( ) :
preset_information_tuple = ( preset_definition . name , ', ' . join ( preset_definition . parsers ) )
# TODO : refactor to pass PresetDefinition .
parser_presets_information . append ( preset_information_tuple )
retu... |
def slamdunkUtrRatesPlot ( self ) :
"""Generate the UTR rates plot""" | cats = OrderedDict ( )
keys = [ 'T>C' , 'A>T' , 'A>G' , 'A>C' , 'T>A' , 'T>G' , 'G>A' , 'G>T' , 'G>C' , 'C>A' , 'C>T' , 'C>G' ]
for i , v in enumerate ( keys ) :
cats [ v ] = { 'color' : self . plot_cols [ i ] }
pconfig = { 'id' : 'slamdunk_utrratesplot' , 'title' : 'Slamdunk: Overall conversion rates per UTR' , 'c... |
def create_job ( self ) :
"""Create public Luna job
Returns :
job _ id ( basestring ) : Luna job id""" | my_user_agent = None
try :
my_user_agent = pkg_resources . require ( 'netort' ) [ 0 ] . version
except pkg_resources . DistributionNotFound :
my_user_agent = 'DistributionNotFound'
finally :
headers = { "User-Agent" : "Uploader/{uploader_ua}, {upward_ua}" . format ( upward_ua = self . meta . get ( 'user_age... |
def on_config_value_changed ( self , config_m , prop_name , info ) :
"""Callback when a config value has been changed
: param ConfigModel config _ m : The config model that has been changed
: param str prop _ name : Should always be ' config '
: param dict info : Information e . g . about the changed config k... | config_key = info [ 'args' ] [ 1 ]
if config_key in [ "EXECUTION_TICKER_ENABLED" ] :
self . check_configuration ( ) |
def polyline ( self , arr ) :
"""Draw a set of lines""" | for i in range ( 0 , len ( arr ) - 1 ) :
self . line ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] , arr [ i + 1 ] [ 0 ] , arr [ i + 1 ] [ 1 ] ) |
def submit ( self ) :
"""Partitions the file into chunks and submits them into group of 4
for download on the api download pool .""" | futures = [ ]
while self . submitted < 4 and not self . done ( ) :
part = self . parts . pop ( 0 )
futures . append ( self . pool . submit ( _download_part , self . file_path , self . session , self . url , self . retry , self . timeout , * part ) )
self . submitted += 1
self . total_submitted += 1
retu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.