signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def normalize_scheme ( path , ext ) :
"""Normalize scheme for paths related to hdfs""" | path = addextension ( path , ext )
parsed = urlparse ( path )
if parsed . scheme : # this appears to already be a fully - qualified URI
return path
else : # this looks like a local path spec
import os
dirname , filename = os . path . split ( path )
if not os . path . isabs ( dirname ) : # need to make r... |
def action ( self , * action_names ) :
"""Decorator , registering them as actions""" | def action_wrapper ( decorated ) :
@ functools . wraps ( decorated )
def wrapper ( argv ) :
kwargs = dict ( arg . split ( '=' ) for arg in argv )
try :
return decorated ( ** kwargs )
except TypeError as e :
if decorated . __doc__ :
e . args += ( de... |
def instruction_BLT ( self , opcode , ea ) :
"""Causes a branch if either , but not both , of the N ( negative ) or V
( overflow ) bits is set . That is , branch if the sign of a valid twos
complement result is , or would be , negative . When used after a subtract
or compare operation on twos complement binar... | if ( self . N ^ self . V ) == 1 : # N xor V
# log . info ( " $ % x BLT branch to $ % x , because N XOR V = = 1 \ t | % s " % (
# self . program _ counter , ea , self . cfg . mem _ info . get _ shortest ( ea )
self . program_counter . set ( ea ) |
def gid_exists ( gid ) :
"""Check if a gid exists""" | try :
grp . getgrgid ( gid )
gid_exists = True
except KeyError :
gid_exists = False
return gid_exists |
def parse ( self , obj ) :
"""Parse the object ' s properties according to its default types .""" | for k , default in obj . __class__ . defaults . items ( ) :
typ = type ( default )
if typ is str :
continue
v = getattr ( obj , k )
if typ is int :
setattr ( obj , k , int ( v or default ) )
elif typ is float :
setattr ( obj , k , float ( v or default ) )
elif typ is bool... |
def check ( state , unused = False , style = False , ignore = None , args = None , ** kwargs ) :
"""Checks for security vulnerabilities and against PEP 508 markers provided in Pipfile .""" | from . . core import do_check
do_check ( three = state . three , python = state . python , system = state . system , unused = unused , ignore = ignore , args = args , pypi_mirror = state . pypi_mirror , ) |
def _scan ( self ) :
"""For every utterance , calculate the size it will need in memory .""" | utt_sizes = { }
for dset_name in self . utt_ids :
per_container = [ ]
for cnt in self . containers :
dset = cnt . _file [ dset_name ]
dtype_size = dset . dtype . itemsize
record_size = dtype_size * dset . size
per_container . append ( record_size )
utt_size = sum ( per_contai... |
def set_time ( time ) :
'''Sets the current time . Must be in 24 hour format .
: param str time : The time to set in 24 hour format . The value must be
double quoted . ie : ' " 17:46 " '
: return : True if successful , False if not
: rtype : bool
: raises : SaltInvocationError on Invalid Time format
: r... | # time must be double quoted ' " 17:46 " '
time_format = _get_date_time_format ( time )
dt_obj = datetime . strptime ( time , time_format )
cmd = 'systemsetup -settime {0}' . format ( dt_obj . strftime ( '%H:%M:%S' ) )
return salt . utils . mac_utils . execute_return_success ( cmd ) |
def NewFromCmy ( c , m , y , alpha = 1.0 , wref = _DEFAULT_WREF ) :
'''Create a new instance based on the specifed CMY values .
Parameters :
The Cyan component value [ 0 . . . 1]
The Magenta component value [ 0 . . . 1]
The Yellow component value [ 0 . . . 1]
: alpha :
The color transparency [ 0 . . . 1... | return Color ( Color . CmyToRgb ( c , m , y ) , 'rgb' , alpha , wref ) |
def find_one_data_object ( zero_ok = False , more_ok = True , ** kwargs ) :
""": param zero _ ok :
If False ( default ) , : class : ` ~ dxpy . exceptions . DXSearchError ` is
raised if the search has 0 results ; if True , returns None if the
search has 0 results
: type zero _ ok : bool
: param more _ ok :... | return _find_one ( find_data_objects , zero_ok = zero_ok , more_ok = more_ok , ** kwargs ) |
def pop_density ( data : CityInfo ) -> str :
"""Calculate the population density from the data entry""" | if not isinstance ( data , CityInfo ) :
raise AttributeError ( "Argument to pop_density() must be an instance of CityInfo" )
return no_dec ( data . get_population ( ) / data . get_area ( ) ) |
def network_security_group_present ( name , resource_group , tags = None , security_rules = None , connection_auth = None , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Ensure a network security group exists .
: param name :
Name of the network security group .
: param resource _ group :
The resource gr... | ret = { 'name' : name , 'result' : False , 'comment' : '' , 'changes' : { } }
if not isinstance ( connection_auth , dict ) :
ret [ 'comment' ] = 'Connection information must be specified via connection_auth dictionary!'
return ret
nsg = __salt__ [ 'azurearm_network.network_security_group_get' ] ( name , resourc... |
def normalize_weights ( self , IIMax , IEMax , EIMax ) :
"""Rescale our weight matrices to have a certain maximum absolute value .
: param IINorm : The target maximum for the II weights
: param IENorm : The target maximum for both IE weight matrices
: param EINorm : The target maximum for both EI weight matri... | weights = [ self . weightsII , self . weightsIEL , self . weightsIER , self . weightsELI , self . weightsERI ]
norms = [ IIMax , IEMax , IEMax , EIMax , EIMax ]
for w , n in zip ( weights , norms ) :
maximum = np . amax ( np . abs ( w ) )
w /= maximum
w *= n |
def exerciseOptions ( self , contract : Contract , exerciseAction : int , exerciseQuantity : int , account : str , override : int ) :
"""Exercise an options contract .
https : / / interactivebrokers . github . io / tws - api / options . html
Args :
contract : The option contract to be exercised .
exerciseAc... | reqId = self . client . getReqId ( )
self . client . exerciseOptions ( reqId , contract , exerciseAction , exerciseQuantity , account , override ) |
def global_import ( mod_name ) :
"""This function search sys . path [ 1 : ] , return specified module .
sys . path [ 1 : ] means the directories other than current directory ( ' . / ' ) .
' mod _ name ' as an argument is string type object .""" | mod_tuple = imp . find_module ( mod_name , sys . path [ 1 : ] )
mod = imp . load_module ( mod_name , mod_tuple [ 0 ] , mod_tuple [ 1 ] , mod_tuple [ 2 ] )
return mod |
def has_task_of_type ( self , typ ) :
"""Returns True if this goal has a task of the given type ( or a subtype of it ) .""" | for task_type in self . task_types ( ) :
if issubclass ( task_type , typ ) :
return True
return False |
def format ( input , ** params ) :
"""Appends string formatted value to result
: param input :
: param params :
: return :""" | PARAM_FORMAT_STRING = 'format.string'
PARAM_FORMAT_INPUT = 'format.input'
PARAM_RESULT_FIELD = 'result.field'
IN_DESC_FIELD = 'field'
IN_DESC_TYPE = 'type'
format_string = params . get ( PARAM_FORMAT_STRING )
format_inputs = params . get ( PARAM_FORMAT_INPUT )
result_field = params . get ( PARAM_RESULT_FIELD )
for row ... |
def advance ( self , size : int ) -> None :
"""Advance the current buffer position by ` ` size ` ` bytes .""" | assert 0 < size <= self . _size
self . _size -= size
pos = self . _first_pos
buffers = self . _buffers
while buffers and size > 0 :
is_large , b = buffers [ 0 ]
b_remain = len ( b ) - size - pos
if b_remain <= 0 :
buffers . popleft ( )
size -= len ( b ) - pos
pos = 0
elif is_larg... |
def concat_batch_variantcalls ( items , region_block = True , skip_jointcheck = False ) :
"""CWL entry point : combine variant calls from regions into single VCF .""" | items = [ utils . to_single_data ( x ) for x in items ]
batch_name = _get_batch_name ( items , skip_jointcheck )
variantcaller = _get_batch_variantcaller ( items )
# Pre - called input variant files
if not variantcaller and all ( d . get ( "vrn_file" ) for d in items ) :
return { "vrn_file" : items [ 0 ] [ "vrn_fil... |
def find_biggest_divisible_set ( arr , size ) :
"""Function to find the biggest subset where each pair of its elements is divisible .
For example :
> > > find _ biggest _ divisible _ set ( [ 1 , 3 , 6 , 13 , 17 , 18 ] , 6)
> > > find _ biggest _ divisible _ set ( [ 10 , 5 , 3 , 15 , 20 ] , 5)
> > > find _ b... | # Create an array to store subset lengths
subset_lengths = [ 0 ] * size
# Initialize each position as 1
subset_lengths [ size - 1 ] = 1
# Traverse from the second last element towards the first
for i in range ( size - 2 , - 1 , - 1 ) :
max_length = 0
for j in range ( i + 1 , size ) : # Check if element is divis... |
def schema ( self ) :
"""Returns the schema of this : class : ` DataFrame ` as a : class : ` pyspark . sql . types . StructType ` .
> > > df . schema
StructType ( List ( StructField ( age , IntegerType , true ) , StructField ( name , StringType , true ) ) )""" | if self . _schema is None :
try :
self . _schema = _parse_datatype_json_string ( self . _jdf . schema ( ) . json ( ) )
except AttributeError as e :
raise Exception ( "Unable to parse datatype from schema. %s" % e )
return self . _schema |
def reset ( self ) :
"""Resets the configuration , and overwrites the existing configuration
file .""" | self . _options = { }
self . save ( force = True )
self . _success = True |
def add_data_point ( self , x , y , number_format = None ) :
"""Return an XyDataPoint object newly created with values * x * and * y * ,
and appended to this sequence .""" | data_point = XyDataPoint ( self , x , y , number_format )
self . append ( data_point )
return data_point |
def read_some ( self ) :
"""Read at least one byte of cooked data unless EOF is hit .
Return b ' ' if EOF is hit .""" | yield from self . process_rawq ( )
while not self . cookedq and not self . eof :
yield from self . fill_rawq ( )
yield from self . process_rawq ( )
buf = self . cookedq
self . cookedq = b''
return buf |
def write ( objct , fileoutput , binary = True ) :
"""Write 3D object to file .
Possile extensions are :
- vtk , vti , ply , obj , stl , byu , vtp , xyz , tif , png , bmp .""" | obj = objct
if isinstance ( obj , Actor ) :
obj = objct . polydata ( True )
elif isinstance ( obj , vtk . vtkActor ) :
obj = objct . GetMapper ( ) . GetInput ( )
fr = fileoutput . lower ( )
if ".vtk" in fr :
w = vtk . vtkPolyDataWriter ( )
elif ".ply" in fr :
w = vtk . vtkPLYWriter ( )
elif ".stl" in fr... |
async def raw ( self , command , * args , _conn = None , ** kwargs ) :
"""Send the raw command to the underlying client . Note that by using this CMD you
will lose compatibility with other backends .
Due to limitations with aiomcache client , args have to be provided as bytes .
For rest of backends , str .
... | start = time . monotonic ( )
ret = await self . _raw ( command , * args , encoding = self . serializer . encoding , _conn = _conn , ** kwargs )
logger . debug ( "%s (%.4f)s" , command , time . monotonic ( ) - start )
return ret |
def unique ( iterable , key = None ) :
"""Removes duplicates from given iterable , using given key as criterion .
: param key : Key function which returns a hashable ,
uniquely identifying an object .
: return : Iterable with duplicates removed""" | ensure_iterable ( iterable )
key = hash if key is None else ensure_callable ( key )
def generator ( ) :
seen = set ( )
for elem in iterable :
k = key ( elem )
if k not in seen :
seen . add ( k )
yield elem
return generator ( ) |
def read_text_file ( filename , encoding = "utf-8" ) :
"""Reads a file under python3 with encoding ( default UTF - 8 ) .
Also works under python2 , without encoding .
Uses the EAFP ( https : / / docs . python . org / 2 / glossary . html # term - eafp )
principle .""" | try :
with open ( filename , 'r' , encoding ) as f :
r = f . read ( )
except TypeError :
with open ( filename , 'r' ) as f :
r = f . read ( )
return r |
def hum1_wei ( x , y , n = 24 ) :
t = y - 1.0j * x
cerf = 1 / sqrt ( pi ) * t / ( 0.5 + t ** 2 )
"""z = x + 1j * y
cerf = 1j * z / sqrt ( pi ) / ( z * * 2-0.5)""" | mask = abs ( x ) + y < 15.0
if any ( mask ) :
w24 = weideman ( x [ mask ] , y [ mask ] , n )
place ( cerf , mask , w24 )
return cerf . real , cerf . imag |
def _dict2schema ( dct ) :
"""Generate a ` marshmallow . Schema ` class given a dictionary of
` Fields < marshmallow . fields . Field > ` .""" | attrs = dct . copy ( )
if MARSHMALLOW_VERSION_INFO [ 0 ] < 3 :
class Meta ( object ) :
strict = True
attrs [ "Meta" ] = Meta
return type ( str ( "" ) , ( ma . Schema , ) , attrs ) |
def _modify_event ( self , event_name , method , func ) :
"""Wrapper to call a list ' s method from one of the events""" | if event_name not in self . ALL_EVENTS :
raise TypeError ( ( 'event_name ("%s") can only be one of the ' 'following: %s' ) % ( event_name , repr ( self . ALL_EVENTS ) ) )
if not isinstance ( func , collections . Callable ) :
raise TypeError ( ( 'func must be callable to be added as an ' 'observer.' ) )
getattr ... |
def aside_for ( cls , view_name ) :
"""A decorator to indicate a function is the aside view for the given view _ name .
Aside views should have a signature like :
@ XBlockAside . aside _ for ( ' student _ view ' )
def student _ aside ( self , block , context = None ) :
return Fragment ( . . . )""" | # pylint : disable = protected - access
def _decorator ( func ) : # pylint : disable = missing - docstring
if not hasattr ( func , '_aside_for' ) :
func . _aside_for = [ ]
func . _aside_for . append ( view_name )
# pylint : disable = protected - access
return func
return _decorator |
def post ( self , urls = None , ** overrides ) :
"""Sets the acceptable HTTP method to POST""" | if urls is not None :
overrides [ 'urls' ] = urls
return self . where ( accept = 'POST' , ** overrides ) |
def connection_checker ( self ) :
'''Run periodic reconnection checks''' | thread = ConnectionChecker ( self )
logger . info ( 'Starting connection-checker thread' )
thread . start ( )
try :
yield thread
finally :
logger . info ( 'Stopping connection-checker' )
thread . stop ( )
logger . info ( 'Joining connection-checker' )
thread . join ( ) |
def _make_nonce ( self ) :
'''Generate a unique ID for the request , 25 chars in length
Returns :
- str : Cryptographic nonce''' | chars = string . digits + string . ascii_letters
nonce = '' . join ( random . choice ( chars ) for i in range ( 25 ) )
if self . _logging :
utils . log ( 'nonce created: %s' % nonce )
return nonce |
def login ( self , email = None , password = None , remember = False ) :
"""Authenticate user and emit event .""" | from flask_login import login_user
user = self . first ( email = email )
if user is None :
events . login_failed_nonexistent_event . send ( )
return False
# check for account being locked
if user . is_locked ( ) :
raise x . AccountLocked ( locked_until = user . locked_until )
# check for email being confirm... |
def add_parameter ( self , ** kwargs ) :
'''Add the parameter to ` ` Parameters ` ` .
* * Arguments * *
The arguments are lumped into two groups : ` ` Parameters . add _ parameter ` `
and ` ` argparse . ArgumentParser . add _ argument ` ` . Parameters that are only
used by ` ` Parameters . add _ parameter `... | parameter_name = max ( kwargs [ 'options' ] , key = len ) . lstrip ( '-' )
if 'dest' in kwargs :
parameter_name = kwargs [ 'dest' ]
group = kwargs . pop ( 'group' , 'default' )
self . groups . add ( group )
parameter_name = '.' . join ( [ group , parameter_name ] ) . lstrip ( '.' ) . replace ( '-' , '_' )
logger . ... |
def bin ( y , bins ) :
"""bin interval / ratio data
Parameters
y : array
( n , q ) , values to bin
bins : array
( k , 1 ) , upper bounds of each bin ( monotonic )
Returns
b : array
( n , q ) , values of values between 0 and k - 1
Examples
> > > import numpy as np
> > > import mapclassify as mc... | if np . ndim ( y ) == 1 :
k = 1
n = np . shape ( y ) [ 0 ]
else :
n , k = np . shape ( y )
b = np . zeros ( ( n , k ) , dtype = 'int' )
i = len ( bins )
if type ( bins ) != list :
bins = bins . tolist ( )
binsc = copy . copy ( bins )
while binsc :
i -= 1
c = binsc . pop ( - 1 )
b [ np . nonz... |
def accept ( self , ** kws ) :
"""Accept a connection . The socket must be bound to an address and
listening for connections . The return value is a pair ( conn , address )
where conn is a new socket object usable to send and receive data on the
connection , and address is the address bound to the socket on t... | return yield_ ( Accept ( self , timeout = self . _timeout , ** kws ) ) |
def process_bounce ( message , notification ) :
"""Function to process a bounce notification""" | mail = message [ 'mail' ]
bounce = message [ 'bounce' ]
bounces = [ ]
for recipient in bounce [ 'bouncedRecipients' ] : # Create each bounce record . Add to a list for reference later .
bounces += [ Bounce . objects . create ( sns_topic = notification [ 'TopicArn' ] , sns_messageid = notification [ 'MessageId' ] , ... |
def get_ecf_props ( ep_id , ep_id_ns , rsvc_id = None , ep_ts = None ) :
"""Prepares the ECF properties
: param ep _ id : Endpoint ID
: param ep _ id _ ns : Namespace of the Endpoint ID
: param rsvc _ id : Remote service ID
: param ep _ ts : Timestamp of the endpoint
: return : A dictionary of ECF propert... | results = { }
if not ep_id :
raise ArgumentError ( "ep_id" , "ep_id must be a valid endpoint id" )
results [ ECF_ENDPOINT_ID ] = ep_id
if not ep_id_ns :
raise ArgumentError ( "ep_id_ns" , "ep_id_ns must be a valid namespace" )
results [ ECF_ENDPOINT_CONTAINERID_NAMESPACE ] = ep_id_ns
if not rsvc_id :
rsvc_i... |
def resample ( args ) :
"""% prog resample yellow - catfish - resample . txt medicago - resample . txt
Plot ALLMAPS performance across resampled real data .""" | p = OptionParser ( resample . __doc__ )
opts , args , iopts = p . set_image_options ( args , figsize = "8x4" , dpi = 300 )
if len ( args ) != 2 :
sys . exit ( not p . print_help ( ) )
dataA , dataB = args
fig = plt . figure ( 1 , ( iopts . w , iopts . h ) )
root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] )
A = fig . add_... |
def _bld_pnab_generic ( self , funcname , ** kwargs ) :
"""implement ' s a generic version of a non - attribute based pandas function""" | margs = { 'mtype' : pnab , 'kwargs' : kwargs }
setattr ( self , funcname , margs ) |
async def get_message ( self , ignore_subscribe_messages = False , timeout = 0 ) :
"""Get the next message if one is available , otherwise None .
If timeout is specified , the system will wait for ` timeout ` seconds
before returning . Timeout should be specified as a floating point
number .""" | response = await self . parse_response ( block = False , timeout = timeout )
if response :
return self . handle_message ( response , ignore_subscribe_messages )
return None |
def eth_sendTransaction ( self , from_ , to = None , gas = None , gas_price = None , value = None , data = None , nonce = None ) :
"""https : / / github . com / ethereum / wiki / wiki / JSON - RPC # eth _ sendtransaction
: param from _ : From account address
: type from _ : str
: param to : To account address... | obj = { }
obj [ 'from' ] = from_
if to is not None :
obj [ 'to' ] = to
if gas is not None :
obj [ 'gas' ] = hex ( gas )
if gas_price is not None :
obj [ 'gasPrice' ] = hex ( gas_price )
if value is not None :
obj [ 'value' ] = hex ( ether_to_wei ( value ) )
if data is not None :
obj [ 'data' ] = dat... |
def fill_wildcards ( self , field = None , value = 0 ) :
"""Update wildcards attribute .
This method update a wildcards considering the attributes of the
current instance .
Args :
field ( str ) : Name of the updated field .
value ( GenericType ) : New value used in the field .""" | if field in [ None , 'wildcards' ] or isinstance ( value , Pad ) :
return
default_value = getattr ( Match , field )
if isinstance ( default_value , IPAddress ) :
if field == 'nw_dst' :
shift = FlowWildCards . OFPFW_NW_DST_SHIFT
base_mask = FlowWildCards . OFPFW_NW_DST_MASK
else :
shi... |
def to_wider_model ( self , pre_layer_id , n_add ) :
"""Widen the last dimension of the output of the pre _ layer .
Args :
pre _ layer _ id : The ID of a convolutional layer or dense layer .
n _ add : The number of dimensions to add .""" | self . operation_history . append ( ( "to_wider_model" , pre_layer_id , n_add ) )
pre_layer = self . layer_list [ pre_layer_id ]
output_id = self . layer_id_to_output_node_ids [ pre_layer_id ] [ 0 ]
dim = layer_width ( pre_layer )
self . vis = { }
self . _search ( output_id , dim , dim , n_add )
# Update the tensor sha... |
def entry_from_resource ( resource , client , loggers ) :
"""Detect correct entry type from resource and instantiate .
: type resource : dict
: param resource : One entry resource from API response .
: type client : : class : ` ~ google . cloud . logging . client . Client `
: param client : Client that owns... | if "textPayload" in resource :
return TextEntry . from_api_repr ( resource , client , loggers )
if "jsonPayload" in resource :
return StructEntry . from_api_repr ( resource , client , loggers )
if "protoPayload" in resource :
return ProtobufEntry . from_api_repr ( resource , client , loggers )
return LogEnt... |
def write_to_output ( content , output = None , encoding = anytemplate . compat . ENCODING ) :
""": param content : Content string to write to
: param output : Output destination
: param encoding : Character set encoding of outputs""" | if anytemplate . compat . IS_PYTHON_3 and isinstance ( content , bytes ) :
content = str ( content , encoding )
if output and not output == '-' :
_write_to_filepath ( content , output )
elif anytemplate . compat . IS_PYTHON_3 :
print ( content )
else :
print ( content . encode ( encoding . lower ( ) ) ,... |
def _gti_dirint_gte_90_kt_prime ( aoi , solar_zenith , solar_azimuth , times , kt_prime ) :
"""Determine kt ' values to be used in GTI - DIRINT AOI > = 90 deg case .
See Marion 2015 Section 2.2.
For AOI > = 90 deg : average of the kt _ prime values for 65 < AOI < 80
in each day ' s morning and afternoon . Mor... | # kt _ prime values from DIRINT calculation for AOI < 90 case
# set the kt _ prime from sunrise to AOI = 90 to be equal to
# the kt _ prime for 65 < AOI < 80 during the morning .
# similar for the afternoon . repeat for every day .
aoi_gte_90 = aoi >= 90
aoi_65_80 = ( aoi > 65 ) & ( aoi < 80 )
zenith_lt_90 = solar_zeni... |
def get_redirect_url ( self , request , ** kwargs ) :
"""Return the URL redirect to . Keyword arguments from the
URL pattern match generating the redirect request
are provided as kwargs to this method .""" | if self . url :
url = self . url % kwargs
args = request . META . get ( 'QUERY_STRING' , '' )
if args and self . query_string :
url = "%s?%s" % ( url , args )
return url
else :
return None |
def score_for_in ( self , leaderboard_name , member ) :
'''Retrieve the score for a member in the named leaderboard .
@ param leaderboard _ name Name of the leaderboard .
@ param member [ String ] Member name .
@ return the score for a member in the leaderboard or + None + if the member is not in the leaderbo... | score = self . redis_connection . zscore ( leaderboard_name , member )
if score is not None :
score = float ( score )
return score |
def get_original_order_unique_ids ( id_array ) :
"""Get the unique id ' s of id _ array , in their original order of appearance .
Parameters
id _ array : 1D ndarray .
Should contain the ids that we want to extract the unique values from .
Returns
original _ order _ unique _ ids : 1D ndarray .
Contains t... | assert isinstance ( id_array , np . ndarray )
assert len ( id_array . shape ) == 1
# Get the indices of the unique IDs in their order of appearance
# Note the [ 1 ] is because the np . unique ( ) call will return both the sorted
# unique IDs and the indices
original_unique_id_indices = np . sort ( np . unique ( id_arra... |
def set_title ( self , msg ) :
"""Set first header line text""" | self . s . move ( 0 , 0 )
self . overwrite_line ( msg , curses . A_REVERSE ) |
def load_model ( location ) :
"""Load any Turi Create model that was previously saved .
This function assumes the model ( can be any model ) was previously saved in
Turi Create model format with model . save ( filename ) .
Parameters
location : string
Location of the model to load . Can be a local path or... | # Check if the location is a dir _ archive , if not , use glunpickler to load
# as pure python model
# If the location is a http location , skip the check , and directly proceed
# to load model as dir _ archive . This is because
# 1 ) exists ( ) does not work with http protocol , and
# 2 ) GLUnpickler does not support ... |
def set_neighbor_data ( self , neighbor_side , data , key , field ) :
"""Assign data from the ' key ' tile to the edge on the
neighboring tile which is on the ' neighbor _ side ' of the ' key ' tile .
The data is assigned to the ' field ' attribute of the neihboring tile ' s
edge .""" | i = self . keys [ key ]
found = False
sides = [ ]
if 'left' in neighbor_side :
if i % self . n_cols == 0 :
return None
i -= 1
sides . append ( 'right' )
found = True
if 'right' in neighbor_side :
if i % self . n_cols == self . n_cols - 1 :
return None
i += 1
sides . append ( ... |
def assess_itx_resistance ( job , gene_expression , univ_options , reports_options ) :
"""Assess the prevalence of the various genes in various cancer pathways and return a report in the txt
format .
: param toil . fileStore . FileID gene _ expression : fsID for the rsem gene expression file
: param dict univ... | work_dir = os . getcwd ( )
tumor_type = univ_options [ 'tumor_type' ]
# Get the input files
input_files = { 'rsem_quant.tsv' : gene_expression , 'itx_resistance.tsv.tar.gz' : reports_options [ 'itx_resistance_file' ] , 'immune_resistance_pathways.json.tar.gz' : reports_options [ 'immune_resistance_pathways_file' ] }
in... |
def _compute_fixed_point_ig ( T , v , max_iter , verbose , print_skip , is_approx_fp , * args , ** kwargs ) :
"""Implement the imitation game algorithm by McLennan and Tourky ( 2006)
for computing an approximate fixed point of ` T ` .
Parameters
is _ approx _ fp : callable
A callable with signature ` is _ a... | if verbose == 2 :
start_time = time . time ( )
_print_after_skip ( print_skip , it = None )
x_new = v
y_new = T ( x_new , * args , ** kwargs )
iterate = 1
converged = is_approx_fp ( x_new )
if converged or iterate >= max_iter :
if verbose == 2 :
error = np . max ( np . abs ( y_new - x_new ) )
... |
def resolve_rows ( rows ) :
"""Recursively iterate over lists of axes merging
them by their vertical overlap leaving a list
of rows .""" | merged_rows = [ ]
for row in rows :
overlap = False
for mrow in merged_rows :
if any ( axis_overlap ( ax1 , ax2 ) for ax1 in row for ax2 in mrow ) :
mrow += row
overlap = True
break
if not overlap :
merged_rows . append ( row )
if rows == merged_rows :
... |
def print_events ( events ) :
"""Prints out the event log for a user""" | columns = [ 'Date' , 'Type' , 'IP Address' , 'label' , 'username' ]
table = formatting . Table ( columns )
for event in events :
table . add_row ( [ event . get ( 'eventCreateDate' ) , event . get ( 'eventName' ) , event . get ( 'ipAddress' ) , event . get ( 'label' ) , event . get ( 'username' ) ] )
return table |
def is_valid_py_file ( path ) :
'''Checks whether the file can be read by the coverage module . This is especially
needed for . pyx files and . py files with syntax errors .''' | import os
is_valid = False
if os . path . isfile ( path ) and not os . path . splitext ( path ) [ 1 ] == '.pyx' :
try :
with open ( path , 'rb' ) as f :
compile ( f . read ( ) , path , 'exec' )
is_valid = True
except :
pass
return is_valid |
def set_context ( self , definition : Definition , explanation : str ) -> None :
"""Set the source code context for this error .""" | self . definition = definition
self . explanation = explanation |
def _gt_from_ge ( self , other ) :
"""Return a > b . Computed by @ total _ ordering from ( a > = b ) and ( a ! = b ) .""" | op_result = self . __ge__ ( other )
if op_result is NotImplemented :
return NotImplemented
return op_result and self != other |
def _unique ( list_of_dicts ) :
'''Returns an unique list of dictionaries given a list that may contain duplicates .''' | unique_list = [ ]
for ele in list_of_dicts :
if ele not in unique_list :
unique_list . append ( ele )
return unique_list |
def find ( self , * args , ** kwargs ) :
"""Run the pymongo find command against the default database and collection
and paginate the output to the screen .""" | # print ( f " database . collection : ' { self . database . name } . { self . collection . name } ' " )
self . print_cursor ( self . collection . find ( * args , ** kwargs ) ) |
def detect_changepoints ( points , min_time , data_processor = acc_difference ) :
"""Detects changepoints on points that have at least a specific duration
Args :
points ( : obj : ` Point ` )
min _ time ( float ) : Min time that a sub - segmented , bounded by two changepoints , must have
data _ processor ( f... | data = data_processor ( points )
changepoints = pelt ( normal_mean ( data , np . std ( data ) ) , len ( data ) )
changepoints . append ( len ( points ) - 1 )
result = [ ]
for start , end in pairwise ( changepoints ) :
time_diff = points [ end ] . time_difference ( points [ start ] )
if time_diff > min_time :
... |
def serve ( config ) :
"Serve the app with Gevent" | from gevent . pywsgi import WSGIServer
app = make_app ( config = config )
host = app . config . get ( "HOST" , '127.0.0.1' )
port = app . config . get ( "PORT" , 5000 )
http_server = WSGIServer ( ( host , port ) , app )
http_server . serve_forever ( ) |
def get_title ( src_name , src_type = None ) :
"""Normalizes a source name as a string to be used for viewer ' s title .""" | if src_type == 'tcp' :
return '{0}:{1}' . format ( * src_name )
return os . path . basename ( src_name ) |
def profile_remove ( name , ** kwargs ) :
"""Remove profile from the storage .""" | ctx = Context ( ** kwargs )
ctx . execute_action ( 'profile:remove' , ** { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , } ) |
def mouse_release_event ( self , event ) :
"""Forward mouse release events to the example""" | # Support left and right mouse button for now
if event . button ( ) not in [ 1 , 2 ] :
return
self . example . mouse_release_event ( event . x ( ) , event . y ( ) , event . button ( ) ) |
def datafeed ( self ) :
"""Return a new raw REST interface to feed resources
: rtype : : py : class : ` ns1 . rest . data . Feed `""" | import ns1 . rest . data
return ns1 . rest . data . Feed ( self . config ) |
def new_device ( device_json , abode ) :
"""Create new device object for the given type .""" | type_tag = device_json . get ( 'type_tag' )
if not type_tag :
raise AbodeException ( ( ERROR . UNABLE_TO_MAP_DEVICE ) )
generic_type = CONST . get_generic_type ( type_tag . lower ( ) )
device_json [ 'generic_type' ] = generic_type
if generic_type == CONST . TYPE_CONNECTIVITY or generic_type == CONST . TYPE_MOISTURE... |
def _multiplyThroughputs ( self ) :
'''Overrides base class in order to deal with opaque components .''' | index = 0
for component in self . components :
if component . throughput != None :
break
index += 1
return BaseObservationMode . _multiplyThroughputs ( self , index ) |
def build_transgenic_lines ( self ) :
"""init class | " transgenic _ line _ source _ name " : " stock _ number " a Class
add superClass | rdfs : subClassOf ilxtr : transgenicLine
add * order * | ilxtr : useObjectProperty ilxtr : < order >
add name | rdfs : label " name "
add def | definition : " description... | triples = [ ]
for cell_line in self . neuron_data :
for tl in cell_line [ 'donor' ] [ 'transgenic_lines' ] :
_id = tl [ 'stock_number' ] if tl [ 'stock_number' ] else tl [ 'id' ]
prefix = tl [ 'transgenic_line_source_name' ]
line_type = tl [ 'transgenic_line_type_name' ]
if prefix no... |
def match ( to_match , values , na_sentinel = - 1 ) :
"""Compute locations of to _ match into values
Parameters
to _ match : array - like
values to find positions of
values : array - like
Unique set of values
na _ sentinel : int , default - 1
Value to mark " not found "
Examples
Returns
match : ... | values = com . asarray_tuplesafe ( values )
htable , _ , values , dtype , ndtype = _get_hashtable_algo ( values )
to_match , _ , _ = _ensure_data ( to_match , dtype )
table = htable ( min ( len ( to_match ) , 1000000 ) )
table . map_locations ( values )
result = table . lookup ( to_match )
if na_sentinel != - 1 : # rep... |
def install_monitor ( self , mon ) :
"""Installs monitor on all executors""" | assert self . binded
self . _monitor = mon
for mod in self . _buckets . values ( ) :
mod . install_monitor ( mon ) |
def readACTIONRECORDs ( self ) :
"""Read zero or more button records ( zero - terminated )""" | out = [ ]
while 1 :
action = self . readACTIONRECORD ( )
if action :
out . append ( action )
else :
break
return out |
def subvol_delete ( self , path ) :
"""Delete a btrfs subvolume in the specified path
: param path : path to delete""" | args = { 'path' : path }
self . _subvol_chk . check ( args )
self . _client . sync ( 'btrfs.subvol_delete' , args ) |
def filter_connection_params ( queue_params ) :
"""Filters the queue params to keep only the connection related params .""" | CONNECTION_PARAMS = ( 'URL' , 'DB' , 'USE_REDIS_CACHE' , 'UNIX_SOCKET_PATH' , 'HOST' , 'PORT' , 'PASSWORD' , 'SENTINELS' , 'MASTER_NAME' , 'SOCKET_TIMEOUT' , 'SSL' , 'CONNECTION_KWARGS' , )
# return { p : v for p , v in queue _ params . items ( ) if p in CONNECTION _ PARAMS }
# Dict comprehension compatible with python... |
def add_mapped_chain_ids ( self , mapped_chains ) :
"""Add chains by ID into the mapped _ chains attribute
Args :
mapped _ chains ( str , list ) : Chain ID or list of IDs""" | mapped_chains = ssbio . utils . force_list ( mapped_chains )
for c in mapped_chains :
if c not in self . mapped_chains :
self . mapped_chains . append ( c )
log . debug ( '{}: added to list of mapped chains' . format ( c ) )
else :
log . debug ( '{}: chain already in list of mapped chain... |
def getStates ( self ) :
'''Calculates updated values of normalized market resources and permanent income level for each
agent . Uses pLvlNow , aNrmNow , PermShkNow , TranShkNow .
Parameters
None
Returns
None''' | pLvlPrev = self . pLvlNow
aNrmPrev = self . aNrmNow
RfreeNow = self . getRfree ( )
# Calculate new states : normalized market resources and permanent income level
self . pLvlNow = pLvlPrev * self . PermShkNow
# Updated permanent income level
self . PlvlAggNow = self . PlvlAggNow * self . PermShkAggNow
# Updated aggrega... |
def _get_next_date_from_partial_date ( partial_date ) :
"""Calculates the next date from the given partial date .
Args :
partial _ date ( inspire _ utils . date . PartialDate ) : The partial date whose next date should be calculated .
Returns :
PartialDate : The next date from the given partial date .""" | relativedelta_arg = 'years'
if partial_date . month :
relativedelta_arg = 'months'
if partial_date . day :
relativedelta_arg = 'days'
next_date = parse ( partial_date . dumps ( ) ) + relativedelta ( ** { relativedelta_arg : 1 } )
return PartialDate . from_parts ( next_date . year , next_date . month if partial_... |
def event_lookup_query ( self , id , ** kwargs ) :
"""Query the Yelp Event Lookup API .
documentation : https : / / www . yelp . com / developers / documentation / v3 / event
required parameters :
* id - event ID""" | if not id :
raise ValueError ( 'A valid event ID (parameter "id") must be provided.' )
return self . _query ( EVENT_LOOKUP_API_URL . format ( id ) , ** kwargs ) |
def get_all_for_bc_set_record ( self , id , ** kwargs ) :
"""Gets running Build Records for a specific Build Configuration Set Record .
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please define a ` callback ` function
to be invoked when receiving the respon... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . get_all_for_bc_set_record_with_http_info ( id , ** kwargs )
else :
( data ) = self . get_all_for_bc_set_record_with_http_info ( id , ** kwargs )
return data |
def _changeMs ( self , line ) :
"""Change the ms part in the string if needed .""" | # use the position of the last space instead
try :
last_space_pos = line . rindex ( ' ' )
except ValueError :
return line
else :
end_str = line [ last_space_pos : ]
new_string = line
if end_str [ - 2 : ] == 'ms' and int ( end_str [ : - 2 ] ) >= 1000 : # isolate the number of milliseconds
ms ... |
def presplit ( host , database , collection , shardkey , shardnumber = None , chunkspershard = 1 , verbose = False ) :
"""Presplit chunks for sharding .
Get information about the number of shards , then split chunks and
distribute over shards . Currently assumes shardkey to be hex string , for
example ObjectI... | con = Connection ( host )
namespace = '%s.%s' % ( database , collection )
# disable balancer
con [ 'config' ] [ 'settings' ] . update ( { '_id' : "balancer" } , { '$set' : { 'stopped' : True } } , upsert = True )
# enable sharding on database if not yet enabled
db_info = con [ 'config' ] [ 'databases' ] . find_one ( { ... |
def parse_sitelist ( sitelist ) :
"""Return list of Site instances from retrieved sitelist data""" | sites = [ ]
for site in sitelist [ "Locations" ] [ "Location" ] :
try :
ident = site [ "id" ]
name = site [ "name" ]
except KeyError :
ident = site [ "@id" ]
# Difference between loc - spec and text for some reason
name = site [ "@name" ]
if "latitude" in site :
... |
def add_chapter ( self , c ) :
"""Add a Chapter to your epub .
Args :
c ( Chapter ) : A Chapter object representing your chapter .
Raises :
TypeError : Raised if a Chapter object isn ' t supplied to this
method .""" | try :
assert type ( c ) == chapter . Chapter
except AssertionError :
raise TypeError ( 'chapter must be of type Chapter' )
chapter_file_output = os . path . join ( self . OEBPS_DIR , self . current_chapter_path )
c . _replace_images_in_chapter ( self . OEBPS_DIR )
c . write ( chapter_file_output )
self . _incre... |
def get_item_mdata ( ) :
"""Return default mdata map for Item""" | return { 'learning_objectives' : { 'element_label' : { 'text' : 'learning objectives' , 'languageTypeId' : str ( DEFAULT_LANGUAGE_TYPE ) , 'scriptTypeId' : str ( DEFAULT_SCRIPT_TYPE ) , 'formatTypeId' : str ( DEFAULT_FORMAT_TYPE ) , } , 'instructions' : { 'text' : 'accepts an osid.id.Id[] object' , 'languageTypeId' : s... |
def create_keyspace_network_topology ( name , dc_replication_map , durable_writes = True , connections = None ) :
"""Creates a keyspace with NetworkTopologyStrategy for replica placement
If the keyspace already exists , it will not be modified .
* * This function should be used with caution , especially in prod... | _create_keyspace ( name , durable_writes , 'NetworkTopologyStrategy' , dc_replication_map , connections = connections ) |
def multiloss ( losses , logging_namespace = "multiloss" , exclude_from_weighting = [ ] ) :
"""Create a loss from multiple losses my mixing them .
This multi - loss implementation is inspired by the Paper " Multi - Task Learning Using Uncertainty to Weight Losses
for Scene Geometry and Semantics " by Kendall , ... | with tf . variable_scope ( logging_namespace ) :
sum_loss = 0
for loss_name , loss in losses . items ( ) :
if loss_name not in exclude_from_weighting :
with tf . variable_scope ( loss_name ) as scope :
sum_loss += variance_corrected_loss ( loss )
else :
su... |
def _call ( self , x , out = None ) :
"""Apply operators to ` ` x ` ` and sum .""" | if out is None :
return self . prod_op ( x ) [ 0 ]
else :
wrapped_out = self . prod_op . range . element ( [ out ] , cast = False )
pspace_result = self . prod_op ( x , out = wrapped_out )
return pspace_result [ 0 ] |
def replace_cluster_role_binding ( self , name , body , ** kwargs ) :
"""replace the specified ClusterRoleBinding
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . replace _ cluster _ role _ binding ( name , bod... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . replace_cluster_role_binding_with_http_info ( name , body , ** kwargs )
else :
( data ) = self . replace_cluster_role_binding_with_http_info ( name , body , ** kwargs )
return data |
def get_term_and_background_counts ( self ) :
'''Returns
A pd . DataFrame consisting of unigram term counts of words occurring
in the TermDocumentMatrix and their corresponding background corpus
counts . The dataframe has two columns , corpus and background .
> > > corpus . get _ unigram _ corpus . get _ te... | background_df = self . _get_background_unigram_frequencies ( )
corpus_freq_df = pd . DataFrame ( { 'corpus' : self . term_category_freq_df . sum ( axis = 1 ) } )
corpus_unigram_freq = corpus_freq_df . loc [ [ w for w in corpus_freq_df . index if ' ' not in w ] ]
df = corpus_unigram_freq . join ( background_df , how = '... |
def channels_kick ( self , room_id , user_id , ** kwargs ) :
"""Removes a user from the channel .""" | return self . __call_api_post ( 'channels.kick' , roomId = room_id , userId = user_id , kwargs = kwargs ) |
def getReflexRuleConditionElement ( self , set_idx = 0 , row_idx = 0 , element = '' ) :
"""Returns the expected value saved in the action list object .
: set _ idx : it is an integer with the position of the reflex rules set
in the widget ' s list .
: row _ idx : is an integer with the numer of the row from t... | if isinstance ( set_idx , str ) :
set_idx = int ( set_idx )
if isinstance ( row_idx , str ) :
row_idx = int ( row_idx )
cond = self . getReflexRuleElement ( idx = set_idx , element = 'conditions' )
return cond [ row_idx ] . get ( element , '' ) |
def find_identifiers ( src ) :
"""Search for a valid identifier ( DOI , ISBN , arXiv , HAL ) in a given file .
. . note : :
This function returns the first matching identifier , that is the most
likely to be relevant for this file . However , it may fail and return an
identifier taken from the references or... | if src . endswith ( ".pdf" ) :
totext = subprocess . Popen ( [ "pdftotext" , src , "-" ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE , bufsize = 1 )
elif src . endswith ( ".djvu" ) :
totext = subprocess . Popen ( [ "djvutxt" , src ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE , bufsi... |
def limit_order ( self , direction , quantity , price , ** kwargs ) :
"""Shortcut for ` ` instrument . order ( . . . ) ` ` and accepts all of its
` optional parameters < # qtpylib . instrument . Instrument . order > ` _
: Parameters :
direction : string
Order Type ( BUY / SELL , EXIT / FLATTEN )
quantity ... | kwargs [ 'limit_price' ] = price
kwargs [ 'order_type' ] = "LIMIT"
self . parent . order ( direction . upper ( ) , self , quantity = quantity , ** kwargs ) |
def parse_a_hall ( self , hall ) :
"""Return names , hall numbers , and the washers / dryers available for a certain hall .
: param hall :
The ID of the hall to retrieve data for .
: type hall : int""" | if hall not in self . hall_to_link :
return None
# change to to empty json idk
page = requests . get ( self . hall_to_link [ hall ] , timeout = 60 )
soup = BeautifulSoup ( page . content , 'html.parser' )
soup . prettify ( )
washers = { "open" : 0 , "running" : 0 , "out_of_order" : 0 , "offline" : 0 , "time_rem... |
def unit_ball_L_inf ( shape , precondition = True ) :
"""A tensorflow variable tranfomed to be constrained in a L _ inf unit ball .
Note that this code also preconditions the gradient to go in the L _ inf
direction of steepest descent .
EXPERIMENTAL : Do not use for adverserial examples if you need to be conf... | x = tf . Variable ( tf . zeros ( shape ) )
if precondition :
return constrain_L_inf_precondition ( x )
else :
return constrain_L_inf ( x ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.