signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def add_resource_subscription ( self , device_id , _resource_path , ** kwargs ) : # noqa : E501
"""Subscribe to a resource path # noqa : E501
The Device Management Connect eventing model consists of observable resources . This means that endpoints can deliver updated resource content , periodically or with a more... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . add_resource_subscription_with_http_info ( device_id , _resource_path , ** kwargs )
# noqa : E501
else :
( data ) = self . add_resource_subscription_with_http_info ( device_id , _resource_path , ** kwargs )
# n... |
def _add ( self , other ) :
"""Add a interval to the underlying IntervalSet data store . This does not perform any tests as we assume that
any requirements have already been checked and that this function is being called by an internal function such
as union ( ) , intersection ( ) or add ( ) .
: param other :... | if len ( [ interval for interval in self if other in interval ] ) > 0 : # if other is already represented
return
# remove any intervals which are fully represented by the interval we are adding
to_remove = [ interval for interval in self if interval in other ]
self . _data . difference_update ( to_remove )
self . _... |
def heightmap_add_hm ( hm1 : np . ndarray , hm2 : np . ndarray , hm3 : np . ndarray ) -> None :
"""Add two heightmaps together and stores the result in ` ` hm3 ` ` .
Args :
hm1 ( numpy . ndarray ) : The first heightmap .
hm2 ( numpy . ndarray ) : The second heightmap to add to the first .
hm3 ( numpy . ndar... | hm3 [ : ] = hm1 [ : ] + hm2 [ : ] |
async def send ( self , data , namespace = None , callback = None ) :
"""Send a message to the server .
The only difference with the : func : ` socketio . Client . send ` method is
that when the ` ` namespace ` ` argument is not given the namespace
associated with the class is used .
Note : this method is a... | return await self . client . send ( data , namespace = namespace or self . namespace , callback = callback ) |
def check_rev_options ( self , rev , dest , rev_options ) :
"""Check the revision options before checkout to compensate that tags
and branches may need origin / as a prefix .
Returns the SHA1 of the branch or tag if found .""" | revisions = self . get_tag_revs ( dest )
revisions . update ( self . get_branch_revs ( dest ) )
origin_rev = 'origin/%s' % rev
if origin_rev in revisions : # remote branch
return [ revisions [ origin_rev ] ]
elif rev in revisions : # a local tag or branch name
return [ revisions [ rev ] ]
else :
logger . wa... |
def save_prep ( cls , instance_or_instances ) :
"""Preprocess the object before the object is saved . This
automatically gets called when the save method gets called .""" | instances = make_obj_list ( instance_or_instances )
tokens = set ( cls . objects . get_available_tokens ( count = len ( instances ) , token_length = cls . token_length ) )
for instance in instances :
if not instance . token :
instance . token = tokens . pop ( )
super ( AbstractTokenModel , cls ) . save_prep... |
def _is_proxy_running ( proxyname ) :
'''Check if proxy for this name is running''' | cmd = ( 'ps ax | grep "salt-proxy --proxyid={0}" | grep -v grep' . format ( salt . ext . six . moves . shlex_quote ( proxyname ) ) )
cmdout = __salt__ [ 'cmd.run_all' ] ( cmd , timeout = 5 , python_shell = True )
if not cmdout [ 'stdout' ] :
return False
else :
return True |
def _file_local_list ( self , dest ) :
'''Helper util to return a list of files in a directory''' | if os . path . isdir ( dest ) :
destdir = dest
else :
destdir = os . path . dirname ( dest )
filelist = set ( )
for root , dirs , files in salt . utils . path . os_walk ( destdir , followlinks = True ) :
for name in files :
path = os . path . join ( root , name )
filelist . add ( path )
retu... |
def agent_delete ( self , agent_id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / chat / agents # delete - agent" | api_path = "/api/v2/agents/{agent_id}"
api_path = api_path . format ( agent_id = agent_id )
return self . call ( api_path , method = "DELETE" , ** kwargs ) |
def show_hist ( self , props = [ ] , bins = 20 , ** kwargs ) :
r"""Show a quick plot of key property distributions .
Parameters
props : string or list of strings
The pore and / or throat properties to be plotted as histograms
bins : int or array _ like
The number of bins to use when generating the histogr... | if type ( props ) is str :
props = [ props ]
N = len ( props )
if N == 1 :
r = 1
c = 1
elif N < 4 :
r = 1
c = N
else :
r = int ( sp . ceil ( N ** 0.5 ) )
c = int ( sp . floor ( N ** 0.5 ) )
for i in range ( len ( props ) ) :
plt . subplot ( r , c , i + 1 )
plt . hist ( self [ props [... |
def initialize_from_assignments ( assignments , k , max_assign_weight = 0.75 ) :
"""Creates a weight initialization matrix from Poisson clustering assignments .
Args :
assignments ( array ) : 1D array of integers , of length cells
k ( int ) : number of states / clusters
max _ assign _ weight ( float , optio... | cells = len ( assignments )
init_W = np . zeros ( ( k , cells ) )
for i , a in enumerate ( assignments ) : # entirely arbitrary . . . maybe it would be better to scale
# the weights based on k ?
init_W [ a , i ] = max_assign_weight
for a2 in range ( k ) :
if a2 != a :
init_W [ a2 , i ] = ( 1... |
def unassign_assessment_taken_from_bank ( self , assessment_taken_id , bank_id ) :
"""Removes an ` ` AssessmentTaken ` ` from a ` ` Bank ` ` .
arg : assessment _ taken _ id ( osid . id . Id ) : the ` ` Id ` ` of the
` ` AssessmentTaken ` `
arg : bank _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Bank ` ... | # Implemented from template for
# osid . resource . ResourceBinAssignmentSession . unassign _ resource _ from _ bin
mgr = self . _get_provider_manager ( 'ASSESSMENT' , local = True )
lookup_session = mgr . get_bank_lookup_session ( proxy = self . _proxy )
lookup_session . get_bank ( bank_id )
# to raise NotFound
self .... |
def register ( func = None , name = None ) :
"""Expose compiler to factory .
: param func : the callable to expose
: type func : callable
: param name : name of format
: type name : str
It can be used as a decorator : :
@ register ( name = ' my : validator ' )
def my _ validator ( obj ) :
if obj is ... | if not name :
raise CompilationError ( 'Name is required' )
if not func :
return partial ( register , name = name )
return FormatRegistry . register ( name , func ) |
def parse_with_retrieved ( self , retrieved ) :
"""Receives in input a dictionary of retrieved nodes .
Does all the logic here .""" | from aiida . common . exceptions import InvalidOperation
import os
output_path = None
error_path = None
try :
output_path , error_path = self . _fetch_output_files ( retrieved )
except InvalidOperation :
raise
except IOError as e :
self . logger . error ( e . message )
return False , ( )
if output_path ... |
def handle_json_GET_routes ( self , params ) :
"""Return a list of all routes .""" | schedule = self . server . schedule
result = [ ]
for r in schedule . GetRouteList ( ) :
result . append ( ( r . route_id , r . route_short_name , r . route_long_name ) )
result . sort ( key = lambda x : x [ 1 : 3 ] )
return result |
def plot_stateseries ( self , names : Optional [ Iterable [ str ] ] = None , average : bool = False , ** kwargs : Any ) -> None :
"""Plot the ` state ` series of the handled model .
See the documentation on method | Element . plot _ inputseries | for
additional information .""" | self . __plot ( self . model . sequences . states , names , average , kwargs ) |
def install ( feature , recurse = False , restart = False , source = None , exclude = None ) :
r'''Install a feature
. . note : :
Some features require reboot after un / installation , if so until the
server is restarted other features can not be installed !
. . note : :
Some features take a long time to ... | # If it is a list of features , make it a comma delimited string
if isinstance ( feature , list ) :
feature = ',' . join ( feature )
# Use Install - WindowsFeature on Windows 2012 ( osversion 6.2 ) and later
# minions . Default to Add - WindowsFeature for earlier releases of Windows .
# The newer command makes mana... |
def bundle_for_objs_and_resources ( objs , resources ) :
'''Generate rendered CSS and JS resources suitable for the given
collection of Bokeh objects
Args :
objs ( seq [ Model or Document ] ) :
resources ( BaseResources or tuple [ BaseResources ] )
Returns :
tuple''' | if isinstance ( resources , BaseResources ) :
js_resources = css_resources = resources
elif isinstance ( resources , tuple ) and len ( resources ) == 2 and all ( r is None or isinstance ( r , BaseResources ) for r in resources ) :
js_resources , css_resources = resources
if js_resources and not css_resource... |
def polygon ( self , * coords , color = "black" , outline = False , outline_color = "black" ) :
"""Draws a polygon from an list of co - ordinates
: param int * coords :
Pairs of x and y positions which make up the polygon .
: param str color :
The color of the shape . Defaults to ` " black " ` .
: param i... | return self . tk . create_polygon ( * coords , outline = utils . convert_color ( outline_color ) if outline else "" , width = int ( outline ) , fill = "" if color is None else utils . convert_color ( color ) ) |
def ispymodule ( self ) :
'''Check if this : class : ` Path ` is a python module .''' | if self . isdir ( ) :
return os . path . isfile ( os . path . join ( self , '__init__.py' ) )
elif self . isfile ( ) :
return self . endswith ( '.py' ) |
def validate ( cls , data ) :
"""Validate input data matches expected failure ` ` dict ` ` format .""" | try :
jsonschema . validate ( data , cls . SCHEMA , # See : https : / / github . com / Julian / jsonschema / issues / 148
types = { 'array' : ( list , tuple ) } )
except jsonschema . ValidationError as e :
raise InvalidFormat ( "Failure data not of the" " expected format: %s" % ( e . message ) )
else : # En... |
def slerp ( R1 , R2 , t1 , t2 , t_out ) :
"""Spherical linear interpolation of rotors
This function uses a simpler interface than the more fundamental
` slerp _ evaluate ` and ` slerp _ vectorized ` functions . The latter
are fast , being implemented at the C level , but take input ` tau `
instead of time .... | tau = ( t_out - t1 ) / ( t2 - t1 )
return np . slerp_vectorized ( R1 , R2 , tau ) |
def send_rpc_async ( self , conn_id , address , rpc_id , payload , timeout , callback ) :
"""Asynchronously send an RPC to this IOTile device
Args :
conn _ id ( int ) : A unique identifier that will refer to this connection
address ( int ) : the address of the tile that we wish to send the RPC to
rpc _ id (... | try :
context = self . conns . get_context ( conn_id )
except ArgumentError :
callback ( conn_id , self . id , False , "Could not find connection information" , 0xFF , bytearray ( ) )
return
self . conns . begin_operation ( conn_id , 'rpc' , callback , timeout )
topics = context [ 'topics' ]
encoded_payload... |
def fields ( self ) -> GraphQLFieldMap :
"""Get provided fields , wrapping them as GraphQLFields if needed .""" | try :
fields = resolve_thunk ( self . _fields )
except GraphQLError :
raise
except Exception as error :
raise TypeError ( f"{self.name} fields cannot be resolved: {error}" )
if not isinstance ( fields , dict ) or not all ( isinstance ( key , str ) for key in fields ) :
raise TypeError ( f"{self.name} fi... |
def scan_file ( path ) :
"""Scan ` path ` for viruses using ` ` clamscan ` ` program .
Args :
path ( str ) : Relative or absolute path of file / directory you need to
scan .
Returns :
dict : ` ` { filename : ( " FOUND " , " virus type " ) } ` ` or blank dict .
Raises :
AssertionError : When the intern... | path = os . path . abspath ( path )
assert os . path . exists ( path ) , "Unreachable file '%s'." % path
result = sh . clamscan ( path , no_summary = True , infected = True , _ok_code = [ 0 , 1 ] )
return _parse_result ( result ) |
def execute ( self , statement , params = ( ) ) :
"""execute sql statement . optionally you can give multiple statements
to save on cursor creation and closure""" | con = self . __con or self . connection
cur = self . __cur or con . cursor ( )
if isinstance ( statement , list ) == False : # we expect to receive instructions in list
statement = [ statement ]
params = [ params ]
for state , param in zip ( statement , params ) :
logger . debug ( "%s %s" % ( state , param ... |
def list_all_tax_rates ( cls , ** kwargs ) :
"""List TaxRates
Return a list of TaxRates
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . list _ all _ tax _ rates ( async = True )
> > > result = thread . get ( )
... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _list_all_tax_rates_with_http_info ( ** kwargs )
else :
( data ) = cls . _list_all_tax_rates_with_http_info ( ** kwargs )
return data |
def _extract_apis_from_function ( logical_id , function_resource , collector ) :
"""Fetches a list of APIs configured for this SAM Function resource .
Parameters
logical _ id : str
Logical ID of the resource
function _ resource : dict
Contents of the function resource including its properties
collector ... | resource_properties = function_resource . get ( "Properties" , { } )
serverless_function_events = resource_properties . get ( SamApiProvider . _FUNCTION_EVENT , { } )
SamApiProvider . _extract_apis_from_events ( logical_id , serverless_function_events , collector ) |
def get_header ( self , key ) :
"""Returns the requested header , or an empty string if the header is not set .
Keyword arguments :
key - - The header name . It will be canonicalized before use .""" | key = canonicalize_header ( key )
if key in self . header :
return self . header [ key ]
return '' |
def list_blocked_work_units ( self , work_spec_name , start = 0 , limit = None ) :
"""Get a dictionary of blocked work units for some work spec .
The dictionary is from work unit name to work unit definiton .
Work units included in this list are blocked because they were
listed as the first work unit in
: f... | return self . registry . filter ( WORK_UNITS_ + work_spec_name + _BLOCKED , start = start , limit = limit ) |
def _add_parameterized_validator_internal ( param_validator , base_tag ) :
"with builtin tag prefixing" | add_parameterized_validator ( param_validator , base_tag , tag_prefix = u'!~~%s(' % param_validator . __name__ ) |
def get_events ( self , event_title , regex = False ) :
"""Search for events with the provided title
Args :
event _ title : The title of the event
Returns :
An event JSON object returned from the server with the following :
" meta " : {
" limit " : 20 , " next " : null , " offset " : 0,
" previous " :... | regex_val = 0
if regex :
regex_val = 1
r = requests . get ( '{0}/events/?api_key={1}&username={2}&c-title=' '{3}®ex={4}' . format ( self . url , self . api_key , self . username , event_title , regex_val ) , verify = self . verify )
if r . status_code == 200 :
json_obj = json . loads ( r . text )
return ... |
def parse ( self , sheet_name = 0 , header = 0 , names = None , index_col = None , usecols = None , squeeze = False , converters = None , true_values = None , false_values = None , skiprows = None , nrows = None , na_values = None , parse_dates = False , date_parser = None , thousands = None , comment = None , skipfoot... | # Can ' t use _ deprecate _ kwarg since sheetname = None has a special meaning
if is_integer ( sheet_name ) and sheet_name == 0 and 'sheetname' in kwds :
warnings . warn ( "The `sheetname` keyword is deprecated, use " "`sheet_name` instead" , FutureWarning , stacklevel = 2 )
sheet_name = kwds . pop ( "sheetname... |
def get_token ( self ) :
"""Retrieves the token from the File System
: return dict or None : The token if exists , None otherwise""" | token = None
if self . token_path . exists ( ) :
with self . token_path . open ( 'r' ) as token_file :
token = self . token_constructor ( self . serializer . load ( token_file ) )
self . token = token
return token |
def translate_file_diff ( data ) :
"""Translates data where data [ " Type " ] = = " Diff " """ | diff = '\\FloatBarrier \section{Configuration}'
sections = data . get ( 'Data' )
for title , config in sections . items ( ) :
title = title . replace ( '_' , '\_' )
diff += ' \n \\subsection{$NAME}' . replace ( '$NAME' , title )
for opt , vals in config . items ( ) :
opt = opt . replace ( '_' , '\_'... |
def status ( self , reference_id , ** params ) :
"""Retrieves the current status of the voice call .
See https : / / developer . telesign . com / docs / voice - api for detailed API documentation .""" | return self . get ( VOICE_STATUS_RESOURCE . format ( reference_id = reference_id ) , ** params ) |
def dafgs ( n = 125 ) : # The 125 may be a hard set ,
# I got strange errors that occasionally happened without it
"""Return ( get ) the summary for the current array in the current DAF .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / dafgs _ c . html
: param n : Optional length... | retarray = stypes . emptyDoubleVector ( 125 )
# libspice . dafgs _ c ( ctypes . cast ( retarray , ctypes . POINTER ( ctypes . c _ double ) ) )
libspice . dafgs_c ( retarray )
return stypes . cVectorToPython ( retarray ) [ 0 : n ] |
def sas_logical_jbod_attachments ( self ) :
"""Gets the SAS Logical JBOD Attachments client .
Returns :
SasLogicalJbodAttachments :""" | if not self . __sas_logical_jbod_attachments :
self . __sas_logical_jbod_attachments = SasLogicalJbodAttachments ( self . __connection )
return self . __sas_logical_jbod_attachments |
def maybe ( cls , val : Optional [ T ] ) -> 'Option[T]' :
"""Shortcut method to return ` ` Some ` ` or : py : data : ` NONE ` based on ` ` val ` ` .
Args :
val : Some value .
Returns :
` ` Some ( val ) ` ` if the ` ` val ` ` is not None , otherwise : py : data : ` NONE ` .
Examples :
> > > Option . mayb... | return cast ( 'Option[T]' , NONE ) if val is None else cls . Some ( val ) |
def format_tree ( tree ) :
"""Format a python tree structure
Given the python tree : :
tree = {
' node ' : [ ' ROOT ' , ' This is the root of the tree ' ] ,
' childs ' : [ {
' node ' : ' A1 ' ,
' childs ' : [ {
' node ' : ' B1 ' ,
' childs ' : [ {
' node ' : ' C1'
' node ' : ' B2'
' node ' : '... | def _traverse_tree ( tree , parents = None ) :
tree [ 'parents' ] = parents
childs = tree . get ( 'childs' , [ ] )
nb_childs = len ( childs )
for index , child in enumerate ( childs ) :
child_parents = list ( parents ) + [ index == nb_childs - 1 ]
tree [ 'childs' ] [ index ] = _traverse_... |
def analyze ( self , scratch , ** kwargs ) :
"""Run and return the results from the BlockCounts plugin .""" | file_blocks = Counter ( )
for script in self . iter_scripts ( scratch ) :
for name , _ , _ in self . iter_blocks ( script . blocks ) :
file_blocks [ name ] += 1
self . blocks . update ( file_blocks )
# Update the overall count
return { 'types' : file_blocks } |
def make_executable ( path , fatal = True ) :
""": param str | None path : chmod file with ' path ' as executable
: param bool | None fatal : Abort execution on failure if True
: return int : 1 if effectively done , 0 if no - op , - 1 on failure""" | if is_executable ( path ) :
return 0
if is_dryrun ( ) :
LOG . debug ( "Would make %s executable" , short ( path ) )
return 1
if not os . path . exists ( path ) :
return abort ( "%s does not exist, can't make it executable" , short ( path ) , fatal = ( fatal , - 1 ) )
try :
os . chmod ( path , 0o755 ... |
def close ( self ) :
"""Close the file , and for mode ' w ' , ' x ' and ' a ' write the ending
records .""" | if self . fp is None :
return
try :
if self . mode in ( 'w' , 'x' , 'a' ) and self . _didModify : # write ending records
with self . _lock :
if self . _seekable :
self . fp . seek ( self . start_dir )
self . _write_end_record ( )
finally :
fp = self . fp
s... |
def sync ( self , resolution , limit = None , ** kwargs ) :
"""Add current Music library section as sync item for specified device .
See description of : func : ` plexapi . library . LibrarySection . search ( ) ` for details about filtering / sorting and
: func : ` plexapi . library . LibrarySection . sync ( ) ... | from plexapi . sync import Policy , MediaSettings
kwargs [ 'mediaSettings' ] = MediaSettings . createPhoto ( resolution )
kwargs [ 'policy' ] = Policy . create ( limit )
return super ( PhotoSection , self ) . sync ( ** kwargs ) |
def inside ( self , other ) :
"""Return true if this rectangle is inside the given shape .""" | return ( self . left >= other . left and self . right <= other . right and self . top <= other . top and self . bottom >= other . bottom ) |
def delticks ( fig ) :
"""deletes half the x - axis tick marks
Parameters
_ _ _ _ _
fig : matplotlib figure number""" | locs = fig . xaxis . get_ticklocs ( )
nlocs = np . delete ( locs , list ( range ( 0 , len ( locs ) , 2 ) ) )
fig . set_xticks ( nlocs ) |
def unwrap ( self ) :
"""Returns a GLFWgammaramp object .""" | red = [ self . red [ i ] for i in range ( self . size ) ]
green = [ self . green [ i ] for i in range ( self . size ) ]
blue = [ self . blue [ i ] for i in range ( self . size ) ]
if NORMALIZE_GAMMA_RAMPS :
red = [ value / 65535.0 for value in red ]
green = [ value / 65535.0 for value in green ]
blue = [ va... |
def cmd_virustotal ( input , verbose ) :
"""Send a file to VirusTotal https : / / www . virustotal . com / and print the report in JSON format .
Note : Before send a file , will check if the file has been analyzed before ( sending the
sha256 of the file ) , if a report exists , no submission will be made , and ... | habucfg = loadcfg ( )
if 'VIRUSTOTAL_APIKEY' not in habucfg :
logging . error ( 'You must provide a virustotal apikey. Use the ~/.habu.json file (variable VIRUSTOTAL_APIKEY), or export the variable HABU_VIRUSTOTAL_APIKEY' )
sys . exit ( 1 )
if verbose :
logging . basicConfig ( level = logging . INFO , forma... |
def _Import ( self , t ) :
"""Handle " import xyz . foo " .""" | self . _fill ( "import " )
for i , ( name , asname ) in enumerate ( t . names ) :
if i != 0 :
self . _write ( ", " )
self . _write ( name )
if asname is not None :
self . _write ( " as " + asname ) |
def get_agent ( self , pool_id , agent_id , include_capabilities = None , include_assigned_request = None , include_last_completed_request = None , property_filters = None ) :
"""GetAgent .
[ Preview API ] Get information about an agent .
: param int pool _ id : The agent pool containing the agent
: param int... | route_values = { }
if pool_id is not None :
route_values [ 'poolId' ] = self . _serialize . url ( 'pool_id' , pool_id , 'int' )
if agent_id is not None :
route_values [ 'agentId' ] = self . _serialize . url ( 'agent_id' , agent_id , 'int' )
query_parameters = { }
if include_capabilities is not None :
query_... |
def random_codons ( peptide , frequency_cutoff = 0.0 , weighted = False , table = None ) :
'''Generate randomized codons given a peptide sequence .
: param peptide : Peptide sequence for which to generate randomized
codons .
: type peptide : coral . Peptide
: param frequency _ cutoff : Relative codon usage ... | if table is None :
table = CODON_FREQ_BY_AA [ 'sc' ]
# Process codon table using frequency _ cutoff
new_table = _cutoff ( table , frequency_cutoff )
# Select codons randomly or using weighted distribution
rna = ''
for amino_acid in str ( peptide ) :
codons = new_table [ amino_acid . upper ( ) ]
if not codon... |
def gerrymanderNodeFilenames ( self ) :
'''When creating nodes , the filename needs to be relative to ` ` conf . py ` ` , so it
will include ` ` self . root _ directory ` ` . However , when generating the API , the
file we are writing to is in the same directory as the generated node files so
we need to remov... | for node in self . all_nodes :
node . file_name = os . path . basename ( node . file_name )
if node . kind == "file" :
node . program_file = os . path . basename ( node . program_file ) |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : ConnectAppContext for this ConnectAppInstance
: rtype : twilio . rest . api . v2010 . account . connect _ app . ConnectApp... | if self . _context is None :
self . _context = ConnectAppContext ( self . _version , account_sid = self . _solution [ 'account_sid' ] , sid = self . _solution [ 'sid' ] , )
return self . _context |
def ToPhotlam ( self , wave , flux , ** kwargs ) :
"""Convert to ` ` photlam ` ` .
Since there is no real conversion necessary , this returns
a copy of input flux ( if array ) or just the input ( if scalar ) .
An input array is copied to avoid modifying the input
in subsequent * * pysynphot * * processing .... | if hasattr ( flux , 'copy' ) :
return flux . copy ( )
# No conversion , just copy the array .
else :
return flux |
def is_numeric_v_string_like ( a , b ) :
"""Check if we are comparing a string - like object to a numeric ndarray .
NumPy doesn ' t like to compare such objects , especially numeric arrays
and scalar string - likes .
Parameters
a : array - like , scalar
The first object to check .
b : array - like , sca... | is_a_array = isinstance ( a , np . ndarray )
is_b_array = isinstance ( b , np . ndarray )
is_a_numeric_array = is_a_array and is_numeric_dtype ( a )
is_b_numeric_array = is_b_array and is_numeric_dtype ( b )
is_a_string_array = is_a_array and is_string_like_dtype ( a )
is_b_string_array = is_b_array and is_string_like_... |
def _get_album ( self , directory ) :
"""Loads set name from SET _ FILE , looks up album _ id on fb ,
it it doesn ' t exists , creates album . Returns album id and album name""" | if not self . _connectToFB ( ) :
print ( "%s - Couldn't connect to fb" % ( directory ) )
return None , None
# Load sets from SET _ FILE
_sets = self . _load_sets ( directory )
# Only grab the first set , FB supports only one set per photo
myset = _sets [ 0 ]
logger . debug ( "Getting album id for %s" % ( myset ... |
def month_days ( year , month ) :
'''How many days are in a given month of a given year''' | if month > 13 :
raise ValueError ( "Incorrect month index" )
# First of all , dispose of fixed - length 29 day months
if month in ( IYYAR , TAMMUZ , ELUL , TEVETH , VEADAR ) :
return 29
# If it ' s not a leap year , Adar has 29 days
if month == ADAR and not leap ( year ) :
return 29
# If it ' s Heshvan , da... |
def separate_words ( text , min_word_return_size ) :
"""Utility function to return a list of all words that are have a length greater than a specified number of characters .
@ param text The text that must be split in to words .
@ param min _ word _ return _ size The minimum no of characters a word must have to... | splitter = re . compile ( '[^a-zA-Z0-9_\\+\\-/]' )
words = [ ]
for single_word in splitter . split ( text ) :
current_word = single_word . strip ( ) . lower ( )
# leave numbers in phrase , but don ' t count as words , since they tend to invalidate scores of their phrases
if len ( current_word ) > min_word_r... |
def map ( coro , iterable , limit = 0 , loop = None , timeout = None , return_exceptions = False , * args , ** kw ) :
"""Concurrently maps values yielded from an iterable , passing then
into an asynchronous coroutine function .
Mapped values will be returned as list .
Items order will be preserved based on or... | # Call each iterable but collecting yielded values
return ( yield from each ( coro , iterable , limit = limit , loop = loop , timeout = timeout , collect = True , return_exceptions = return_exceptions ) ) |
def _build_ssl_context ( cls , session : AppSession ) -> ssl . SSLContext :
'''Create the SSL options .
The options must be accepted by the ` ssl ` module .''' | args = session . args
# Logic is based on tornado . netutil . ssl _ options _ to _ context
ssl_context = ssl . SSLContext ( args . secure_protocol )
if args . check_certificate :
ssl_context . verify_mode = ssl . CERT_REQUIRED
cls . _load_ca_certs ( session )
ssl_context . load_verify_locations ( session . ... |
def run ( self ) :
'''Running the workbench CLI''' | # Announce versions
self . versions ( )
# Sample / Tag info and Help
self . tags ( )
print '\n%s' % self . workbench . help ( 'cli' )
# Now that we have the Workbench connection spun up , we register some stuff
# with the embedded IPython interpreter and than spin it up
# cfg = IPython . config . loader . Config ( )
cf... |
async def copy_to ( self , dest , container , buffering = True ) :
"""Coroutine method to copy content from this stream to another stream .""" | if self . eof :
await dest . write ( u'' if self . isunicode else b'' , True )
elif self . errored :
await dest . error ( container )
else :
try :
while not self . eof :
await self . prepareRead ( container )
data = self . readonce ( )
try :
await ... |
def get_url_for_get ( url , parameters = None ) : # type : ( str , Optional [ Dict ] ) - > str
"""Get full url for GET request including parameters
Args :
url ( str ) : URL to download
parameters ( Optional [ Dict ] ) : Parameters to pass . Defaults to None .
Returns :
str : Full url""" | spliturl = urlsplit ( url )
getparams = OrderedDict ( parse_qsl ( spliturl . query ) )
if parameters is not None :
getparams . update ( parameters )
spliturl = spliturl . _replace ( query = urlencode ( getparams ) )
return urlunsplit ( spliturl ) |
def run_tasks ( self ) :
'''Runs all assigned task in separate green threads . If the task should not be run , schedule it''' | pool = Pool ( len ( self . tasks ) )
for task in self . tasks : # Launch a green thread to schedule the task
# A task will be managed by 2 green thread : execution thread and scheduling thread
pool . spawn ( self . run , task )
return pool |
def _write_crmod_file ( filename ) :
"""Write a valid crmod configuration file to filename .
TODO : Modify configuration according to , e . g . , 2D""" | crmod_lines = [ '***FILES***' , '../grid/elem.dat' , '../grid/elec.dat' , '../rho/rho.dat' , '../config/config.dat' , 'F ! potentials ?' , '../mod/pot/pot.dat' , 'T ! measurements ?' , '../mod/volt.dat' , 'F ! sensitivities ?' , '../mod/sens/sens.dat' , 'F ! an... |
def _replace ( self , feature , cursor ) :
"""Insert a feature into the database .""" | try :
cursor . execute ( constants . _UPDATE , list ( feature . astuple ( ) ) + [ feature . id ] )
except sqlite3 . ProgrammingError :
cursor . execute ( constants . _INSERT , list ( feature . astuple ( self . default_encoding ) ) + [ feature . id ] ) |
def get_client ( self , name ) :
"""Like : meth : ` . get ` , but only mechanisms inheriting
: class : ` ClientMechanism ` will be returned .
Args :
name : The SASL mechanism name .
Returns :
The mechanism object or ` ` None ` `""" | mech = self . get ( name )
return mech if isinstance ( mech , ClientMechanism ) else None |
def _normal_model ( self , beta ) :
"""Creates the structure of the model ( model matrices etc ) for
a Normal family ARIMA model .
Parameters
beta : np . ndarray
Contains untransformed starting values for the latent variables
Returns
mu : np . ndarray
Contains the predicted values ( location ) for the... | Y = np . array ( self . data [ self . max_lag : ] )
# Transform latent variables
z = np . array ( [ self . latent_variables . z_list [ k ] . prior . transform ( beta [ k ] ) for k in range ( beta . shape [ 0 ] ) ] )
# Constant and AR terms
if self . ar != 0 :
mu = np . matmul ( np . transpose ( self . X ) , z [ : -... |
def encoded_class ( block , offset = 0 ) :
"""predicate indicating whether a block of memory includes a magic number""" | if not block :
raise InvalidFileFormatNull
for key in __magicmap__ :
if block . find ( key , offset , offset + len ( key ) ) > - 1 :
return __magicmap__ [ key ]
raise InvalidFileFormat |
def initialize_unordered_bulk_op ( self , bypass_document_validation = False ) :
"""* * DEPRECATED * * - Initialize an unordered batch of write operations .
Operations will be performed on the server in arbitrary order ,
possibly in parallel . All operations will be attempted .
: Parameters :
- ` bypass _ d... | warnings . warn ( "initialize_unordered_bulk_op is deprecated" , DeprecationWarning , stacklevel = 2 )
return BulkOperationBuilder ( self , False , bypass_document_validation ) |
def run_simulation ( c1 , c2 ) :
"""using character and planet , run the simulation""" | print ( 'running simulation...' )
traits = character . CharacterCollection ( character . fldr )
c1 = traits . generate_random_character ( )
c2 = traits . generate_random_character ( )
print ( c1 )
print ( c2 )
rules = battle . BattleRules ( battle . rules_file )
b = battle . Battle ( c1 , c2 , traits , rules , print_co... |
def intersect_boxes ( box1 , box2 ) :
"""Takes two pyPdf boxes ( such as page . mediaBox ) and returns the pyPdf
box which is their intersection .""" | if not box1 and not box2 :
return None
if not box1 :
return box2
if not box2 :
return box1
intersect = RectangleObject ( [ 0 , 0 , 0 , 0 ] )
# Note [ llx , lly , urx , ury ] = = [ l , b , r , t ]
intersect . upperRight = ( min ( box1 . upperRight [ 0 ] , box2 . upperRight [ 0 ] ) , min ( box1 . upperRight [... |
def remove_isolated_nodes ( G ) :
"""Remove from a graph all the nodes that have no incident edges ( ie , node
degree = 0 ) .
Parameters
G : networkx multidigraph
the graph from which to remove nodes
Returns
networkx multidigraph""" | isolated_nodes = [ node for node , degree in dict ( G . degree ( ) ) . items ( ) if degree < 1 ]
G . remove_nodes_from ( isolated_nodes )
log ( 'Removed {:,} isolated nodes' . format ( len ( isolated_nodes ) ) )
return G |
def detectUbuntuTablet ( self ) :
"""Return detection of an Ubuntu Mobile OS tablet
Detects a tablet running the Ubuntu Mobile OS .""" | if UAgentInfo . deviceUbuntu in self . __userAgent and UAgentInfo . deviceTablet in self . __userAgent :
return True
return False |
def update ( self , url = values . unset , method = values . unset , status = values . unset , fallback_url = values . unset , fallback_method = values . unset , status_callback = values . unset , status_callback_method = values . unset ) :
"""Update the CallInstance
: param unicode url : The absolute URL that re... | data = values . of ( { 'Url' : url , 'Method' : method , 'Status' : status , 'FallbackUrl' : fallback_url , 'FallbackMethod' : fallback_method , 'StatusCallback' : status_callback , 'StatusCallbackMethod' : status_callback_method , } )
payload = self . _version . update ( 'POST' , self . _uri , data = data , )
return C... |
def check_attributes ( qpi ) :
"""Check QPimage attributes
Parameters
qpi : qpimage . core . QPImage
Raises
IntegrityCheckError
if the check fails""" | missing_attrs = [ ]
for key in DATA_KEYS :
if key not in qpi . meta :
missing_attrs . append ( key )
if missing_attrs :
msg = "Attributes are missing: {} " . format ( missing_attrs ) + "in {}!" . format ( qpi )
raise IntegrityCheckError ( msg ) |
def send_to_redshift ( instance , data , replace = True , batch_size = 1000 , types = None , primary_key = ( ) , create_boolean = False ) :
"""data = {
" table _ name " : ' name _ of _ the _ redshift _ schema ' + ' . ' + ' name _ of _ the _ redshift _ table ' # Must already exist ,
" columns _ name " : [ first ... | connection_kwargs = redshift_credentials . credential ( instance )
print ( "Initiate send_to_redshift..." )
print ( "Test to know if the table exists..." )
if ( not create . existing_test ( instance , data [ "table_name" ] ) ) or ( types is not None ) or ( primary_key != ( ) ) :
create_boolean = True
print ( "Test ... |
def _mysql_isval ( val ) :
"""These types should either be ignored or have already been
inserted into the SQL directly and dont need sqlalchemy to do
it for us .""" | if _mysql_is_list ( val ) :
return False
elif isinstance ( val , mysql_col ) :
return False
elif val in [ None , mysql_now , mysql_ignore ] :
return False
return True |
def hide_arp_holder_arp_entry_interfacename ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
hide_arp_holder = ET . SubElement ( config , "hide-arp-holder" , xmlns = "urn:brocade.com:mgmt:brocade-arp" )
arp_entry = ET . SubElement ( hide_arp_holder , "arp-entry" )
arp_ip_address_key = ET . SubElement ( arp_entry , "arp-ip-address" )
arp_ip_address_key . text = kwargs . pop ( ... |
def compute_absolute_error ( self , predicted_data , record , dataframe_record ) :
'''Calculate the absolute error for this case .''' | absolute_error = abs ( record [ 'DDG' ] - predicted_data [ self . ddg_analysis_type ] )
dataframe_record [ 'AbsoluteError' ] = absolute_error |
def scan ( self ) :
"""Analyze state and queue tasks .""" | log . debug ( "scanning machine: %s..." % self . name )
deployed = set ( )
services = yield self . client . get_children ( self . path + "/services" )
for name in services :
log . debug ( "checking service: '%s'..." % name )
try :
value , metadata = yield self . client . get ( self . path + "/services/"... |
def parseDtstart ( contentline , allowSignatureMismatch = False ) :
"""Convert a contentline ' s value into a date or date - time .
A variety of clients don ' t serialize dates with the appropriate VALUE
parameter , so rather than failing on these ( technically invalid ) lines ,
if allowSignatureMismatch is T... | tzinfo = getTzid ( getattr ( contentline , 'tzid_param' , None ) )
valueParam = getattr ( contentline , 'value_param' , 'DATE-TIME' ) . upper ( )
if valueParam == "DATE" :
return stringToDate ( contentline . value )
elif valueParam == "DATE-TIME" :
try :
return stringToDateTime ( contentline . value , t... |
def event_date ( self , event_date ) :
"""Set the Events " event date " value .""" | self . _group_data [ 'eventDate' ] = self . _utils . format_datetime ( event_date , date_format = '%Y-%m-%dT%H:%M:%SZ' ) |
def get_name_cost ( db , name ) :
"""Get the cost of a name , given the fully - qualified name .
Do so by finding the namespace it belongs to ( even if the namespace is being imported ) .
Return { ' amount ' : . . . , ' units ' : . . . } on success
Return None if the namespace has not been declared""" | lastblock = db . lastblock
namespace_id = get_namespace_from_name ( name )
if namespace_id is None or len ( namespace_id ) == 0 :
log . debug ( "No namespace '%s'" % namespace_id )
return None
namespace = db . get_namespace ( namespace_id )
if namespace is None : # maybe importing ?
log . debug ( "Namespace... |
def chunks ( self ) :
"""Block dimensions for this dataset ' s data or None if it ' s not a dask
array .""" | chunks = { }
for v in self . variables . values ( ) :
if v . chunks is not None :
for dim , c in zip ( v . dims , v . chunks ) :
if dim in chunks and c != chunks [ dim ] :
raise ValueError ( 'inconsistent chunks' )
chunks [ dim ] = c
return Frozen ( SortedKeysDict ( c... |
def create_payment ( self , request , amount , description = '' ) :
"""Dummy function for creating a payment through a payment gateway .
Should be overridden in gateway implementations .
Can be used for testing - to simulate a failed payment / error ,
pass ` error : true ` in the request data .""" | err = request . POST . get ( "error" , False )
if err :
raise PaymentError ( "Dummy error requested" )
return 'fake_transaction_id' |
def i2repr ( self , pkt , x ) : # type : ( Optional [ packet . Packet ] , int ) - > str
"""i2repr is overloaded to restrict the acceptable x values ( not None )
@ param packet . Packet | None pkt : the packet instance containing this field instance ; probably unused . # noqa : E501
@ param int x : the value to ... | return super ( UVarIntField , self ) . i2repr ( pkt , x ) |
def onresize ( self , emitter , width , height ) :
"""WebPage Event that occurs on webpage gets resized""" | super ( MyApp , self ) . onresize ( emitter , width , height ) |
async def on_raw_privmsg ( self , message ) :
"""PRIVMSG command .""" | nick , metadata = self . _parse_user ( message . source )
target , message = message . params
self . _sync_user ( nick , metadata )
await self . on_message ( target , nick , message )
if self . is_channel ( target ) :
await self . on_channel_message ( target , nick , message )
else :
await self . on_private_mes... |
def write_metadata ( self , output_path ) :
"""Build a JSON - LD dataset for LSST Projectmeta .
Parameters
output _ path : ` str `
File path where the ` ` metadata . jsonld ` ` should be written for the
build .""" | if self . _config . lsstdoc is None :
self . _logger . info ( 'No known LSST LaTeX source (--tex argument). ' 'Not writing a metadata.jsonld file.' )
return
# Build a JSON - LD dataset for the report + source repository .
product_data = ltdclient . get_product ( self . _config )
metadata = self . _config . lsst... |
def train ( self , data_iterator ) :
"""Train a keras model on a worker""" | optimizer = get_optimizer ( self . master_optimizer )
self . model = model_from_yaml ( self . yaml , self . custom_objects )
self . model . compile ( optimizer = optimizer , loss = self . master_loss , metrics = self . master_metrics )
self . model . set_weights ( self . parameters . value )
feature_iterator , label_it... |
def exponentiate_commuting_pauli_sum ( pauli_sum ) :
"""Returns a function that maps all substituent PauliTerms and sums them into a program . NOTE : Use
this function with care . Substituent PauliTerms should commute .
: param PauliSum pauli _ sum : PauliSum to exponentiate .
: returns : A function that para... | if not isinstance ( pauli_sum , PauliSum ) :
raise TypeError ( "Argument 'pauli_sum' must be a PauliSum." )
fns = [ exponential_map ( term ) for term in pauli_sum ]
def combined_exp_wrap ( param ) :
return Program ( [ f ( param ) for f in fns ] )
return combined_exp_wrap |
def accept ( self , deviceId , device ) :
"""Adds the named device to the store .
: param deviceId :
: param device :
: return :""" | storedDevice = self . devices . get ( deviceId )
if storedDevice is None :
logger . info ( 'Initialising device ' + deviceId )
storedDevice = Device ( self . maxAgeSeconds )
storedDevice . deviceId = deviceId
# this uses an async handler to decouple the recorder put ( of the data ) from the analyser han... |
def validate ( ref_time , ref_freqs , est_time , est_freqs ) :
"""Checks that the time and frequency inputs are well - formed .
Parameters
ref _ time : np . ndarray
reference time stamps in seconds
ref _ freqs : list of np . ndarray
reference frequencies in Hz
est _ time : np . ndarray
estimate time s... | util . validate_events ( ref_time , max_time = MAX_TIME )
util . validate_events ( est_time , max_time = MAX_TIME )
if ref_time . size == 0 :
warnings . warn ( "Reference times are empty." )
if ref_time . ndim != 1 :
raise ValueError ( "Reference times have invalid dimension" )
if len ( ref_freqs ) == 0 :
w... |
def _trim_zeros_complex ( str_complexes , na_rep = 'NaN' ) :
"""Separates the real and imaginary parts from the complex number , and
executes the _ trim _ zeros _ float method on each of those .""" | def separate_and_trim ( str_complex , na_rep ) :
num_arr = str_complex . split ( '+' )
return ( _trim_zeros_float ( [ num_arr [ 0 ] ] , na_rep ) + [ '+' ] + _trim_zeros_float ( [ num_arr [ 1 ] [ : - 1 ] ] , na_rep ) + [ 'j' ] )
return [ '' . join ( separate_and_trim ( x , na_rep ) ) for x in str_complexes ] |
def _clean_item ( self , item ) :
'''Cleans the item to be logged''' | item_copy = dict ( item )
del item_copy [ 'body' ]
del item_copy [ 'links' ]
del item_copy [ 'response_headers' ]
del item_copy [ 'request_headers' ]
del item_copy [ 'status_code' ]
del item_copy [ 'status_msg' ]
item_copy [ 'action' ] = 'ack'
item_copy [ 'logger' ] = self . logger . name
item_copy
return item_copy |
def taskinfo ( self ) :
"""Retrieve the Task Information""" | task_input = { 'taskName' : 'QueryTask' , 'inputParameters' : { "Task_Name" : self . _name } }
info = taskengine . execute ( task_input , self . _engine , cwd = self . _cwd )
task_def = info [ 'outputParameters' ] [ 'DEFINITION' ]
task_def [ 'name' ] = str ( task_def . pop ( 'NAME' ) )
task_def [ 'description' ] = str ... |
def build_sourcemap ( sources ) :
"""Similar to build _ headermap ( ) , but builds a dictionary of includes from
the " source " files ( i . e . " . c / . cc " files ) .""" | sourcemap = { }
for sfile in sources :
inc = find_includes ( sfile )
sourcemap [ sfile ] = set ( inc )
return sourcemap |
def text_fd_to_metric_families ( fd ) :
"""Parse Prometheus text format from a file descriptor .
This is a laxer parser than the main Go parser ,
so successful parsing does not imply that the parsed
text meets the specification .
Yields Metric ' s .""" | name = ''
documentation = ''
typ = 'untyped'
samples = [ ]
allowed_names = [ ]
def build_metric ( name , documentation , typ , samples ) : # Munge counters into OpenMetrics representation
# used internally .
if typ == 'counter' :
if name . endswith ( '_total' ) :
name = name [ : - 6 ]
el... |
async def create_connection ( address , * , db = None , password = None , ssl = None , encoding = None , parser = None , loop = None , timeout = None , connection_cls = None ) :
"""Creates redis connection .
Opens connection to Redis server specified by address argument .
Address argument can be one of the foll... | assert isinstance ( address , ( tuple , list , str ) ) , "tuple or str expected"
if isinstance ( address , str ) :
logger . debug ( "Parsing Redis URI %r" , address )
address , options = parse_url ( address )
db = options . setdefault ( 'db' , db )
password = options . setdefault ( 'password' , password... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.