signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _parse_decorated_functions ( self , code ) :
"""Return URL rule , HTTP methods and docstring .""" | matches = re . finditer ( r"""
# @rest decorators
(?P<decorators>
(?:@rest\(.+?\)\n)+ # one or more @rest decorators inside
)
# docstring delimited by 3 double quotes
.+?"{3}(?P<docstring>.+?)"{3}
""" , ... |
def save_image ( self , image , local_filename ) :
"""Identical to : meth : ` dockermap . client . base . DockerClientWrapper . save _ image ` with additional logging .""" | self . push_log ( "Receiving tarball for image '{0}' and storing as '{1}'" . format ( image , local_filename ) )
super ( DockerFabricClient , self ) . save_image ( image , local_filename ) |
from typing import List
def can_sort_by_shifting ( nums : List [ int ] ) -> bool :
"""Function to determine if given list can be sorted in non - decreasing order by
performing circular shift operation on the list any number of times . Circular shift
to the right means moving all elements one position to the rig... | if len ( nums ) == 0 :
return True
sorted_nums = sorted ( nums )
min_index = nums . index ( min ( nums ) )
shifted_nums = nums [ min_index : ] + nums [ : min_index ]
return sorted_nums == shifted_nums |
def get_property ( host = None , admin_username = None , admin_password = None , property = None ) :
'''. . versionadded : : Fluorine
Return specific property
host
The chassis host .
admin _ username
The username used to access the chassis .
admin _ password
The password used to access the chassis .
... | if property is None :
raise SaltException ( 'No property specified!' )
ret = __execute_ret ( 'get \'{0}\'' . format ( property ) , host = host , admin_username = admin_username , admin_password = admin_password )
return ret |
def fetch ( clobber = False ) :
"""Downloads the IPHAS 3D dust map of Sale et al . ( 2014 ) .
Args :
clobber ( Optional [ bool ] ) : If ` ` True ` ` , any existing file will be
overwritten , even if it appears to match . If ` ` False ` ` ( the
default ) , ` ` fetch ( ) ` ` will attempt to determine if the d... | dest_dir = fname_pattern = os . path . join ( data_dir ( ) , 'iphas' )
url_pattern = 'http://www.iphas.org/data/extinction/A_samp_{:03d}.tar.gz'
fname_pattern = os . path . join ( dest_dir , 'A_samp_' ) + '{:03d}.tar.gz'
# Check if file already exists
if not clobber :
h5_fname = os . path . join ( dest_dir , 'iphas... |
def url_as_file ( url , ext = None ) :
"""Context manager that GETs a given ` url ` and provides it as a local file .
The file is in a closed state upon entering the context ,
and removed when leaving it , if still there .
To give the file name a specific extension , use ` ext ` ;
the extension can optional... | if ext :
ext = '.' + ext . strip ( '.' )
# normalize extension
url_hint = 'www-{}-' . format ( urlparse ( url ) . hostname or 'any' )
content = requests . get ( url ) . content
with tempfile . NamedTemporaryFile ( suffix = ext or '' , prefix = url_hint , delete = False ) as handle :
handle . write ( content... |
def make_chart ( self ) :
'''Returns
altair . Chart''' | task_df = self . get_task_df ( )
import altair as alt
chart = alt . Chart ( task_df ) . mark_bar ( ) . encode ( x = 'start' , x2 = 'end' , y = 'term' , )
return chart |
def _param_updated ( self , pk ) :
"""Callback with data for an updated parameter""" | if self . _useV2 :
var_id = struct . unpack ( '<H' , pk . data [ : 2 ] ) [ 0 ]
else :
var_id = pk . data [ 0 ]
element = self . toc . get_element_by_id ( var_id )
if element :
if self . _useV2 :
s = struct . unpack ( element . pytype , pk . data [ 2 : ] ) [ 0 ]
else :
s = struct . unpack... |
def update_path ( self , path ) :
"""There are EXTENDED messages which don ' t include any routers at
all , and any of the EXTENDED messages may have some arbitrary
flags in them . So far , they ' re all upper - case and none start
with $ luckily . The routers in the path should all be
LongName - style rout... | oldpath = self . path
self . path = [ ]
for p in path :
if p [ 0 ] != '$' :
break
# this will create a Router if we give it a router
# LongName that doesn ' t yet exist
router = self . router_container . router_from_id ( p )
self . path . append ( router )
# if the path grew , notify lis... |
def clean ( inst ) :
"""Routine to return FPMU data cleaned to the specified level
Parameters
inst : ( pysat . Instrument )
Instrument class object , whose attribute clean _ level is used to return
the desired level of data selectivity .
Returns
Void : ( NoneType )
data in inst is modified in - place ... | inst . data . replace ( - 999. , np . nan , inplace = True )
# Te
inst . data . replace ( - 9.9999998e+30 , np . nan , inplace = True )
# Ni
return None |
def set_configuration ( self , command ) :
"""Defines the current configuration of the logger . Can be used at any moment during runtime to modify the logger
behavior .
: param command : The command object that holds all the necessary information from the remote process .""" | self . permanent_progressbar_slots = command . permanent_progressbar_slots
self . redraw_frequency_millis = command . redraw_frequency_millis
self . console_level = command . console_level
self . task_millis_to_removal = command . task_millis_to_removal
self . console_format_strftime = command . console_format_strftime... |
def tokenize ( contents ) :
"""Parse a string called contents for CMake tokens .""" | tokens = _scan_for_tokens ( contents )
tokens = _compress_tokens ( tokens )
tokens = [ token for token in tokens if token . type != TokenType . Whitespace ]
return tokens |
def __entropy ( data ) :
'''Compute entropy of the flattened data set ( e . g . a density distribution ) .''' | # normalize and convert to float
data = data / float ( numpy . sum ( data ) )
# for each grey - value g with a probability p ( g ) = 0 , the entropy is defined as 0 , therefore we remove these values and also flatten the histogram
data = data [ numpy . nonzero ( data ) ]
# compute entropy
return - 1. * numpy . sum ( da... |
def onerror ( self , message , source , lineno , colno ) :
"""Called when an error occurs .""" | return ( message , source , lineno , colno ) |
def parmap ( f , X , nprocs = multiprocessing . cpu_count ( ) ) :
"""paralell map for multiprocessing""" | q_in = multiprocessing . Queue ( 1 )
q_out = multiprocessing . Queue ( )
proc = [ multiprocessing . Process ( target = fun , args = ( f , q_in , q_out ) ) for _ in range ( nprocs ) ]
for p in proc :
p . daemon = True
p . start ( )
sent = [ q_in . put ( ( i , x ) ) for i , x in enumerate ( X ) ]
[ q_in . put ( (... |
def show_news_line ( slug = None , limit = 3 , ** kwargs ) :
"""Отображает список последних новостей
Пример использования : :
{ % show _ news _ line ' news _ section _ slug ' 3 class = ' news - class ' % }
: param slug : символьный код категории новостей , если не задан фильтрация по категории не происходи... | if slug is None :
section = None
q = News . objects . published ( )
else :
section = Section . objects . get ( slug = slug )
q = News . objects . published ( ) . filter ( sections__slug = slug )
models = q . prefetch_related ( 'sections' ) . order_by ( '-date' , '-id' ) . all ( ) [ : limit ]
return { 'm... |
def is_website ( url ) :
"""Check if given url string is a website .
Usage : :
> > > is _ website ( " http : / / www . domain . com " )
True
> > > is _ website ( " domain . com " )
False
: param data : Data to check .
: type data : unicode
: return : Is website .
: rtype : bool""" | if re . match ( r"(http|ftp|https)://([\w\-\.]+)/?" , url ) :
LOGGER . debug ( "> {0}' is matched as website." . format ( url ) )
return True
else :
LOGGER . debug ( "> {0}' is not matched as website." . format ( url ) )
return False |
def to_pickle ( self , filename ) :
"""Save Camera to a pickle file , given a filename .""" | with open ( filename , 'wb' ) as f :
pickle . dump ( self , f ) |
def _provision_network ( self , port_id , net_uuid , network_type , physical_network , segmentation_id ) :
"""Provision the network with the received information .""" | LOG . info ( "Provisioning network %s" , net_uuid )
vswitch_name = self . _get_vswitch_name ( network_type , physical_network )
if network_type == h_constant . TYPE_VLAN : # Nothing to do
pass
elif network_type == h_constant . TYPE_FLAT : # Nothing to do
pass
elif network_type == h_constant . TYPE_LOCAL : # TOD... |
def gather ( self , futures , consume_exceptions = True ) :
"""This returns a Future that waits for all the Futures in the list
` ` futures ` `
: param futures : a list of Futures ( or coroutines ? )
: param consume _ exceptions : if True , any errors are eaten and
returned in the result list .""" | # from the asyncio docs : " If return _ exceptions is True , exceptions
# in the tasks are treated the same as successful results , and
# gathered in the result list ; otherwise , the first raised
# exception will be immediately propagated to the returned
# future . "
return asyncio . gather ( * futures , return_except... |
def create_user ( self , data ) :
"""Create a User .""" | # http : / / teampasswordmanager . com / docs / api - users / # create _ user
log . info ( 'Create user with %s' % data )
NewID = self . post ( 'users.json' , data ) . get ( 'id' )
log . info ( 'User has been created with ID %s' % NewID )
return NewID |
def run ( self ) :
'''Execute a single step and return results . The result for batch mode is the
input , output etc returned as alias , and for interactive mode is the return value
of the last expression .''' | # return value of the last executed statement
self . last_res = None
self . start_time = time . time ( )
self . completed = defaultdict ( int )
# prepare environments , namely variables that can be used by the step
# * step _ name : name of the step , can be used by step process to determine
# actions dynamically .
env... |
def license_loader ( lic_dir = LIC_DIR ) :
"""Loads licenses from the given directory .""" | lics = [ ]
for ln in os . listdir ( lic_dir ) :
lp = os . path . join ( lic_dir , ln )
with open ( lp ) as lf :
txt = lf . read ( )
lic = License ( txt )
lics . append ( lic )
return lics |
def _format_batch_statuses ( statuses , batch_ids , tracker ) :
"""Takes a statuses dict and formats it for transmission with Protobuf and
ZMQ .
Args :
statuses ( dict of int ) : Dict with batch ids as the key , status as value
batch _ ids ( list of str ) : The batch ids in their original order
tracker ( ... | proto_statuses = [ ]
for batch_id in batch_ids :
if statuses [ batch_id ] == client_batch_submit_pb2 . ClientBatchStatus . INVALID :
invalid_txns = tracker . get_invalid_txn_info ( batch_id )
for txn_info in invalid_txns :
try :
txn_info [ 'transaction_id' ] = txn_info . ... |
def log_summary ( self ) :
"""Log a summary of all the participants ' status codes .""" | participants = Participant . query . with_entities ( Participant . status ) . all ( )
counts = Counter ( [ p . status for p in participants ] )
sorted_counts = sorted ( counts . items ( ) , key = itemgetter ( 0 ) )
self . log ( "Status summary: {}" . format ( str ( sorted_counts ) ) )
return sorted_counts |
def get_from_string ( cls , string_condition ) :
"""Convert string value obtained from k8s API to PodCondition enum value
: param string _ condition : str , condition value from Kubernetes API
: return : PodCondition""" | if string_condition == 'PodScheduled' :
return cls . SCHEDULED
elif string_condition == 'Ready' :
return cls . READY
elif string_condition == 'Initialized' :
return cls . INITIALIZED
elif string_condition == 'Unschedulable' :
return cls . UNSCHEDULABLE
elif string_condition == 'ContainersReady' :
re... |
def nlmsg_find_attr ( nlh , hdrlen , attrtype ) :
"""Find a specific attribute in a Netlink message .
https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / msg . c # L231
Positional arguments :
nlh - - Netlink message header ( nlmsghdr class instance ) .
hdrlen - - length of family specifi... | return nla_find ( nlmsg_attrdata ( nlh , hdrlen ) , nlmsg_attrlen ( nlh , hdrlen ) , attrtype ) |
def get_block ( block_id , api_code = None ) :
"""Get a single block based on a block hash .
: param str block _ id : block hash to look up
: param str api _ code : Blockchain . info API code ( optional )
: return : an instance of : class : ` Block ` class""" | resource = 'rawblock/' + block_id
if api_code is not None :
resource += '?api_code=' + api_code
response = util . call_api ( resource )
json_response = json . loads ( response )
return Block ( json_response ) |
def plot_imag ( fignum , Bimag , Mimag , s ) :
"""function to plot d ( Delta M ) / dB curves""" | plt . figure ( num = fignum )
plt . clf ( )
if not isServer :
plt . figtext ( .02 , .01 , version_num )
plt . plot ( Bimag , Mimag , 'r' )
plt . xlabel ( 'B (T)' )
plt . ylabel ( 'M/Ms' )
plt . axvline ( 0 , color = 'k' )
plt . title ( s ) |
def get_certificates_v1 ( self ) :
"""Return a list of : class : ` asn1crypto . x509 . Certificate ` which are found
in the META - INF folder ( v1 signing ) .
Note that we simply extract all certificates regardless of the signer .
Therefore this is just a list of all certificates found in all signers .""" | certs = [ ]
for x in self . get_signature_names ( ) :
certs . append ( x509 . Certificate . load ( self . get_certificate_der ( x ) ) )
return certs |
def resetSession ( self , username = None , password = None , verify = True ) :
"""resets the session""" | self . disconnectSession ( )
self . session = AikidoSession ( username , password , verify ) |
def from_args ( cls , args , project_profile_name = None ) :
"""Given the raw profiles as read from disk and the name of the desired
profile if specified , return the profile component of the runtime
config .
: param args argparse . Namespace : The arguments as parsed from the cli .
: param project _ profil... | cli_vars = parse_cli_vars ( getattr ( args , 'vars' , '{}' ) )
threads_override = getattr ( args , 'threads' , None )
target_override = getattr ( args , 'target' , None )
raw_profiles = read_profile ( args . profiles_dir )
profile_name = cls . pick_profile_name ( args . profile , project_profile_name )
return cls . fro... |
def ftdi_to_clkbits ( baudrate ) : # from libftdi
"""10,27 = > divisor = 10000 , rate = 300
88,13 = > divisor = 5000 , rate = 600
C4,09 = > divisor = 2500 , rate = 1200
E2,04 = > divisor = 1250 , rate = 2,400
71,02 = > divisor = 625 , rate = 4,800
38,41 = > divisor = 312.5 , rate = 9,600
D0,80 = > divis... | clk = 48000000
clk_div = 16
frac_code = [ 0 , 3 , 2 , 4 , 1 , 5 , 6 , 7 ]
actual_baud = 0
if baudrate >= clk / clk_div :
encoded_divisor = 0
actual_baud = ( clk // clk_div )
elif baudrate >= clk / ( clk_div + clk_div / 2 ) :
encoded_divisor = 1
actual_baud = clk // ( clk_div + clk_div // 2 )
elif baudra... |
def list_alarms ( self , entity , limit = None , marker = None , return_next = False ) :
"""Returns a list of all the alarms created on the specified entity .""" | return entity . list_alarms ( limit = limit , marker = marker , return_next = return_next ) |
def deserialize ( self , payload , obj_type ) : # type : ( str , Union [ T , str ] ) - > Any
"""Deserializes payload into an instance of provided ` ` obj _ type ` ` .
The ` ` obj _ type ` ` parameter can be a primitive type , a generic
model object or a list / dict of model objects .
The list or dict object t... | if payload is None :
return None
try :
payload = json . loads ( payload )
except Exception :
raise SerializationException ( "Couldn't parse response body: {}" . format ( payload ) )
return self . __deserialize ( payload , obj_type ) |
def _get_pk ( self ) :
"""Override the default _ get _ pk method to retrieve the real pk value if we
have a SingleValueField or a RedisModel instead of a real PK value""" | pk = super ( ExtendedCollectionManager , self ) . _get_pk ( )
if pk is not None and isinstance ( pk , RawFilter ) : # We have a RedisModel and we want its pk , or a RedisField
# ( single value ) and we want its value
if isinstance ( pk . value , RedisModel ) :
pk = pk . value . pk . get ( )
elif isinsta... |
def reset_cmd_timeout ( self ) :
"""Reset timeout for command execution .""" | if self . _cmd_timeout :
self . _cmd_timeout . cancel ( )
self . _cmd_timeout = self . loop . call_later ( self . client . timeout , self . transport . close ) |
def add_cidr_rules ( self , rules ) :
"""Add cidr rules to security group via boto .
Args :
rules ( list ) : Allowed Security Group ports and protocols .
Returns :
True : Upon successful completion .
Raises :
SpinnakerSecurityGroupError : boto3 call failed to add CIDR block to
Security Group .""" | session = boto3 . session . Session ( profile_name = self . env , region_name = self . region )
client = session . client ( 'ec2' )
group_id = get_security_group_id ( self . app_name , self . env , self . region )
for rule in rules :
data = { 'DryRun' : False , 'GroupId' : group_id , 'IpPermissions' : [ { 'IpProtoc... |
def get_process ( cmd ) :
"""Get a command process .""" | if sys . platform . startswith ( 'win' ) :
startupinfo = subprocess . STARTUPINFO ( )
startupinfo . dwFlags |= subprocess . STARTF_USESHOWWINDOW
process = subprocess . Popen ( cmd , startupinfo = startupinfo , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , stdin = subprocess . PIPE , shell = Fa... |
def get_module ( self , name , folder = None ) :
"""Returns a ` PyObject ` if the module was found .""" | # check if this is a builtin module
pymod = self . pycore . builtin_module ( name )
if pymod is not None :
return pymod
module = self . find_module ( name , folder )
if module is None :
raise ModuleNotFoundError ( 'Module %s not found' % name )
return self . pycore . resource_to_pyobject ( module ) |
def lemmatize ( text_string ) :
'''Returns base from of text _ string using NLTK ' s WordNetLemmatizer as type str .
Keyword argument :
- text _ string : string instance
Exceptions raised :
- InputError : occurs should a non - string argument be passed''' | if text_string is None or text_string == "" :
return ""
elif isinstance ( text_string , str ) :
return LEMMATIZER . lemmatize ( text_string )
else :
raise InputError ( "string not passed as primary argument" ) |
def add_init_script ( self , file , name ) :
"""Add this file to the init . d directory""" | f_path = os . path . join ( "/etc/init.d" , name )
f = open ( f_path , "w" )
f . write ( file )
f . close ( )
os . chmod ( f_path , stat . S_IREAD | stat . S_IWRITE | stat . S_IEXEC )
self . run ( "/usr/sbin/update-rc.d %s defaults" % name ) |
def map_prop_value_as_index ( prp , lst ) :
"""Returns the given prop of each item in the list
: param prp :
: param lst :
: return :""" | return from_pairs ( map ( lambda item : ( prop ( prp , item ) , item ) , lst ) ) |
def Nu_Mokry ( Re , Pr , rho_w = None , rho_b = None ) :
r'''Calculates internal convection Nusselt number for turbulent vertical
upward flow in a pipe under supercritical conditions according to [ 1 ] _ ,
and reviewed in [ 2 ] _ .
. . math : :
Nu _ b = 0.0061 Re _ b ^ { 0.904 } \ bar { Pr } _ b ^ { 0.684} ... | Nu = 0.0061 * Re ** 0.904 * Pr ** 0.684
if rho_w and rho_b :
Nu *= ( rho_w / rho_b ) ** 0.564
return Nu |
def uniq ( pipe ) :
'''this works like bash ' s uniq command where the generator only iterates
if the next value is not the previous''' | pipe = iter ( pipe )
previous = next ( pipe )
yield previous
for i in pipe :
if i is not previous :
previous = i
yield i |
def ensure_has_same_campaigns ( self ) :
"""Ensure that the 2 campaigns to merge have been generated
from the same campaign . yaml""" | lhs_yaml = osp . join ( self . lhs , 'campaign.yaml' )
rhs_yaml = osp . join ( self . rhs , 'campaign.yaml' )
assert osp . isfile ( lhs_yaml )
assert osp . isfile ( rhs_yaml )
assert filecmp . cmp ( lhs_yaml , rhs_yaml ) |
def _group_flat_tags ( tag , tags ) :
"""Extract tags sharing the same name as the provided tag . Used to collect
options for radio and checkbox inputs .
: param Tag tag : BeautifulSoup tag
: param list tags : List of tags
: return : List of matching tags""" | grouped = [ tag ]
name = tag . get ( 'name' , '' ) . lower ( )
while tags and tags [ 0 ] . get ( 'name' , '' ) . lower ( ) == name :
grouped . append ( tags . pop ( 0 ) )
return grouped |
def rm_incomplete_des_asc ( des_mask , asc_mask ) :
'''Remove descents - ascents that have no corresponding ascent - descent
Args
des _ mask : ndarray
Boolean mask of descents in the depth data
asc _ mask : ndarray
Boolean mask of ascents in the depth data
Returns
des _ mask : ndarray
Boolean mask o... | from . import utils
# Get start / stop indices for descents and ascents
des_start , des_stop = utils . contiguous_regions ( des_mask )
asc_start , asc_stop = utils . contiguous_regions ( asc_mask )
des_mask = utils . rm_regions ( des_mask , asc_mask , des_start , des_stop )
asc_mask = utils . rm_regions ( asc_mask , de... |
def statichttp ( container = None ) :
"wrap a WSGI - style function to a HTTPRequest event handler" | def decorator ( func ) :
@ functools . wraps ( func )
def handler ( event ) :
return _handler ( container , event , func )
if hasattr ( func , '__self__' ) :
handler . __self__ = func . __self__
return handler
return decorator |
def get_keys_from_shelve ( file_name , file_location ) :
"""Function to retreive all keys in a shelve
Args :
file _ name : Shelve storage file name
file _ location : The location of the file , derive from the os module
Returns :
a list of the keys""" | temp_list = list ( )
file = __os . path . join ( file_location , file_name )
shelve_store = __shelve . open ( file )
for key in shelve_store :
temp_list . append ( key )
shelve_store . close ( )
return temp_list |
def run_job ( self , job_id , array_id = None ) :
"""This function is called to run a job ( e . g . in the grid ) with the given id and the given array index if applicable .""" | # set the job ' s status in the database
try : # get the job from the database
self . lock ( )
jobs = self . get_jobs ( ( job_id , ) )
if not len ( jobs ) : # it seems that the job has been deleted in the meanwhile
return
job = jobs [ 0 ]
# get the machine name we are executing on ; this mig... |
def arbiter ( ** params ) :
'''Obtain the ` ` arbiter ` ` .
It returns the arbiter instance only if we are on the arbiter
context domain , otherwise it returns nothing .''' | arbiter = get_actor ( )
if arbiter is None : # Create the arbiter
return set_actor ( _spawn_actor ( 'arbiter' , None , ** params ) )
elif arbiter . is_arbiter ( ) :
return arbiter |
def getdoc ( obj ) :
"""Get object docstring
: rtype : str""" | inspect_got_doc = inspect . getdoc ( obj )
if inspect_got_doc in ( object . __init__ . __doc__ , object . __doc__ ) :
return ''
# We never want this builtin stuff
return ( inspect_got_doc or '' ) . strip ( ) |
def resources_with_perms ( cls , instance , perms , resource_ids = None , resource_types = None , db_session = None ) :
"""returns all resources that user has perms for
( note that at least one perm needs to be met )
: param instance :
: param perms :
: param resource _ ids : restricts the search to specifi... | # owned entities have ALL permissions so we return those resources too
# even without explict perms set
# TODO : implement admin superrule perm - maybe return all apps
db_session = get_db_session ( db_session , instance )
query = db_session . query ( cls . models_proxy . Resource ) . distinct ( )
group_ids = [ gr . id ... |
def find_globals_and_nonlocals ( node , globs , nonlocals , code , version ) :
"""search a node of parse tree to find variable names that need a
either ' global ' or ' nonlocal ' statements added .""" | for n in node :
if isinstance ( n , SyntaxTree ) :
globs , nonlocals = find_globals_and_nonlocals ( n , globs , nonlocals , code , version )
elif n . kind in read_global_ops :
globs . add ( n . pattr )
elif ( version >= 3.0 and n . kind in nonglobal_ops and n . pattr in code . co_freevars an... |
def on_task_init ( self , task_id , task ) :
"""Called before every task .""" | try :
is_eager = task . request . is_eager
except AttributeError :
is_eager = False
if not is_eager :
self . close_database ( ) |
def get_asset_notification_session_for_repository ( self , asset_receiver , repository_id , proxy ) :
"""Gets the asset notification session for the given repository .
arg : asset _ receiver ( osid . repository . AssetReceiver ) : the
notification callback
arg : repository _ id ( osid . id . Id ) : the Id of ... | if not repository_id or not asset_receiver :
raise NullArgument ( )
if not self . supports_asset_lookup ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise OperationFailed ( 'import error' )
proxy = self . _convert_proxy ( proxy )
try :
session = sessions . AssetAdm... |
def make_entry_point ( patches , original_entry_point ) :
"""Use this to make a console _ script entry point for your application
which applies patches .
: param patches : iterable of pymonkey patches to apply . Ex : ( ' my - patch , )
: param original _ entry _ point : Such as ' pip '""" | def entry ( argv = None ) :
argv = argv if argv is not None else sys . argv [ 1 : ]
return main ( tuple ( patches ) + ( '--' , original_entry_point ) + tuple ( argv ) )
return entry |
def set_pointlist ( self , pointlist ) :
"""Overwrite pointlist .
Parameters
pointlist : a list of strokes ; each stroke is a list of points
The inner lists represent strokes . Every stroke consists of points .
Every point is a dictinary with ' x ' , ' y ' , ' time ' .""" | assert type ( pointlist ) is list , "pointlist is not of type list, but %r" % type ( pointlist )
assert len ( pointlist ) >= 1 , "The pointlist of formula_id %i is %s" % ( self . formula_id , self . get_pointlist ( ) )
self . raw_data_json = json . dumps ( pointlist ) |
def subscribe ( self , connection , destination ) :
"""Subscribes a connection to the specified topic destination .
@ param connection : The client connection to subscribe .
@ type connection : L { coilmq . server . StompConnection }
@ param destination : The topic destination ( e . g . ' / topic / foo ' )
... | self . log . debug ( "Subscribing %s to %s" % ( connection , destination ) )
self . _topics [ destination ] . add ( connection ) |
def fatal ( callingClass , astr_key , astr_extraMsg = "" ) :
'''Convenience dispatcher to the error _ exit ( ) method .
Will raise " fatal " error , i . e . terminate script .''' | b_exitToOS = True
report ( callingClass , astr_key , b_exitToOS , astr_extraMsg ) |
def to_shcoeffs ( self , nmax = None , normalization = '4pi' , csphase = 1 ) :
"""Return the spherical harmonic coefficients using the first n Slepian
coefficients .
Usage
s = x . to _ shcoeffs ( [ nmax ] )
Returns
s : SHCoeffs class instance
The spherical harmonic coefficients obtained from using the f... | if type ( normalization ) != str :
raise ValueError ( 'normalization must be a string. ' + 'Input type was {:s}' . format ( str ( type ( normalization ) ) ) )
if normalization . lower ( ) not in set ( [ '4pi' , 'ortho' , 'schmidt' ] ) :
raise ValueError ( "normalization must be '4pi', 'ortho' " + "or 'schmidt'.... |
def is_defined ( self , objtxt , force_import = False ) :
"""Return True if object is defined""" | return isdefined ( objtxt , force_import = force_import , namespace = self . locals ) |
def sanity_check ( args ) :
"""Verify if the work folder is a django app .
A valid django app always must have a models . py file
: return : None""" | if not os . path . isfile ( os . path . join ( args [ 'django_application_folder' ] , 'models.py' ) ) :
print ( "django_application_folder is not a Django application folder" )
sys . exit ( 1 ) |
def factorized_gaussian_noise ( in_features , out_features , device ) :
"""Factorised ( cheaper ) gaussian noise from " Noisy Networks for Exploration "
by Meire Fortunato , Mohammad Gheshlaghi Azar , Bilal Piot and others""" | in_noise = scaled_noise ( in_features , device = device )
out_noise = scaled_noise ( out_features , device = device )
return out_noise . ger ( in_noise ) , out_noise |
def absent ( profile = 'pagerduty' , subdomain = None , api_key = None , ** kwargs ) :
'''Ensure a pagerduty service does not exist .
Name can be the service name or pagerduty service id .''' | r = __salt__ [ 'pagerduty_util.resource_absent' ] ( 'services' , [ 'name' , 'id' ] , profile , subdomain , api_key , ** kwargs )
return r |
def check_availability ( self , isos ) :
'''This routine checks if the requested set of isotopes is
available in the dataset .
Parameters
isos : list
set of isotopes in format [ ' Si - 28 ' , ' Si - 30 ' ] .
Returns
list
[ index , delta _ b , ratio _ b ] .
index : where is it .
delta _ b : is it a... | # make names
iso1name = iso_name_converter ( isos [ 0 ] )
iso2name = iso_name_converter ( isos [ 1 ] )
ratio = iso1name + '/' + iso2name
ratio_inv = iso2name + '/' + iso1name
delta = 'd(' + iso1name + '/' + iso2name + ')'
delta_inv = 'd(' + iso2name + '/' + iso1name + ')'
index = - 1
# search for data entry
try :
i... |
def replace_namespaced_ingress ( self , name , namespace , body , ** kwargs ) :
"""replace the specified Ingress
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . replace _ namespaced _ ingress ( name , namespac... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . replace_namespaced_ingress_with_http_info ( name , namespace , body , ** kwargs )
else :
( data ) = self . replace_namespaced_ingress_with_http_info ( name , namespace , body , ** kwargs )
return data |
def fetch_contributing_projects ( self , ** kwargs ) :
"""List projects as contributor
Fetch projects that the currently authenticated user has access to because he or she is a contributor .
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please define a ` call... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . fetch_contributing_projects_with_http_info ( ** kwargs )
else :
( data ) = self . fetch_contributing_projects_with_http_info ( ** kwargs )
return data |
def body ( self ) :
"""Seralizes and returns the response body .
On subsequent access , returns the cached value .""" | if self . _body is None :
raw_body = self . _raw_body
if self . _body_writer is None :
self . _body = raw_body ( ) if callable ( raw_body ) else raw_body
else :
self . _body = self . _body_writer ( raw_body )
return self . _body |
def _find_bracket_position ( self , text , bracket_left , bracket_right , pos_quote ) :
"""Return the start and end position of pairs of brackets .
https : / / stackoverflow . com / questions / 29991917/
indices - of - matching - parentheses - in - python""" | pos = { }
pstack = [ ]
for idx , character in enumerate ( text ) :
if character == bracket_left and not self . is_char_in_pairs ( idx , pos_quote ) :
pstack . append ( idx )
elif character == bracket_right and not self . is_char_in_pairs ( idx , pos_quote ) :
if len ( pstack ) == 0 :
... |
def main ( ) :
"""Entry point for gns3 - converter""" | arg_parse = setup_argparse ( )
args = arg_parse . parse_args ( )
if not args . quiet :
print ( 'GNS3 Topology Converter' )
if args . debug :
logging_level = logging . DEBUG
else :
logging_level = logging . WARNING
logging . basicConfig ( level = logging_level , format = LOG_MSG_FMT , datefmt = LOG_DATE_FMT ... |
def _raise_unrecoverable_error_client ( self , exception ) :
"""Raises an exceptions . ClientError with a message telling that the error probably comes from the client
configuration .
: param exception : Exception that caused the ClientError
: type exception : Exception
: raise exceptions . ClientError""" | message = ( 'There was an unrecoverable error during the HTTP request which is probably related to your ' 'configuration. Please verify `' + self . DEPENDENCY + '` library configuration and update it. If the ' 'issue persists, do not hesitate to contact us with the following information: `' + repr ( exception ) + '`.' ... |
def loads ( self , content , ** options ) :
"""Load config from given string ' content ' after some checks .
: param content : Config file content
: param options :
options will be passed to backend specific loading functions .
please note that options have to be sanitized w /
: func : ` anyconfig . utils... | container = self . _container_factory ( ** options )
if not content or content is None :
return container ( )
options = self . _load_options ( container , ** options )
return self . load_from_string ( content , container , ** options ) |
def get_port_range ( port_def ) :
'''Given a port number or range , return a start and end to that range . Port
ranges are defined as a string containing two numbers separated by a dash
( e . g . ' 4505-4506 ' ) .
A ValueError will be raised if bad input is provided .''' | if isinstance ( port_def , six . integer_types ) : # Single integer , start / end of range is the same
return port_def , port_def
try :
comps = [ int ( x ) for x in split ( port_def , '-' ) ]
if len ( comps ) == 1 :
range_start = range_end = comps [ 0 ]
else :
range_start , range_end = c... |
def optOut ( self , playback = None , library = None ) :
"""Opt in or out of sharing stuff with plex .
See : https : / / www . plex . tv / about / privacy - legal /""" | params = { }
if playback is not None :
params [ 'optOutPlayback' ] = int ( playback )
if library is not None :
params [ 'optOutLibraryStats' ] = int ( library )
url = 'https://plex.tv/api/v2/user/privacy'
return self . query ( url , method = self . _session . put , data = params ) |
def send_photo ( self , photo : str , caption : str = None , reply : Message = None , on_success : callable = None , reply_markup : botapi . ReplyMarkup = None ) :
"""Send photo to this peer .
: param photo : File path to photo to send .
: param caption : Caption for photo
: param reply : Message object or me... | self . twx . send_photo ( peer = self , photo = photo , caption = caption , reply = reply , reply_markup = reply_markup , on_success = on_success ) |
def chained ( self , text = None , fore = None , back = None , style = None ) :
"""Called by the various ' color ' methods to colorize a single string .
The RESET _ ALL code is appended to the string unless text is empty .
Raises ValueError on invalid color names .
Arguments :
text : String to colorize , or... | self . data = '' . join ( ( self . data , self . color ( text = text , fore = fore , back = back , style = style ) , ) )
return self |
def fit_mle ( self , init_vals , print_res = True , method = "BFGS" , loss_tol = 1e-06 , gradient_tol = 1e-06 , maxiter = 1000 , ridge = None , constrained_pos = None , just_point = False , ** kwargs ) :
"""Parameters
init _ vals : 1D ndarray .
The initial values to start the optimization process with . There
... | # Check integrity of passed arguments
kwargs_to_be_ignored = [ "init_shapes" , "init_intercepts" , "init_coefs" ]
if any ( [ x in kwargs for x in kwargs_to_be_ignored ] ) :
msg = "MNL model does not use of any of the following kwargs:\n{}"
msg_2 = "Remove such kwargs and pass a single init_vals argument"
ra... |
def run_in_thread_pool ( self , pool_size = None , func = None , * args ) :
"""If ` kwargs ` needed , try like this : func = lambda : foo ( * args , * * kwargs )""" | executor = Pool ( pool_size )
return self . loop . run_in_executor ( executor , func , * args ) |
async def login ( cls , url , * , username = None , password = None , insecure = False ) :
"""Make an ` Origin ` by logging - in with a username and password .
: return : A tuple of ` ` profile ` ` and ` ` origin ` ` , where the former is an
unsaved ` Profile ` instance , and the latter is an ` Origin ` instanc... | profile , session = await bones . SessionAPI . login ( url = url , username = username , password = password , insecure = insecure )
return profile , cls ( session ) |
def calcPunkProp ( sNow ) :
'''Calculates the proportion of punks in the population , given data from each type .
Parameters
pNow : [ np . array ]
List of arrays of binary data , representing the fashion choice of each
agent in each type of this market ( 0 = jock , 1 = punk ) .
pop _ size : [ int ]
List... | sNowX = np . asarray ( sNow ) . flatten ( )
pNow = np . mean ( sNowX )
return FashionMarketInfo ( pNow ) |
def soft_target_update ( self ) :
"""Soft update model parameters :
. . math : :
\\ theta _ target = \\ tau \\ times \\ theta _ local + ( 1 - \\ tau ) \\ times \\ theta _ target ,
with \\ tau \\ ll 1
See https : / / arxiv . org / pdf / 1509.02971 . pdf""" | for target_param , local_param in zip ( self . target . parameters ( ) , self . local . parameters ( ) ) :
target_param . data . copy_ ( self . tau * local_param . data + ( 1.0 - self . tau ) * target_param . data ) |
def update_ar_listing_catalog ( portal ) :
"""Add Indexes / Metadata to bika _ catalog _ analysisrequest _ listing""" | cat_id = CATALOG_ANALYSIS_REQUEST_LISTING
catalog = api . get_tool ( cat_id )
logger . info ( "Updating Indexes/Metadata of Catalog '{}'" . format ( cat_id ) )
indexes_to_add = [ # name , attribute , metatype
( "getClientID" , "getClientID" , "FieldIndex" ) , ( "is_active" , "is_active" , "BooleanIndex" ) , ( "is_recei... |
def btreeSearch ( self , ip ) :
"""" b - tree search method
" param : ip""" | if not ip . isdigit ( ) :
ip = self . ip2Long ( ip )
if len ( self . __headerSip ) < 1 : # pass the super block
self . __f . seek ( 8 )
# read the header block
b = self . __f . read ( 8192 )
# parse the header block
sip = None
ptr = None
for i in range ( 0 , len ( b ) - 1 , 8 ) :
... |
def validate_arrangement_version ( self ) :
"""Validate if the arrangement _ version is supported
This is for autorebuilds to fail early otherwise they may failed
on workers because of osbs - client validation checks .
Method should be called after self . adjust _ build _ kwargs
Shows a warning when version... | arrangement_version = self . build_kwargs [ 'arrangement_version' ]
if arrangement_version is None :
return
if arrangement_version <= 5 : # TODO : raise as ValueError in release 1.6.38 +
self . log . warning ( "arrangement_version <= 5 is deprecated and will be removed" " in release 1.6.38" ) |
def validate_setup ( transactions ) :
"""First two transactions must set rate & days .""" | if not transactions :
return True
try :
first , second = transactions [ : 2 ]
except ValueError :
print ( 'Error: vacationrc file must have both initial days and rates entries' )
return False
parts1 , parts2 = first . split ( ) , second . split ( )
if parts1 [ 0 ] != parts2 [ 0 ] :
print ( 'Error: F... |
def get_unixtime_registered ( self ) :
"""Returns the user ' s registration date as a UNIX timestamp .""" | doc = self . _request ( self . ws_prefix + ".getInfo" , True )
return int ( doc . getElementsByTagName ( "registered" ) [ 0 ] . getAttribute ( "unixtime" ) ) |
def default_jardiff_options ( updates = None ) :
"""generate an options object with the appropriate default values in
place for API usage of jardiff features . overrides is an optional
dictionary which will be used to update fields on the options
object .""" | parser = create_optparser ( )
options , _args = parser . parse_args ( list ( ) )
if updates : # pylint : disable = W0212
options . _update_careful ( updates )
return options |
def get_instance ( self , payload ) :
"""Build an instance of WorkflowCumulativeStatisticsInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . taskrouter . v1 . workspace . workflow . workflow _ cumulative _ statistics . WorkflowCumulativeStatisticsInstance
: rtype : twili... | return WorkflowCumulativeStatisticsInstance ( self . _version , payload , workspace_sid = self . _solution [ 'workspace_sid' ] , workflow_sid = self . _solution [ 'workflow_sid' ] , ) |
def int_to_string ( x ) :
"""Convert integer x into a string of bytes , as per X9.62.""" | assert x >= 0
if x == 0 :
return b ( '\0' )
result = [ ]
while x :
ordinal = x & 0xFF
result . append ( int2byte ( ordinal ) )
x >>= 8
result . reverse ( )
return b ( '' ) . join ( result ) |
def add ( self , urls ) :
"""Add the provided urls to this purge request
The urls argument can be a single string , a list of strings , a queryset
or model instance . Models must implement ` get _ absolute _ url ( ) ` .""" | if isinstance ( urls , ( list , tuple ) ) :
self . urls . extend ( urls )
elif isinstance ( urls , basestring ) :
self . urls . append ( urls )
elif isinstance ( urls , QuerySet ) :
for obj in urls :
self . urls . append ( obj . get_absolute_url ( ) )
elif hasattr ( urls , 'get_absolute_url' ) :
... |
def push_state ( self , new_file = '' ) :
'Saves the current error state to parse subpackages' | self . subpackages . append ( { 'detected_type' : self . detected_type , 'message_tree' : self . message_tree , 'resources' : self . pushable_resources , 'metadata' : self . metadata } )
self . message_tree = { }
self . pushable_resources = { }
self . metadata = { 'requires_chrome' : False , 'listed' : self . metadata ... |
def parse_content ( self , content ) :
"""Use all the defined scanners to search the log file , setting the
properties defined in the scanner .""" | self . lines = content
for scanner in self . scanners :
scanner ( self ) |
def makeSoftwareVersion ( store , version , systemVersion ) :
"""Return the SoftwareVersion object from store corresponding to the
version object , creating it if it doesn ' t already exist .""" | return store . findOrCreate ( SoftwareVersion , systemVersion = systemVersion , package = unicode ( version . package ) , version = unicode ( version . short ( ) ) , major = version . major , minor = version . minor , micro = version . micro ) |
def appendPadding ( str , blocksize = AES_blocksize , mode = 'CMS' ) :
'''Pad ( append padding to ) string for use with symmetric encryption algorithm
Input : ( string ) str - String to be padded
( int ) blocksize - block size of the encryption algorithm
( string ) mode - padding scheme one in ( CMS , Bit , Z... | if mode not in ( 0 , 'CMS' ) :
for k in MODES . keys ( ) :
if mode in k :
return globals ( ) [ 'append' + k [ 1 ] + 'Padding' ] ( str , blocksize )
else :
return appendCMSPadding ( str , blocksize )
else :
return appendCMSPadding ( str , blocksize ) |
def dataset_create_version_cli ( self , folder , version_notes , quiet = False , convert_to_csv = True , delete_old_versions = False , dir_mode = 'skip' ) :
"""client wrapper for creating a version of a dataset
Parameters
folder : the folder with the dataset configuration / data files
version _ notes : notes ... | folder = folder or os . getcwd ( )
result = self . dataset_create_version ( folder , version_notes , quiet = quiet , convert_to_csv = convert_to_csv , delete_old_versions = delete_old_versions , dir_mode = dir_mode )
if result . invalidTags :
print ( ( 'The following are not valid tags and could not be added to ' '... |
def _process_emerge_err ( stdout , stderr ) :
'''Used to parse emerge output to provide meaningful output when emerge fails''' | ret = { }
rexp = re . compile ( r'^[<>=][^ ]+/[^ ]+ [^\n]+' , re . M )
slot_conflicts = re . compile ( r'^[^ \n]+/[^ ]+:[^ ]' , re . M ) . findall ( stderr )
if slot_conflicts :
ret [ 'slot conflicts' ] = slot_conflicts
blocked = re . compile ( r'(?m)^\[blocks .+\] ' r'([^ ]+/[^ ]+-[0-9]+[^ ]+)' r'.*$' ) . findall ... |
def _index ( self ) :
"""Keys a list of file paths that have been pickled in this directory .
The index is stored in a json file in the same directory as the
pickled objects .""" | if self . __index is None :
try :
with open ( self . _get_path ( 'index.json' ) ) as f :
data = json . load ( f )
except ( IOError , ValueError ) :
self . __index = { }
else : # 0 means version is not defined ( = always delete cache ) :
if data . get ( 'version' , 0 ) != ... |
def to_dict ( self ) :
"""Return a dictionary representation of the dataset .""" | d = dict ( doses = self . doses , ns = self . ns , means = self . means , stdevs = self . stdevs )
d . update ( self . kwargs )
return d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.