signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_default_plugin ( cls ) :
'''Return a default plugin .''' | from importlib import import_module
from django . conf import settings
default_plugin = getattr ( settings , 'ACCESS_DEFAULT_PLUGIN' , "access.plugins.DjangoAccessPlugin" )
if default_plugin not in cls . default_plugins :
logger . info ( "Creating a default plugin: %s" , default_plugin )
path = default_plugin .... |
def add_coupon ( self , coupon , idempotency_key = None ) :
"""Add a coupon to a Customer .
The coupon can be a Coupon object , or a valid Stripe Coupon ID .""" | if isinstance ( coupon , StripeModel ) :
coupon = coupon . id
stripe_customer = self . api_retrieve ( )
stripe_customer [ "coupon" ] = coupon
stripe_customer . save ( idempotency_key = idempotency_key )
return self . __class__ . sync_from_stripe_data ( stripe_customer ) |
def is_non_zero_before_non_zero ( self , other ) :
"""Return ` ` True ` ` if this time interval ends
when the given other time interval begins ,
and both have non zero length .
: param other : the other interval
: type other : : class : ` ~ aeneas . exacttiming . TimeInterval `
: raises TypeError : if ` `... | return self . is_adjacent_before ( other ) and ( not self . has_zero_length ) and ( not other . has_zero_length ) |
def get_news_aggregation ( self ) :
"""Calling News Aggregation API
Return :
json data""" | news_aggregation_url = self . api_path + "news_aggregation" + "/"
response = self . get_response ( news_aggregation_url )
return response |
def _record_field_to_json ( fields , row_value ) :
"""Convert a record / struct field to its JSON representation .
Args :
fields ( Sequence [ : class : ` ~ google . cloud . bigquery . schema . SchemaField ` ] , ) :
The : class : ` ~ google . cloud . bigquery . schema . SchemaField ` s of the
record ' s subf... | record = { }
isdict = isinstance ( row_value , dict )
for subindex , subfield in enumerate ( fields ) :
subname = subfield . name
if isdict :
subvalue = row_value . get ( subname )
else :
subvalue = row_value [ subindex ]
record [ subname ] = _field_to_json ( subfield , subvalue )
return... |
def _update_dispatches ( self ) :
"""Updates dispatched data in DB according to information gather by ` mark _ * ` methods ,""" | Dispatch . log_dispatches_errors ( self . _st [ 'error' ] + self . _st [ 'failed' ] )
Dispatch . set_dispatches_statuses ( ** self . _st )
self . _init_delivery_statuses_dict ( ) |
def get_using_network_time ( ) :
'''Display whether network time is on or off
: return : True if network time is on , False if off
: rtype : bool
CLI Example :
. . code - block : : bash
salt ' * ' timezone . get _ using _ network _ time''' | ret = salt . utils . mac_utils . execute_return_result ( 'systemsetup -getusingnetworktime' )
return salt . utils . mac_utils . validate_enabled ( salt . utils . mac_utils . parse_return ( ret ) ) == 'on' |
def info ( ctx , check_fips ) :
"""Show general information .
Displays information about the attached YubiKey such as serial number ,
firmware version , applications , etc .""" | dev = ctx . obj [ 'dev' ]
if dev . is_fips and check_fips :
fips_status = get_overall_fips_status ( dev . serial , dev . config )
click . echo ( 'Device type: {}' . format ( dev . device_name ) )
click . echo ( 'Serial number: {}' . format ( dev . serial or 'Not set or unreadable' ) )
if dev . version :
f_versi... |
def _mdb_get_database ( uri , ** kwargs ) :
"""Helper - function to connect to MongoDB and return a database object .
The ` uri ' argument should be either a full MongoDB connection URI string ,
or just a database name in which case a connection to the default mongo
instance at mongodb : / / localhost : 27017... | if not "tz_aware" in kwargs : # default , but not forced
kwargs [ "tz_aware" ] = True
connection_factory = MongoClient
_parsed_uri = { }
try :
_parsed_uri = pymongo . uri_parser . parse_uri ( uri )
except pymongo . errors . InvalidURI : # assume URI to be just the database name
db_name = uri
_conn = Mon... |
def migrate ( move_data = True , update_alias = True ) :
"""Upgrade function that creates a new index for the data . Optionally it also can
( and by default will ) reindex previous copy of the data into the new index
( specify ` ` move _ data = False ` ` to skip this step ) and update the alias to
point to th... | # construct a new index name by appending current timestamp
next_index = PATTERN . replace ( '*' , datetime . now ( ) . strftime ( '%Y%m%d%H%M%S%f' ) )
# get the low level connection
es = connections . get_connection ( )
# create new index , it will use the settings from the template
es . indices . create ( index = nex... |
def oauth1_token_setter ( remote , resp , token_type = '' , extra_data = None ) :
"""Set an OAuth1 token .
: param remote : The remote application .
: param resp : The response .
: param token _ type : The token type . ( Default : ` ` ' ' ` ` )
: param extra _ data : Extra information . ( Default : ` ` None... | return token_setter ( remote , resp [ 'oauth_token' ] , secret = resp [ 'oauth_token_secret' ] , extra_data = extra_data , token_type = token_type , ) |
def get_smart_invite ( self , smart_invite_id , recipient_email ) :
"""Gets the details for a smart invite .
: param string smart _ invite _ id : - A String uniquely identifying the event for your
application ( note : this is NOT an ID generated by Cronofy ) .
: param string recipient _ email : - The email ad... | params = { 'smart_invite_id' : smart_invite_id , 'recipient_email' : recipient_email }
return self . request_handler . get ( 'smart_invites' , params = params , use_api_key = True ) . json ( ) |
def tag_named_entities ( self ) :
"""Tag ` ` named _ entities ` ` layer .
This automatically performs morphological analysis along with all dependencies .""" | if not self . is_tagged ( LABEL ) :
self . tag_labels ( )
nes = [ ]
word_start = - 1
labels = self . labels + [ 'O' ]
# last is sentinel
words = self . words
label = 'O'
for i , l in enumerate ( labels ) :
if l . startswith ( 'B-' ) or l == 'O' :
if word_start != - 1 :
nes . append ( { START... |
def _create_percolator_mapping ( index , doc_type ) :
"""Update mappings with the percolator field .
. . note : :
This is only needed from ElasticSearch v5 onwards , because percolators
are now just a special type of field inside mappings .""" | if ES_VERSION [ 0 ] >= 5 :
current_search_client . indices . put_mapping ( index = index , doc_type = doc_type , body = PERCOLATOR_MAPPING , ignore = [ 400 , 404 ] ) |
def validate_month_for_31_days ( month_number ) :
"""A function that checks if a given month number is for a month that has 31 days .
Args :
month _ number ( int ) : Number representing the month ( 1-12)
Returns :
bool : True if the month has 31 days , False otherwise
Examples :
> > > validate _ month _... | month_31_days = [ 1 , 3 , 5 , 7 , 8 , 10 , 12 ]
return month_number in month_31_days |
def chi_squareds ( self , p = None ) :
"""Returns a list of chi squared for each data set . Also uses ydata _ massaged .
p = None means use the fit results""" | if len ( self . _set_xdata ) == 0 or len ( self . _set_ydata ) == 0 :
return None
if p is None :
p = self . results [ 0 ]
# get the residuals
rs = self . studentized_residuals ( p )
# Handle the none case
if rs == None :
return None
# square em and sum em .
cs = [ ]
for r in rs :
cs . append ( sum ( r *... |
def find_xor_mask ( data , alphabet = None , max_depth = 3 , min_depth = 0 , iv = None ) :
"""Produce a series of bytestrings that when XORed together end up being
equal to ` ` data ` ` and only contain characters from the giving
` ` alphabet ` ` . The initial state ( or previous state ) can be given as
` ` i... | if alphabet is None :
alphabet = set ( i for i in range ( 256 ) if i not in ( 0 , 10 , 13 ) )
else :
alphabet = set ( six . iterbytes ( alphabet ) )
if iv is None :
iv = b'\0' * len ( data )
if len ( data ) != len ( iv ) :
raise ValueError ( 'length of iv differs from data' )
if not min_depth and data =... |
def sync_sdb ( saltenv = None , extmod_whitelist = None , extmod_blacklist = None ) :
'''. . versionadded : : 2015.5.8,2015.8.3
Sync sdb modules from ` ` salt : / / _ sdb ` ` to the minion
saltenv
The fileserver environment from which to sync . To sync from more than
one environment , pass a comma - separat... | ret = _sync ( 'sdb' , saltenv , extmod_whitelist , extmod_blacklist )
return ret |
def anyword_substring_search_inner ( query_word , target_words ) :
"""return True if ANY target _ word matches a query _ word""" | for target_word in target_words :
if ( target_word . startswith ( query_word ) ) :
return query_word
return False |
def psql_to_obj ( cls , file_path = None , text = '' , columns = None , remove_empty_rows = True , key_on = None , deliminator = ' | ' , eval_cells = True ) :
"""This will convert a psql file or text to a seaborn table
: param file _ path : str of the path to the file
: param text : str of the csv text
: para... | text = cls . _get_lines ( file_path , text )
if len ( text ) == 1 :
text = text [ 0 ] . split ( '\r' )
if not text [ 1 ] . replace ( '+' , '' ) . replace ( '-' , '' ) . strip ( ) :
text . pop ( 1 )
# get rid of bar
list_of_list = [ [ cls . _eval_cell ( cell , _eval = eval_cells ) for cell in row . split ( delim... |
def match_repository_configuration ( url , page_size = 10 , page_index = 0 , sort = "" ) :
"""Search for Repository Configurations based on internal or external url with exact match""" | content = match_repository_configuration_raw ( url , page_size , page_index , sort )
if content :
return utils . format_json_list ( content ) |
def is_quota_exceeded ( self ) -> bool :
'''Return whether the quota is exceeded .''' | if self . quota and self . _url_table is not None :
return self . size >= self . quota and self . _url_table . get_root_url_todo_count ( ) == 0 |
def forcemerge ( self , index = None , params = None ) :
"""The force merge API allows to force merging of one or more indices
through an API . The merge relates to the number of segments a Lucene
index holds within each shard . The force merge operation allows to
reduce the number of segments by merging them... | return self . transport . perform_request ( "POST" , _make_path ( index , "_forcemerge" ) , params = params ) |
def __allocateBits ( self ) :
"""Allocates the bit range depending on the required bit count""" | if self . _bit_count < 0 :
raise Exception ( "A margin cannot request negative number of bits" )
if self . _bit_count == 0 :
return
# Build a list of occupied ranges
margins = self . _qpart . getMargins ( )
occupiedRanges = [ ]
for margin in margins :
bitRange = margin . getBitRange ( )
if bitRange is n... |
def clear_masters ( self ) :
"""Clear master packages if already exist in dependencies
or if added to install two or more times""" | packages = [ ]
for mas in Utils ( ) . remove_dbs ( self . packages ) :
if mas not in self . dependencies :
packages . append ( mas )
self . packages = packages |
def cancel_rekey ( self , recovery_key = False ) :
"""Cancel any in - progress rekey .
This clears the rekey settings as well as any progress made . This must be called to change the parameters of the
rekey .
Note : Verification is still a part of a rekey . If rekeying is canceled during the verification flow... | api_path = '/v1/sys/rekey/init'
if recovery_key :
api_path = '/v1/sys/rekey-recovery-key/init'
response = self . _adapter . delete ( url = api_path , )
return response |
def lv_unpack ( txt ) :
"""Deserializes a string of the length : value format
: param txt : The input string
: return : a list og values""" | txt = txt . strip ( )
res = [ ]
while txt :
l , v = txt . split ( ':' , 1 )
res . append ( v [ : int ( l ) ] )
txt = v [ int ( l ) : ]
return res |
def get_start_time ( self ) :
"""Determines when has this process started running .
@ rtype : win32 . SYSTEMTIME
@ return : Process start time .""" | if win32 . PROCESS_ALL_ACCESS == win32 . PROCESS_ALL_ACCESS_VISTA :
dwAccess = win32 . PROCESS_QUERY_LIMITED_INFORMATION
else :
dwAccess = win32 . PROCESS_QUERY_INFORMATION
hProcess = self . get_handle ( dwAccess )
CreationTime = win32 . GetProcessTimes ( hProcess ) [ 0 ]
return win32 . FileTimeToSystemTime ( C... |
def _handle_eio_message ( self , sid , data ) :
"""Dispatch Engine . IO messages .""" | if sid in self . _binary_packet :
pkt = self . _binary_packet [ sid ]
if pkt . add_attachment ( data ) :
del self . _binary_packet [ sid ]
if pkt . packet_type == packet . BINARY_EVENT :
self . _handle_event ( sid , pkt . namespace , pkt . id , pkt . data )
else :
... |
def for_category ( self , category , context = None ) :
"""Returns actions list for this category in current application .
Actions are filtered according to : meth : ` . Action . available ` .
if ` context ` is None , then current action context is used
( : attr : ` context ` )""" | assert self . installed ( ) , "Actions not enabled on this application"
actions = self . _state [ "categories" ] . get ( category , [ ] )
if context is None :
context = self . context
return [ a for a in actions if a . available ( context ) ] |
def _get_cputemp_with_lmsensors ( self , zone = None ) :
"""Tries to determine CPU temperature using the ' sensors ' command .
Searches for the CPU temperature by looking for a value prefixed
by either " CPU Temp " or " Core 0 " - does not look for or average
out temperatures of all codes if more than one .""... | sensors = None
command = [ "sensors" ]
if zone :
try :
sensors = self . py3 . command_output ( command + [ zone ] )
except self . py3 . CommandError :
pass
if not sensors :
sensors = self . py3 . command_output ( command )
m = re . search ( "(Core 0|CPU Temp).+\+(.+).+\(.+" , sensors )
if m ... |
def mavlink_packet ( self , m ) :
'''handle an incoming mavlink packet''' | from MAVProxy . modules . mavproxy_map import mp_slipmap
mtype = m . get_type ( )
sysid = m . get_srcSystem ( )
if mtype == "HEARTBEAT" :
vname = 'plane'
if m . type in [ mavutil . mavlink . MAV_TYPE_FIXED_WING ] :
vname = 'plane'
elif m . type in [ mavutil . mavlink . MAV_TYPE_GROUND_ROVER ] :
... |
def _create_temporary_projects ( enabled_regions , args ) :
"""Creates a temporary project needed to build an underlying workflow
for a global workflow . Returns a dictionary with region names as keys
and project IDs as values
The regions in which projects will be created can be :
i . regions specified in d... | # Create one temp project in each region
projects_by_region = { }
# Project IDs by region
for region in enabled_regions :
try :
project_input = { "name" : "Temporary build project for dx build global workflow" , "region" : region }
if args . bill_to :
project_input [ "billTo" ] = args . ... |
def shell_run ( cmd , cin = None , cwd = None , timeout = 10 , critical = True , verbose = True ) :
'''Runs a shell command within a controlled environment .
. . note : : | use _ photon _ m |
: param cmd : The command to run
* A string one would type into a console like : command : ` git push - u origin maste... | res = dict ( command = cmd )
if cin :
cin = str ( cin )
res . update ( dict ( stdin = cin ) )
if cwd :
res . update ( dict ( cwd = cwd ) )
if isinstance ( cmd , str ) :
cmd = _split ( cmd )
try :
p = _Popen ( cmd , stdin = _PIPE , stdout = _PIPE , stderr = _PIPE , bufsize = 1 , cwd = cwd , universal... |
def _akima_interpolate ( xi , yi , x , der = 0 , axis = 0 ) :
"""Convenience function for akima interpolation .
xi and yi are arrays of values used to approximate some function f ,
with ` ` yi = f ( xi ) ` ` .
See ` Akima1DInterpolator ` for details .
Parameters
xi : array _ like
A sorted list of x - co... | from scipy import interpolate
try :
P = interpolate . Akima1DInterpolator ( xi , yi , axis = axis )
except TypeError : # Scipy earlier than 0.17.0 missing axis
P = interpolate . Akima1DInterpolator ( xi , yi )
if der == 0 :
return P ( x )
elif interpolate . _isscalar ( der ) :
return P ( x , der = der )... |
def files_write ( self , path , file , offset = 0 , create = False , truncate = False , count = None , ** kwargs ) :
"""Writes to a mutable file in the MFS .
. . code - block : : python
> > > c . files _ write ( " / test / file " , io . BytesIO ( b " hi " ) , create = True )
Parameters
path : str
Filepath... | opts = { "offset" : offset , "create" : create , "truncate" : truncate }
if count is not None :
opts [ "count" ] = count
kwargs . setdefault ( "opts" , opts )
args = ( path , )
body , headers = multipart . stream_files ( file , self . chunk_size )
return self . _client . request ( '/files/write' , args , data = bod... |
def less_naive ( gold_schemes ) :
"""find ' less naive ' baseline ( most common scheme of a given length in subcorpus )""" | best_schemes = defaultdict ( lambda : defaultdict ( int ) )
for g in gold_schemes :
best_schemes [ len ( g ) ] [ tuple ( g ) ] += 1
for i in best_schemes :
best_schemes [ i ] = tuple ( max ( best_schemes [ i ] . items ( ) , key = lambda x : x [ 1 ] ) [ 0 ] )
naive_schemes = [ ]
for g in gold_schemes :
naive... |
def mkdir ( self , href ) :
"""create remote folder
: param href : remote path
: return : response""" | for iTry in range ( TRYINGS ) :
logger . info ( u ( "mkdir(%s): %s" ) % ( iTry , href ) )
try :
href = remote ( href )
con = self . getConnection ( )
con . request ( "MKCOL" , _encode_utf8 ( href ) , "" , self . getHeaders ( ) )
response = con . getresponse ( )
checkRespo... |
def get_command_arg_list ( self , command_name : str , to_parse : Union [ Statement , str ] , preserve_quotes : bool ) -> Tuple [ Statement , List [ str ] ] :
"""Called by the argument _ list and argparse wrappers to retrieve just the arguments being
passed to their do _ * methods as a list .
: param command _ ... | # Check if to _ parse needs to be converted to a Statement
if not isinstance ( to_parse , Statement ) :
to_parse = self . parse ( command_name + ' ' + to_parse , expand = False )
if preserve_quotes :
return to_parse , to_parse . arg_list
else :
return to_parse , to_parse . argv [ 1 : ] |
def root ( path : Union [ str , pathlib . Path ] ) -> _Root :
"""Retrieve a root directory object from a path .
: param path : The path string or Path object .
: return : The created root object .""" | return _Root . from_path ( _normalise_path ( path ) ) |
def lstled ( x , n , array ) :
"""Given a number x and an array of non - decreasing floats
find the index of the largest array element less than or equal to x .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / lstled _ c . html
: param x : Value to search against .
: type x : ... | array = stypes . toDoubleVector ( array )
x = ctypes . c_double ( x )
n = ctypes . c_int ( n )
return libspice . lstled_c ( x , n , array ) |
def run ( self ) :
"""Filter job callback .""" | from pyrocore import config
try :
config . engine . open ( )
# TODO : select view into items
items = [ ]
self . run_filter ( items )
except ( error . LoggableError , xmlrpc . ERRORS ) as exc :
self . LOG . warn ( str ( exc ) ) |
def decouple ( fn ) :
"""Inverse operation of couple .
Create two functions of one argument and one return from a function that
takes two arguments and has two returns
Examples
> > > h = lambda x : ( 2 * x * * 3 , 6 * x * * 2)
> > > f , g = decouple ( h )
> > > f ( 5)
250
> > > g ( 5)
150""" | def fst ( * args , ** kwargs ) :
return fn ( * args , ** kwargs ) [ 0 ]
def snd ( * args , ** kwargs ) :
return fn ( * args , ** kwargs ) [ 1 ]
return fst , snd |
def inspecting_client_factory ( self , host , port , ioloop_set_to ) :
"""Return an instance of : class : ` ReplyWrappedInspectingClientAsync ` or similar
Provided to ease testing . Dynamically overriding this method after instantiation
but before start ( ) is called allows for deep brain surgery . See
: clas... | return ReplyWrappedInspectingClientAsync ( host , port , ioloop = ioloop_set_to , auto_reconnect = self . auto_reconnect ) |
def _setChoice ( self , s , strict = 0 ) :
"""Set choice parameter from string s""" | clist = _getChoice ( s , strict )
self . choice = list ( map ( self . _coerceValue , clist ) )
self . _setChoiceDict ( ) |
def _toolkits_select_columns ( dataset , columns ) :
"""Same as select columns but redirect runtime error to ToolkitError .""" | try :
return dataset . select_columns ( columns )
except RuntimeError :
missing_features = list ( set ( columns ) . difference ( set ( dataset . column_names ( ) ) ) )
raise ToolkitError ( "Input data does not contain the following columns: " + "{}" . format ( missing_features ) ) |
def set_ntp_servers ( primary_server = None , secondary_server = None , deploy = False ) :
'''Set the NTP servers of the Palo Alto proxy minion . A commit will be required before this is processed .
CLI Example :
Args :
primary _ server ( str ) : The primary NTP server IP address or FQDN .
secondary _ serve... | ret = { }
if primary_server :
query = { 'type' : 'config' , 'action' : 'set' , 'xpath' : '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server' , 'element' : '<ntp-server-address>{0}</ntp-server-address>' . format ( primary_server ) }
ret . update ( { 'pri... |
def clean_filename ( s , minimal_change = False ) :
"""Sanitize a string to be used as a filename .
If minimal _ change is set to true , then we only strip the bare minimum of
characters that are problematic for filesystems ( namely , ' : ' , ' / ' and
' \x00 ' , ' \n ' ) .""" | # First , deal with URL encoded strings
h = html_parser . HTMLParser ( )
s = h . unescape ( s )
s = unquote_plus ( s )
# Strip forbidden characters
# https : / / msdn . microsoft . com / en - us / library / windows / desktop / aa365247 ( v = vs . 85 ) . aspx
s = ( s . replace ( ':' , '-' ) . replace ( '/' , '-' ) . rep... |
def copy_db ( source_env , destination_env ) :
"""Copies Db betweem servers , ie develop to qa .
Should be called by function from function defined in project fabfile .
Example usage :
def copy _ db _ between _ servers ( source _ server , destination _ server ) :
source _ env = { }
destination _ env = { }... | env . update ( source_env )
local_file_path = _get_db ( )
# put the file on external file system
# clean external db
# load database into external file system
env . update ( destination_env )
with cd ( env . remote_path ) :
sudo ( 'mkdir -p backups' , user = env . remote_user )
sudo ( env . python + ' manage.py... |
def _pullMessage ( self ) :
"""Call pull api with seq value to get message data .""" | data = { "msgs_recv" : 0 , "sticky_token" : self . _sticky , "sticky_pool" : self . _pool , "clientid" : self . _client_id , "state" : "active" if self . _markAlive else "offline" , }
return self . _get ( self . req_url . STICKY , data , fix_request = True , as_json = True ) |
def bootstrap_trajectories ( trajs , correlation_length ) :
"""Generates a randomly resampled count matrix given the input coordinates .
See API function for full documentation .""" | from scipy . stats import rv_discrete
# if we have just one trajectory , put it into a one - element list :
if ( isinstance ( trajs [ 0 ] , ( int , int , float ) ) ) :
trajs = [ trajs ]
ntraj = len ( trajs )
# determine correlation length to be used
lengths = determine_lengths ( trajs )
Ltot = np . sum ( lengths )
... |
def create_class_instance ( element , element_id , doc_id ) :
"""given an Salt XML element , returns a corresponding ` SaltElement ` class
instance , i . e . a SaltXML ` SToken ` node will be converted into a
` TokenNode ` .
Parameters
element : lxml . etree . _ Element
an ` etree . _ Element ` is the XML... | xsi_type = get_xsi_type ( element )
element_class = XSI_TYPE_CLASSES [ xsi_type ]
return element_class . from_etree ( element ) |
def jira_connection ( config ) :
"""Gets a JIRA API connection . If a connection has already been created the existing connection
will be returned .""" | global _jira_connection
if _jira_connection :
return _jira_connection
else :
jira_options = { 'server' : config . get ( 'jira' ) . get ( 'url' ) }
cookies = configuration . _get_cookies_as_dict ( )
jira_connection = jira_ext . JIRA ( options = jira_options )
session = jira_connection . _session
... |
def validate ( self , value ) :
"""Re - implements the orb . Column . validate method to verify that the
reference model type that is used with this column instance is
the type of value being provided .
: param value : < variant >
: return : < bool >""" | ref_model = self . referenceModel ( )
if isinstance ( value , orb . Model ) :
expected_schema = ref_model . schema ( ) . name ( )
received_schema = value . schema ( ) . name ( )
if expected_schema != received_schema :
raise orb . errors . InvalidReference ( self . name ( ) , expects = expected_schem... |
def from_json_and_lambdas ( cls , file : str , lambdas ) :
"""Builds a GrFN from a JSON object .
Args :
cls : The class variable for object creation .
file : Filename of a GrFN JSON file .
Returns :
type : A GroundedFunctionNetwork object .""" | with open ( file , "r" ) as f :
data = json . load ( f )
return cls . from_dict ( data , lambdas ) |
def get_variants ( self , arch = None , types = None , recursive = False ) :
"""Return all variants of given arch and types .
Supported variant types :
self - include the top - level ( " self " ) variant as well
addon
variant
optional""" | types = types or [ ]
result = [ ]
if "self" in types :
result . append ( self )
for variant in six . itervalues ( self . variants ) :
if types and variant . type not in types :
continue
if arch and arch not in variant . arches . union ( [ "src" ] ) :
continue
result . append ( variant )
... |
def version ( self ) :
"""Fetch version information from all plugins and store in the report
version file""" | versions = [ ]
versions . append ( "sosreport: %s" % __version__ )
for plugname , plug in self . loaded_plugins :
versions . append ( "%s: %s" % ( plugname , plug . version ) )
self . archive . add_string ( content = "\n" . join ( versions ) , dest = 'version.txt' ) |
def mouseDoubleClickEvent ( self , event ) :
"""Emits the node double clicked event when a node is double clicked .
: param event | < QMouseDoubleClickEvent >""" | super ( XNodeScene , self ) . mouseDoubleClickEvent ( event )
# emit the node double clicked signal
if event . button ( ) == Qt . LeftButton :
item = self . itemAt ( event . scenePos ( ) )
if not item :
self . clearSelection ( )
else :
blocked = self . signalsBlocked ( )
self . block... |
def can ( user , action , subject ) :
"""Checks if a given user has the ability to perform the action on a subject
: param user : A user object
: param action : an action string , typically ' read ' , ' edit ' , ' manage ' . Use bouncer . constants for readability
: param subject : the resource in question . ... | ability = Ability ( user , get_authorization_method ( ) )
return ability . can ( action , subject ) |
def read_anchors ( ac , qorder , sorder , minsize = 0 ) :
"""anchors file are just ( geneA , geneB ) pairs ( with possible deflines )""" | all_anchors = defaultdict ( list )
nanchors = 0
anchor_to_block = { }
for a , b , idx in ac . iter_pairs ( minsize = minsize ) :
if a not in qorder or b not in sorder :
continue
qi , q = qorder [ a ]
si , s = sorder [ b ]
pair = ( qi , si )
all_anchors [ ( q . seqid , s . seqid ) ] . append ... |
def get_predicted_log_arr ( self ) :
'''getter''' | if isinstance ( self . __predicted_log_arr , np . ndarray ) :
return self . __predicted_log_arr
else :
raise TypeError ( ) |
def cut ( self , start = None , stop = None , whence = 0 , version = None , include_ends = True , time_from_zero = False , ) :
"""cut * MDF * file . * start * and * stop * limits are absolute values
or values relative to the first timestamp depending on the * whence *
argument .
Parameters
start : float
s... | if version is None :
version = self . version
else :
version = validate_version_argument ( version )
out = MDF ( version = version )
if whence == 1 :
timestamps = [ ]
for i , group in enumerate ( self . groups ) :
fragment = next ( self . _load_data ( group ) )
master = self . get_master... |
def set_power ( self , state ) :
"""Sets the power state of the smart plug .""" | packet = bytearray ( 16 )
packet [ 0 ] = 2
if self . check_nightlight ( ) :
packet [ 4 ] = 3 if state else 2
else :
packet [ 4 ] = 1 if state else 0
self . send_packet ( 0x6a , packet ) |
def make_venv ( self , dj_version ) :
"""Creates a virtual environment for a given Django version .
: param str dj _ version :
: rtype : str
: return : path to created virtual env""" | venv_path = self . _get_venv_path ( dj_version )
self . logger . info ( 'Creating virtual environment for Django %s ...' % dj_version )
try :
create_venv ( venv_path , ** VENV_CREATE_KWARGS )
except ValueError :
self . logger . warning ( 'Virtual environment directory already exists. Skipped.' )
self . venv_ins... |
def setRecord ( self , record ) :
"""Sets the record instance for this widget to the inputed record .
: param record | < orb . Table >""" | self . _record = record
if ( not record ) :
return
self . setModel ( record . __class__ )
schema = self . model ( ) . schema ( )
# set the information
column_edits = self . findChildren ( XOrbColumnEdit )
for widget in column_edits :
columnName = widget . columnName ( )
column = schema . column ( columnName... |
def get_device_state ( self , device , id_override = None , type_override = None ) :
"""Get device state via online API .
Args :
device ( WinkDevice ) : The device the change is being requested for .
id _ override ( String , optional ) : A device ID used to override the
passed in device ' s ID . Used to mak... | _LOGGER . info ( "Getting state via online API" )
object_id = id_override or device . object_id ( )
object_type = type_override or device . object_type ( )
url_string = "{}/{}s/{}" . format ( self . BASE_URL , object_type , object_id )
arequest = requests . get ( url_string , headers = API_HEADERS )
response_json = are... |
def mul ( lhs : Any , rhs : Any , default : Any = RaiseTypeErrorIfNotProvided ) -> Any :
"""Returns lhs * rhs , or else a default if the operator is not implemented .
This method is mostly used by _ _ pow _ _ methods trying to return
NotImplemented instead of causing a TypeError .
Args :
lhs : Left hand sid... | # Use left - hand - side ' s _ _ mul _ _ .
left_mul = getattr ( lhs , '__mul__' , None )
result = NotImplemented if left_mul is None else left_mul ( rhs )
# Fallback to right - hand - side ' s _ _ rmul _ _ .
if result is NotImplemented :
right_mul = getattr ( rhs , '__rmul__' , None )
result = NotImplemented if... |
def parse_entry ( self , row ) :
"""Parse an individual VCF entry and return a VCFEntry which contains information about
the call ( such as alternative allele , zygosity , etc . )""" | var_call = VCFEntry ( self . individuals )
var_call . parse_entry ( row )
return var_call |
def mc_sample_path ( P , init = 0 , sample_size = 1000 , random_state = None ) :
"""Generates one sample path from the Markov chain represented by
( n x n ) transition matrix P on state space S = { { 0 , . . . , n - 1 } } .
Parameters
P : array _ like ( float , ndim = 2)
A Markov transition matrix .
init ... | random_state = check_random_state ( random_state )
if isinstance ( init , numbers . Integral ) :
X_0 = init
else :
cdf0 = np . cumsum ( init )
u_0 = random_state . random_sample ( )
X_0 = searchsorted ( cdf0 , u_0 )
mc = MarkovChain ( P )
return mc . simulate ( ts_length = sample_size , init = X_0 , ran... |
def build_joblist ( jobgraph ) :
"""Returns a list of jobs , from a passed jobgraph .""" | jobset = set ( )
for job in jobgraph :
jobset = populate_jobset ( job , jobset , depth = 1 )
return list ( jobset ) |
def _install_hiero ( use_threaded_wrapper ) :
"""Helper function to The Foundry Hiero support""" | import hiero
import nuke
if "--hiero" not in nuke . rawArgs :
raise ImportError
def threaded_wrapper ( func , * args , ** kwargs ) :
return hiero . core . executeInMainThreadWithResult ( func , args , kwargs )
_common_setup ( "Hiero" , threaded_wrapper , use_threaded_wrapper ) |
def aveknt ( t , k ) :
"""Compute the running average of ` k ` successive elements of ` t ` . Return the averaged array .
Parameters :
Python list or rank - 1 array
int , > = 2 , how many successive elements to average
Returns :
rank - 1 array , averaged data . If k > len ( t ) , returns a zero - length a... | t = np . atleast_1d ( t )
if t . ndim > 1 :
raise ValueError ( "t must be a list or a rank-1 array" )
n = t . shape [ 0 ]
u = max ( 0 , n - ( k - 1 ) )
# number of elements in the output array
out = np . empty ( ( u , ) , dtype = t . dtype )
for j in range ( u ) :
out [ j ] = sum ( t [ j : ( j + k ) ] ) / k
ret... |
def urls ( self ) :
"""Get all of the api endpoints .
NOTE : only for django as of now .
NOTE : urlpatterns are deprecated since Django1.8
: return list : urls""" | from django . conf . urls import url
urls = [ url ( r'^$' , self . documentation ) , url ( r'^map$' , self . map_view ) , ]
for resource_name in self . resource_map :
urls . extend ( [ url ( r'(?P<resource_name>{})$' . format ( resource_name ) , self . handler_view ) , url ( r'(?P<resource_name>{})/(?P<ids>[\w\-\,]... |
def pid ( self ) :
"""The process ' PID .""" | # Support for pexpect ' s functionality .
if hasattr ( self . subprocess , 'proc' ) :
return self . subprocess . proc . pid
# Standard subprocess method .
return self . subprocess . pid |
def writeln ( self , text , fg = 'black' , bg = 'white' ) :
'''write to the console with linefeed''' | if not isinstance ( text , str ) :
text = str ( text )
self . write ( text + '\n' , fg = fg , bg = bg ) |
def _pop_colors_and_alpha ( glyphclass , kwargs , prefix = "" , default_alpha = 1.0 ) :
"""Given a kwargs dict , a prefix , and a default value , looks for different
color and alpha fields of the given prefix , and fills in the default value
if it doesn ' t exist .""" | result = dict ( )
# TODO : The need to do this and the complexity of managing this kind of
# thing throughout the codebase really suggests that we need to have
# a real stylesheet class , where defaults and Types can declaratively
# substitute for this kind of imperative logic .
color = kwargs . pop ( prefix + "color" ... |
def create_config ( cls , params , prefix = None , name = None ) :
"""Create a new : class : ` . Config ` container .
Invoked during initialisation , it overrides defaults
with ` ` params ` ` and apply the ` ` prefix ` ` to non global
settings .""" | if isinstance ( cls . cfg , Config ) :
cfg = cls . cfg . copy ( name = name , prefix = prefix )
else :
cfg = cls . cfg . copy ( )
if name :
cfg [ name ] = name
if prefix :
cfg [ prefix ] = prefix
cfg = Config ( ** cfg )
cfg . update_settings ( )
cfg . update ( params , True )
return ... |
def bracket_level ( text , open = { '(' , '[' , '{' } , close = { ')' , ']' , '}' } ) :
"""Return 0 if string contains balanced brackets or no brackets .""" | level = 0
for c in text :
if c in open :
level += 1
elif c in close :
level -= 1
return level |
def add_hash_memo ( self , memo_hash ) :
"""Set the memo for the transaction to a new : class : ` HashMemo
< stellar _ base . memo . HashMemo > ` .
: param memo _ hash : A 32 byte hash or hex encoded string to use as the memo .
: type memo _ hash : bytes , str
: return : This builder instance .""" | memo_hash = memo . HashMemo ( memo_hash )
return self . add_memo ( memo_hash ) |
def create_chebyshev_samples ( order , dim = 1 ) :
"""Chebyshev sampling function .
Args :
order ( int ) :
The number of samples to create along each axis .
dim ( int ) :
The number of dimensions to create samples for .
Returns :
samples following Chebyshev sampling scheme mapped to the
` ` [ 0 , 1 ... | x_data = .5 * numpy . cos ( numpy . arange ( order , 0 , - 1 ) * numpy . pi / ( order + 1 ) ) + .5
x_data = chaospy . quad . combine ( [ x_data ] * dim )
return x_data . T |
def tokens_for_completion ( self , line : str , begidx : int , endidx : int ) -> Tuple [ List [ str ] , List [ str ] ] :
"""Used by tab completion functions to get all tokens through the one being completed
: param line : the current input line with leading whitespace removed
: param begidx : the beginning inde... | import copy
unclosed_quote = ''
quotes_to_try = copy . copy ( constants . QUOTES )
tmp_line = line [ : endidx ]
tmp_endidx = endidx
# Parse the line into tokens
while True :
try :
initial_tokens = shlex_split ( tmp_line [ : tmp_endidx ] )
# If the cursor is at an empty token outside of a quoted stri... |
def using ( _other , ** kwargs ) :
"""Callback that processes the match with a different lexer .
The keyword arguments are forwarded to the lexer , except ` state ` which
is handled separately .
` state ` specifies the state that the new lexer will start in , and can
be an enumerable such as ( ' root ' , ' ... | gt_kwargs = { }
if 'state' in kwargs :
s = kwargs . pop ( 'state' )
if isinstance ( s , ( list , tuple ) ) :
gt_kwargs [ 'stack' ] = s
else :
gt_kwargs [ 'stack' ] = ( 'root' , s )
if _other is this :
def callback ( lexer , match , ctx = None ) : # if keyword arguments are given the call... |
def parse_metadata_string ( metadata_string ) :
"""Grab end time with regular expression .""" | regex = r"STOP_DATE.+?VALUE\s*=\s*\"(.+?)\""
match = re . search ( regex , metadata_string , re . DOTALL )
end_time_str = match . group ( 1 )
return end_time_str |
def leaves ( self , nodes = None , unique = True ) :
"""Get the leaves of the tree starting at this root .
Args :
nodes ( iterable ) : limit leaves for these node names
unique : only include individual leaf nodes once
Returns :
list of leaf nodes""" | if nodes is None :
return super ( DependencyTree , self ) . leaves ( unique = unique )
res = list ( )
for child_id in nodes :
for sub_child in self . _all_nodes [ child_id ] . leaves ( unique = unique ) :
if not unique or sub_child not in res :
res . append ( sub_child )
return res |
def serial ( self ) :
"""Returns true if the CI server should run in serial mode .""" | serial = self . property_get ( "SERIAL" , False )
if isinstance ( serial , str ) :
return serial . lower ( ) == "true"
else :
return serial |
def require_component_access ( view_func , component ) :
"""Perform component can _ access check to access the view .
: param component containing the view ( panel or dashboard ) .
Raises a : exc : ` ~ horizon . exceptions . NotAuthorized ` exception if the
user cannot access the component containing the view... | from horizon . exceptions import NotAuthorized
@ functools . wraps ( view_func , assigned = available_attrs ( view_func ) )
def dec ( request , * args , ** kwargs ) :
if not component . can_access ( { 'request' : request } ) :
raise NotAuthorized ( _ ( "You are not authorized to access %s" ) % request . pat... |
def make_route ( self , dst , gw = None , dev = None ) :
"""Internal function : create a route for ' dst ' via ' gw ' .""" | prefix , plen = ( dst . split ( "/" ) + [ "128" ] ) [ : 2 ]
plen = int ( plen )
if gw is None :
gw = "::"
if dev is None :
dev , ifaddr , x = self . route ( gw )
else : # TODO : do better than that
# replace that unique address by the list of all addresses
lifaddr = in6_getifaddr ( )
# filter ( lambda x... |
def watch_zone ( self , zone_id ) :
"""Add a zone to the watchlist .
Zones on the watchlist will push all
state changes ( and those of the source they are currently connected to )
back to the client""" | r = yield from self . _send_cmd ( "WATCH %s ON" % ( zone_id . device_str ( ) , ) )
self . _watched_zones . add ( zone_id )
return r |
def NewFromHsl ( h , s , l , alpha = 1.0 , wref = _DEFAULT_WREF ) :
'''Create a new instance based on the specifed HSL values .
Parameters :
The Hue component value [ 0 . . . 1]
The Saturation component value [ 0 . . . 1]
The Lightness component value [ 0 . . . 1]
: alpha :
The color transparency [ 0 . ... | return Color ( ( h , s , l ) , 'hsl' , alpha , wref ) |
def display ( port = None , height = None ) :
"""Display a TensorBoard instance already running on this machine .
Args :
port : The port on which the TensorBoard server is listening , as an
` int ` , or ` None ` to automatically select the most recently
launched TensorBoard .
height : The height of the fr... | _display ( port = port , height = height , print_message = True , display_handle = None ) |
def get_snapshot ( self , entity_id , lt = None , lte = None ) :
"""Gets the last snapshot for entity , optionally until a particular version number .
: rtype : Snapshot""" | snapshots = self . snapshot_store . get_domain_events ( entity_id , lt = lt , lte = lte , limit = 1 , is_ascending = False )
if len ( snapshots ) == 1 :
return snapshots [ 0 ] |
def load_credential_file ( self , path ) :
"""Load a credential file as is setup like the Java utilities""" | c_data = StringIO . StringIO ( )
c_data . write ( "[Credentials]\n" )
for line in open ( path , "r" ) . readlines ( ) :
c_data . write ( line . replace ( "AWSAccessKeyId" , "aws_access_key_id" ) . replace ( "AWSSecretKey" , "aws_secret_access_key" ) )
c_data . seek ( 0 )
self . readfp ( c_data ) |
def _parse_number_from_substring ( smoothie_substring ) :
'''Returns the number in the expected string " N : 12.3 " , where " N " is the
axis , and " 12.3 " is a floating point value for the axis ' position''' | try :
return round ( float ( smoothie_substring . split ( ':' ) [ 1 ] ) , GCODE_ROUNDING_PRECISION )
except ( ValueError , IndexError , TypeError , AttributeError ) :
log . exception ( 'Unexpected argument to _parse_number_from_substring:' )
raise ParseError ( 'Unexpected argument to _parse_number_from_subs... |
def _set_hyperparameters ( self , parameters ) :
"""Set internal optimization parameters .""" | for name , value in parameters . iteritems ( ) :
try :
getattr ( self , name )
except AttributeError :
raise ValueError ( 'Each parameter in parameters must be an attribute. ' '{} is not.' . format ( name ) )
setattr ( self , name , value ) |
def get_posix ( self , i ) :
"""Get POSIX .""" | index = i . index
value = [ '[' ]
try :
c = next ( i )
if c != ':' :
raise ValueError ( 'Not a valid property!' )
else :
value . append ( c )
c = next ( i )
if c == '^' :
value . append ( c )
c = next ( i )
while c != ':' :
if c not... |
def fetch_partial ( self , container , obj , size ) :
"""Returns the first ' size ' bytes of an object . If the object is smaller
than the specified ' size ' value , the entire object is returned .""" | return self . _manager . fetch_partial ( container , obj , size ) |
async def build_task_dependencies ( chain , task , name , my_task_id ) :
"""Recursively build the task dependencies of a task .
Args :
chain ( ChainOfTrust ) : the chain of trust to add to .
task ( dict ) : the task definition to operate on .
name ( str ) : the name of the task to operate on .
my _ task _... | log . info ( "build_task_dependencies {} {}" . format ( name , my_task_id ) )
if name . count ( ':' ) > chain . context . config [ 'max_chain_length' ] :
raise CoTError ( "Too deep recursion!\n{}" . format ( name ) )
sorted_dependencies = find_sorted_task_dependencies ( task , name , my_task_id )
for task_name , ta... |
def canAdd ( self , filename ) :
"""Determines if a filename can be added to the depot under the current client
: param filename : File path to add
: type filename : str""" | try :
result = self . run ( [ 'add' , '-n' , '-t' , 'text' , filename ] ) [ 0 ]
except errors . CommandError as err :
LOGGER . debug ( err )
return False
if result . get ( 'code' ) not in ( 'error' , 'info' ) :
return True
LOGGER . warn ( 'Unable to add {}: {}' . format ( filename , result [ 'data' ] ) ... |
def __parseThunkData ( self , thunk , importSection ) :
"""Parses the data of a thunk and sets the data""" | offset = to_offset ( thunk . header . AddressOfData , importSection )
if 0xf0000000 & thunk . header . AddressOfData == 0x80000000 :
thunk . ordinal = thunk . header . AddressOfData & 0x0fffffff
else :
ibn = IMAGE_IMPORT_BY_NAME . from_buffer ( importSection . raw , offset )
checkOffset ( offset + 2 , impor... |
def add_new_observations ( self , y , exogenous = None , ** kwargs ) :
"""Update the endog / exog samples after a model fit .
After fitting your model and creating forecasts , you ' re going
to need to attach new samples to the data you fit on . These are
used to compute new forecasts ( but using the same est... | return self . update ( y , exogenous , ** kwargs ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.