signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def normalize ( self , normalizationLevel = "minute" , fusionMethod = "mean" , interpolationMethod = "linear" ) :
"""Normalizes the TimeSeries data points .
If this function is called , the TimeSeries gets ordered ascending
automatically . The new timestamps will represent the center of each time
bucket . Wit... | # do not normalize the TimeSeries if it is already normalized , either by
# definition or a prior call of normalize ( * )
if self . _normalizationLevel == normalizationLevel :
if self . _normalized : # pragma : no cover
return
# check if all parameters are defined correctly
if normalizationLevel not in Norm... |
def _groups_of_size ( iterable , n , fillvalue = None ) :
"""Collect data into fixed - length chunks or blocks .""" | # _ groups _ of _ size ( ' ABCDEFG ' , 3 , ' x ' ) - - > ABC DEF Gxx
args = [ iter ( iterable ) ] * n
return zip_longest ( fillvalue = fillvalue , * args ) |
def upload_directory_contents ( input_dict , environment_dict ) :
"""This function serves to upload every file in a user - supplied
source directory to all of the vessels in the current target group .
It essentially calls seash ' s ` upload ` function repeatedly , each
time with a file name taken from the sou... | # Check user input and seash state :
# 1 , Make sure there is an active user key .
if environment_dict [ "currentkeyname" ] is None :
raise seash_exceptions . UserError ( """Error: Please set an identity before using 'uploaddir'!
Example:
!> loadkeys your_user_name
!> as your_user_name
your_user_name@ !>
""" )
#... |
def order ( self , last ) :
'''Perform ordering with respect model fields .''' | desc = last . desc
field = last . name
nested = last . nested
nested_args = [ ]
while nested :
meta = nested . model . _meta
nested_args . extend ( ( self . backend . basekey ( meta ) , nested . name ) )
last = nested
nested = nested . nested
method = 'ALPHA' if last . field . internal_type == 'text' el... |
def upload ( self , fileobj , bucket , key , transfer_config = None , subscribers = None ) :
'''upload a file using Aspera''' | check_io_access ( fileobj , os . R_OK , True )
return self . _queue_task ( bucket , [ FilePair ( key , fileobj ) ] , transfer_config , subscribers , enumAsperaDirection . SEND ) |
def convertDict2Attrs ( self , * args , ** kwargs ) :
"""The trick for iterable Mambu Objects comes here :
You iterate over each element of the responded List from Mambu ,
and create a Mambu Group object for each one , initializing them
one at a time , and changing the attrs attribute ( which just
holds a l... | for n , c in enumerate ( self . attrs ) : # ok ok , I ' m modifying elements of a list while iterating it . BAD PRACTICE !
try :
params = self . params
except AttributeError as aerr :
params = { }
kwargs . update ( params )
try :
group = self . mambugroupclass ( urlfunc = None , ... |
def parseDate ( self , dateString , sourceTime = None ) :
"""Parse short - form date strings : :
'05/28/2006 ' or ' 04.21'
@ type dateString : string
@ param dateString : text to convert to a C { datetime }
@ type sourceTime : struct _ time
@ param sourceTime : C { struct _ time } value to use as the base... | if sourceTime is None :
yr , mth , dy , hr , mn , sec , wd , yd , isdst = time . localtime ( )
else :
yr , mth , dy , hr , mn , sec , wd , yd , isdst = sourceTime
# values pulled from regex ' s will be stored here and later
# assigned to mth , dy , yr based on information from the locale
# -1 is used as the mar... |
def makefile ( graph ) :
"""Format graph as Makefile .""" | from renku . models . provenance . activities import ProcessRun , WorkflowRun
for activity in graph . activities . values ( ) :
if not isinstance ( activity , ProcessRun ) :
continue
elif isinstance ( activity , WorkflowRun ) :
steps = activity . subprocesses . values ( )
else :
step... |
def load ( fname ) :
"""Loads symbol from a JSON file .
You can also use pickle to do the job if you only work on python .
The advantage of load / save is the file is language agnostic .
This means the file saved using save can be loaded by other language binding of mxnet .
You also get the benefit being ab... | if not isinstance ( fname , string_types ) :
raise TypeError ( 'fname need to be string' )
handle = SymbolHandle ( )
check_call ( _LIB . MXSymbolCreateFromFile ( c_str ( fname ) , ctypes . byref ( handle ) ) )
return Symbol ( handle ) |
def team_scores ( self , team_scores , time , show_datetime , use_12_hour_format ) :
"""Prints the teams scores in a pretty format""" | for score in team_scores [ "matches" ] :
if score [ "status" ] == "FINISHED" :
click . secho ( "%s\t" % score [ "utcDate" ] . split ( 'T' ) [ 0 ] , fg = self . colors . TIME , nl = False )
self . scores ( self . parse_result ( score ) )
elif show_datetime :
self . scores ( self . parse_r... |
def extract_bbox ( layers ) :
"""Returns a bounding box for ` ` layers ` ` or ( 0 , 0 , 0 , 0 ) if the layers
have no bounding box .""" | if not hasattr ( layers , '__iter__' ) :
layers = [ layers ]
bboxes = [ layer . bbox for layer in layers if layer . is_visible ( ) and not layer . bbox == ( 0 , 0 , 0 , 0 ) ]
if len ( bboxes ) == 0 : # Empty bounding box .
return ( 0 , 0 , 0 , 0 )
lefts , tops , rights , bottoms = zip ( * bboxes )
return ( min ... |
def create_public_ip ( access_token , subscription_id , resource_group , public_ip_name , dns_label , location ) :
'''Create a public ip address .
Args :
access _ token ( str ) : A valid Azure authentication token .
subscription _ id ( str ) : Azure subscription id .
resource _ group ( str ) : Azure resourc... | endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourceGroups/' , resource_group , '/providers/Microsoft.Network/publicIPAddresses/' , public_ip_name , '?api-version=' , NETWORK_API ] )
ip_body = { 'location' : location }
properties = { 'publicIPAllocationMethod' : 'Dynamic' }
pr... |
def _bounded_int_doc ( cls ) :
"""Add bounded int docstring template to class init .""" | def __init__ ( self , value = None , min = None , max = None , step = None , ** kwargs ) :
if value is not None :
kwargs [ 'value' ] = value
if min is not None :
kwargs [ 'min' ] = min
if max is not None :
kwargs [ 'max' ] = max
if step is not None :
kwargs [ 'step' ] = s... |
def convert_branch ( self , old_node , new_node , ids_to_skip , comment_dict = None ) :
"""Recursively walk a indicator logic tree , starting from a Indicator node .
Converts OpenIOC 1.1 Indicator / IndicatorItems to Openioc 1.0 and preserves order .
: param old _ node : An Indicator node , which we walk down t... | expected_tag = 'Indicator'
if old_node . tag != expected_tag :
raise DowngradeError ( 'old_node expected tag is [%s]' % expected_tag )
if not comment_dict :
comment_dict = { }
for node in old_node . getchildren ( ) :
node_id = node . get ( 'id' )
if node_id in ids_to_skip :
continue
if node ... |
def __launchThreads ( self , numThreads ) :
"""Launch some threads and start to process users .
: param numThreads : number of thrads to launch .
: type numThreads : int .""" | i = 0
while i < numThreads :
self . __logger . debug ( "Launching thread number " + str ( i ) )
i += 1
newThr = Thread ( target = self . __processUsers )
newThr . setDaemon ( True )
self . __threads . add ( newThr )
newThr . start ( ) |
def set_cookie ( self , cookie ) :
"""Set a cookie , without checking whether or not it should be set .""" | c = self . _cookies
self . _cookies_lock . acquire ( )
try :
if cookie . domain not in c :
c [ cookie . domain ] = { }
c2 = c [ cookie . domain ]
if cookie . path not in c2 :
c2 [ cookie . path ] = { }
c3 = c2 [ cookie . path ]
c3 [ cookie . name ] = cookie
finally :
self . _cook... |
def classifyplot_from_valfile ( val_file , outtype = "png" , title = None , size = None , samples = None , callers = None ) :
"""Create a plot from a summarized validation file .
Does new - style plotting of summarized metrics of
false negative rate and false discovery rate .
https : / / en . wikipedia . org ... | mpl . use ( 'Agg' , force = True )
df = pd . read_csv ( val_file )
grouped = df . groupby ( [ "sample" , "caller" , "vtype" ] )
df = grouped . apply ( _calculate_fnr_fdr )
df = df . reset_index ( )
if len ( df ) == 0 :
return [ ]
else :
out_file = "%s.%s" % ( os . path . splitext ( val_file ) [ 0 ] , outtype )
... |
def _make_sid_selector ( self , assets ) :
"""Build an indexer mapping ` ` self . sids ` ` to ` ` assets ` ` .
Parameters
assets : list [ int ]
List of assets requested by a caller of ` ` load _ raw _ arrays ` ` .
Returns
index : np . array [ int64]
Index array containing the index in ` ` self . sids ` ... | assets = np . array ( assets )
sid_selector = self . sids . searchsorted ( assets )
unknown = np . in1d ( assets , self . sids , invert = True )
sid_selector [ unknown ] = - 1
return sid_selector |
def com ( self ) :
"""the center of mass of the molecule""" | return ( self . coordinates * self . masses . reshape ( ( - 1 , 1 ) ) ) . sum ( axis = 0 ) / self . mass |
def entity_type_path ( cls , project , entity_type ) :
"""Return a fully - qualified entity _ type string .""" | return google . api_core . path_template . expand ( 'projects/{project}/agent/entityTypes/{entity_type}' , project = project , entity_type = entity_type , ) |
def get_template_parameters_file ( template_full_path ) :
"""Checks for existance of parameters file against supported suffixes and returns parameters file path if found
Args :
template _ full _ path : full filepath for template file
Returns :
filename of parameters file if it exists""" | for suffix in EFConfig . PARAMETER_FILE_SUFFIXES :
parameters_file = template_full_path . replace ( "/templates" , "/parameters" ) + suffix
if exists ( parameters_file ) :
return parameters_file
else :
continue
return None |
def get_dpi ( raise_error = True ) :
"""Get screen DPI from the OS
Parameters
raise _ error : bool
If True , raise an error if DPI could not be determined .
Returns
dpi : float
Dots per inch of the primary screen .""" | display = quartz . CGMainDisplayID ( )
mm = quartz . CGDisplayScreenSize ( display )
px = quartz . CGDisplayBounds ( display ) . size
return ( px . width / mm . width + px . height / mm . height ) * 0.5 * 25.4 |
def to_dataframe ( self , dtypes = None ) :
"""Create a : class : ` pandas . DataFrame ` of rows in the page .
This method requires the pandas libary to create a data frame and the
fastavro library to parse row blocks .
. . warning : :
DATETIME columns are not supported . They are currently parsed as
stri... | if pandas is None :
raise ImportError ( _PANDAS_REQUIRED )
if dtypes is None :
dtypes = { }
columns = collections . defaultdict ( list )
for row in self :
for column in row :
columns [ column ] . append ( row [ column ] )
for column in dtypes :
columns [ column ] = pandas . Series ( columns [ co... |
def write ( self , result , cr = True ) :
"""Shortcut for self . window ( ) . write _ feedback ( result ) call
: param result : same as feedback in : meth : ` WConsoleWindowProto . write _ feedback `
: param cr : same as cr in : meth : ` WConsoleWindowProto . write _ feedback `
: return : None""" | self . window ( ) . write_feedback ( result , cr = cr ) |
def run ( self , fig ) :
"""Run the exporter on the given figure
Parmeters
fig : matplotlib . Figure instance
The figure to export""" | # Calling savefig executes the draw ( ) command , putting elements
# in the correct place .
fig . savefig ( io . BytesIO ( ) , format = 'png' , dpi = fig . dpi )
if self . close_mpl :
import matplotlib . pyplot as plt
plt . close ( fig )
self . crawl_fig ( fig ) |
def request ( self , * args , ** kwargs ) -> XMLResponse :
"""Makes an HTTP Request , with mocked User – Agent headers .
Returns a class : ` HTTPResponse < HTTPResponse > ` .""" | # Convert Request object into HTTPRequest object .
r = super ( XMLSession , self ) . request ( * args , ** kwargs )
return XMLResponse . _from_response ( r ) |
def track_from_file ( file_object , filetype , timeout = DEFAULT_ASYNC_TIMEOUT , force_upload = False ) :
"""Create a track object from a file - like object .
NOTE : Does not create the detailed analysis for the Track . Call
Track . get _ analysis ( ) for that .
Args :
file _ object : a file - like Python o... | if not force_upload :
try : # Check if this file has already been uploaded .
# This is much faster than uploading .
md5 = hashlib . md5 ( file_object . read ( ) ) . hexdigest ( )
return track_from_md5 ( md5 )
except util . EchoNestAPIError : # Fall through to do a fresh upload .
pass... |
def _table_relabel ( table , substitutions , replacements = None ) :
"""Change table column names , otherwise leaving table unaltered
Parameters
substitutions
Returns
relabeled : TableExpr""" | if replacements is not None :
raise NotImplementedError
observed = set ( )
exprs = [ ]
for c in table . columns :
expr = table [ c ]
if c in substitutions :
expr = expr . name ( substitutions [ c ] )
observed . add ( c )
exprs . append ( expr )
for c in substitutions :
if c not in ob... |
def icon ( self ) :
"""Get QIcon from wrapper""" | if self . _icon is None :
self . _icon = QIcon ( self . pm ( ) )
return self . _icon |
def decode ( name , encoded_data = None , contents_pillar = None , encoding_type = 'base64' , checksum = 'md5' ) :
'''Decode an encoded file and write it to disk
. . versionadded : : 2016.3.0
name
Path of the file to be written .
encoded _ data
The encoded file . Either this option or ` ` contents _ pilla... | ret = { 'name' : name , 'changes' : { } , 'result' : False , 'comment' : '' }
if not ( encoded_data or contents_pillar ) :
raise CommandExecutionError ( "Specify either the 'encoded_data' or " "'contents_pillar' argument." )
elif encoded_data and contents_pillar :
raise CommandExecutionError ( "Specify only one... |
def dead_code_elimination ( node ) :
"""Perform a simple form of dead code elimination on a Python AST .
This method performs reaching definitions analysis on all function
definitions . It then looks for the definition of variables that are not used
elsewhere and removes those definitions .
This function ta... | to_remove = set ( def_ [ 1 ] for def_ in annotate . unused ( node ) if not isinstance ( def_ [ 1 ] , ( gast . arguments , gast . For ) ) )
for n in list ( to_remove ) :
for succ in gast . walk ( n ) :
if anno . getanno ( succ , 'push' , False ) :
to_remove . add ( anno . getanno ( succ , 'push' ... |
def is_probably_a_voice_vote ( self ) :
'''Guess whether this vote is a " voice vote " .''' | if '+voice_vote' in self :
return True
if '+vote_type' in self :
if self [ '+vote_type' ] == 'Voice' :
return True
if 'voice vote' in self [ 'motion' ] . lower ( ) :
return True
return False |
def compile_path ( self , path , write = True , package = None , * args , ** kwargs ) :
"""Compile a path and returns paths to compiled files .""" | path = fixpath ( path )
if not isinstance ( write , bool ) :
write = fixpath ( write )
if os . path . isfile ( path ) :
if package is None :
package = False
destpath = self . compile_file ( path , write , package , * args , ** kwargs )
return [ destpath ] if destpath is not None else [ ]
elif os... |
def health ( args ) :
"""Health FireCloud Server""" | r = fapi . health ( )
fapi . _check_response_code ( r , 200 )
return r . content |
def no_update_last_login ( ) :
"""Disconnect any signals to update _ last _ login ( ) for the scope of the context
manager , then restore .""" | kw = { 'receiver' : update_last_login }
kw_id = { 'receiver' : update_last_login , 'dispatch_uid' : 'update_last_login' }
was_connected = user_logged_in . disconnect ( ** kw )
was_connected_id = not was_connected and user_logged_in . disconnect ( ** kw_id )
yield
# Restore signal if needed
if was_connected :
user_l... |
def up ( ctx , instance_id ) :
"""Start EC2 instance""" | session = create_session ( ctx . obj [ 'AWS_PROFILE_NAME' ] )
ec2 = session . resource ( 'ec2' )
try :
instance = ec2 . Instance ( instance_id )
instance . start ( )
except botocore . exceptions . ClientError as e :
click . echo ( "Invalid instance ID {0} ({1})" . format ( instance_id , e ) , err = True )
... |
def _to_brightness ( self , brightness ) :
"""Step to a given brightness .
: param brightness : Get to this brightness .""" | self . _to_value ( self . _brightness , brightness , self . command_set . brightness_steps , self . _dimmer , self . _brighter ) |
def sort_card_indices ( cards , indices , ranks = None ) :
"""Sorts the given Deck indices by the given ranks . Must also supply the
` ` Stack ` ` , ` ` Deck ` ` , or ` ` list ` ` that the indices are from .
: arg cards :
The cards the indices are from . Can be a ` ` Stack ` ` , ` ` Deck ` ` , or
` ` list `... | ranks = ranks or DEFAULT_RANKS
if ranks . get ( "suits" ) :
indices = sorted ( indices , key = lambda x : ranks [ "suits" ] [ cards [ x ] . suit ] if cards [ x ] . suit != None else 0 )
if ranks . get ( "values" ) :
indices = sorted ( indices , key = lambda x : ranks [ "values" ] [ cards [ x ] . value ] )
retur... |
def get_distributed_session_creator ( server ) :
"""Args :
server ( tf . train . Server ) :
Returns :
tf . train . SessionCreator""" | server_def = server . server_def
is_chief = ( server_def . job_name == 'worker' ) and ( server_def . task_index == 0 )
init_op = tf . global_variables_initializer ( )
local_init_op = tf . local_variables_initializer ( )
ready_op = tf . report_uninitialized_variables ( )
ready_for_local_init_op = tf . report_uninitializ... |
def match ( self , value , ignorecase = False ) :
"""Construct a regexp match ( ` ` ~ ` ` ) filter . Combine with ` ` not _ ` ` method to construct a negative regexp match ( ` ` ! ~ ` ` ) filter .
: param value : Filter value
: param ignorecase : If bool ` True ` , make match case insensitive ( ` ` ~ * ` ` , ` ... | if not ignorecase :
self . op = '~'
self . negate_op = '!~'
else :
self . op = '~*'
self . negate_op = '!~*'
self . value = self . _value ( value )
return self |
def create_parser ( ) :
"""Create the argument parser for iotile .""" | parser = argparse . ArgumentParser ( description = DESCRIPTION , formatter_class = argparse . RawDescriptionHelpFormatter )
parser . add_argument ( '-v' , '--verbose' , action = "count" , default = 0 , help = "Increase logging level (goes error, warn, info, debug)" )
parser . add_argument ( '-l' , '--logfile' , help = ... |
def get_request_data ( request = None ) :
"""Get request header / form data
A typical request behind NGINX looks like this :
' CONNECTION _ TYPE ' : ' close ' ,
' CONTENT _ LENGTH ' : ' 52 ' ,
' CONTENT _ TYPE ' : ' application / x - www - form - urlencoded ; charset = UTF - 8 ' ,
' GATEWAY _ INTERFACE ' ... | # noqa
if request is None : # get the request
request = api . get_request ( )
# Happens in the test runner
if not request :
return { }
# Try to obtain the real IP address of the client
forwarded_for = request . get_header ( "X_FORWARDED_FOR" )
real_ip = request . get_header ( "X_REAL_IP" )
remote_address = requ... |
def get_elections ( self , obj ) :
"""All elections in division .""" | election_day = ElectionDay . objects . get ( date = self . context [ 'election_date' ] )
elections = list ( obj . elections . filter ( election_day = election_day ) )
district = DivisionLevel . objects . get ( name = DivisionLevel . DISTRICT )
for district in obj . children . filter ( level = district ) :
elections... |
def export_start_event ( bpmn_graph , export_elements , node , nodes_classification , order = 0 , prefix = "" , condition = "" , who = "" ) :
"""Start event export
: param bpmn _ graph : an instance of BpmnDiagramGraph class ,
: param export _ elements : a dictionary object . The key is a node ID , value is a d... | # Assuming that there is only one event definition
event_definitions = node [ 1 ] . get ( consts . Consts . event_definitions )
if event_definitions is not None and len ( event_definitions ) > 0 :
event_definition = node [ 1 ] [ consts . Consts . event_definitions ] [ 0 ]
else :
event_definition = None
if event... |
def swo_enable ( self , cpu_speed , swo_speed = 9600 , port_mask = 0x01 ) :
"""Enables SWO output on the target device .
Configures the output protocol , the SWO output speed , and enables any
ITM & stimulus ports .
This is equivalent to calling ` ` . swo _ start ( ) ` ` .
Note :
If SWO is already enabled... | if self . swo_enabled ( ) :
self . swo_stop ( )
res = self . _dll . JLINKARM_SWO_EnableTarget ( cpu_speed , swo_speed , enums . JLinkSWOInterfaces . UART , port_mask )
if res != 0 :
raise errors . JLinkException ( res )
self . _swo_enabled = True
return None |
def compute_dominance_frontier ( graph , domtree ) :
"""Compute a dominance frontier based on the given post - dominator tree .
This implementation is based on figure 2 of paper An Efficient Method of Computing Static Single Assignment
Form by Ron Cytron , etc .
: param graph : The graph where we want to comp... | df = { }
# Perform a post - order search on the dominator tree
for x in networkx . dfs_postorder_nodes ( domtree ) :
if x not in graph : # Skip nodes that are not in the graph
continue
df [ x ] = set ( )
# local set
for y in graph . successors ( x ) :
if x not in domtree . predecessors (... |
def _deserialize_default ( cls , cls_target , obj_raw ) :
""": type cls _ target : T | type
: type obj _ raw : int | str | bool | float | list | dict | None
: rtype : T""" | if cls . _is_deserialized ( cls_target , obj_raw ) :
return obj_raw
elif type ( obj_raw ) == dict :
return cls . _deserialize_dict ( cls_target , obj_raw )
else :
return cls_target ( obj_raw ) |
def difference ( self , boolean_switches ) :
"""[ COMPATIBILITY ]
Make a copy of the current instance , and then discard all options that are in boolean _ switches .
: param set boolean _ switches : A collection of Boolean switches to disable .
: return : A new SimStateOptions instance .""" | ops = SimStateOptions ( self )
for key in boolean_switches :
ops . discard ( key )
return ops |
def _ancestors ( self , qname : Union [ QualName , bool ] = None ) -> List [ InstanceNode ] :
"""XPath - return the list of receiver ' s ancestors .""" | return self . up ( ) . _ancestors ( qname ) |
def _get_buffered_response ( self ) :
"""Returns a buffered response
: return : Buffered response""" | response = self . _get_response ( )
if response . request . method == 'DELETE' and response . status_code == 204 :
return [ { 'status' : 'record deleted' } ] , 1
result = self . _response . json ( ) . get ( 'result' , None )
if result is None :
raise MissingResult ( 'The expected `result` key was missing in the... |
def _webdav_move_copy ( self , remote_path_source , remote_path_target , operation ) :
"""Copies or moves a remote file or directory
: param remote _ path _ source : source file or folder to copy / move
: param remote _ path _ target : target file to which to copy / move
: param operation : MOVE or COPY
: r... | if operation != "MOVE" and operation != "COPY" :
return False
if remote_path_target [ - 1 ] == '/' :
remote_path_target += os . path . basename ( remote_path_source )
if not ( remote_path_target [ 0 ] == '/' ) :
remote_path_target = '/' + remote_path_target
remote_path_source = self . _normalize_path ( remo... |
def unique ( seen , * iterables ) :
"""Get the unique items in iterables while preserving order . Note that this
mutates the seen set provided only when the returned generator is used .
Args :
seen ( set ) : either an empty set , or the set of things already seen
* iterables : one or more iterable lists to ... | _add = seen . add
# return a generator of the unique items and the set of the seen items
# the seen set will mutate when the generator is iterated over
return ( i for i in chain ( * iterables ) if i not in seen and not _add ( i ) ) |
def offset_to_window ( self , off_x , off_y ) :
"""Convert data offset to window coordinates .
Parameters
off _ x , off _ y : float or ndarray
Data offsets .
Returns
coord : tuple
Offset in window coordinates in the form of ` ` ( x , y ) ` ` .""" | arr_pts = np . asarray ( ( off_x , off_y ) ) . T
return self . tform [ 'cartesian_to_native' ] . to_ ( arr_pts ) . T [ : 2 ] |
def discounted_return ( reward , length , discount ) :
"""Discounted Monte - Carlo returns .""" | timestep = tf . range ( reward . shape [ 1 ] . value )
mask = tf . cast ( timestep [ None , : ] < length [ : , None ] , tf . float32 )
return_ = tf . reverse ( tf . transpose ( tf . scan ( lambda agg , cur : cur + discount * agg , tf . transpose ( tf . reverse ( mask * reward , [ 1 ] ) , [ 1 , 0 ] ) , tf . zeros_like (... |
def get_mapping_client ( self , max_concurrency = 64 , auto_batch = None ) :
"""Returns a thread unsafe mapping client . This client works
similar to a redis pipeline and returns eventual result objects .
It needs to be joined on to work properly . Instead of using this
directly you shold use the : meth : ` m... | if auto_batch is None :
auto_batch = self . auto_batch
return MappingClient ( connection_pool = self . connection_pool , max_concurrency = max_concurrency , auto_batch = auto_batch ) |
def infer_schema ( environment , start_response , headers ) :
"""Return the inferred schema of the requested stream .
POST body should contain a JSON encoded version of :
{ stream : stream _ name ,
namespace : namespace _ name ( optional )""" | stream = environment [ 'json' ] [ 'stream' ]
namespace = environment [ 'json' ] . get ( 'namespace' ) or settings . default_namespace
start_response ( '200 OK' , headers )
schema = _infer_schema ( namespace , stream )
response = { 'stream' : stream , 'namespace' : namespace , 'schema' : schema , SUCCESS_FIELD : True }
... |
def create ( self , image , command = None , ** kwargs ) :
"""Create a container without starting it . Similar to ` ` docker create ` ` .
Takes the same arguments as : py : meth : ` run ` , except for ` ` stdout ` ` ,
` ` stderr ` ` , and ` ` remove ` ` .
Returns :
A : py : class : ` Container ` object .
... | if isinstance ( image , Image ) :
image = image . id
kwargs [ 'image' ] = image
kwargs [ 'command' ] = command
kwargs [ 'version' ] = self . client . api . _version
create_kwargs = _create_container_args ( kwargs )
resp = self . client . api . create_container ( ** create_kwargs )
return self . get ( resp [ 'Id' ] ... |
def _get_config ( self , i ) :
"""Get the config .
: type i : cleo . inputs . input . Input
: rtype : dict""" | variables = { }
if not i . get_option ( 'config' ) :
raise Exception ( 'The --config|-c option is missing.' )
with open ( i . get_option ( 'config' ) ) as fh :
exec ( fh . read ( ) , { } , variables )
return variables [ 'DATABASES' ] |
def QA_fetch_get_macroindex_list ( ip = None , port = None ) :
"""宏观指标列表
Keyword Arguments :
ip { [ type ] } - - [ description ] ( default : { None } )
port { [ type ] } - - [ description ] ( default : { None } )
38 10 宏观指标 HG""" | global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list ( ) if extension_market_list is None else extension_market_list
return extension_market_list . query ( 'market==38' ) |
def run_crbox ( self , spstring , form , output = "" , wavecat = "INDEF" , lowave = 0 , hiwave = 30000 ) :
"""Calcspec has a bug . We will use countrate instead , and force it
to use a box function of uniform transmission as the obsmode .""" | range = hiwave - lowave
midwave = range / 2.0
iraf . countrate ( spectrum = spstring , magnitude = "" , instrument = "box(%f,%f)" % ( midwave , range ) , form = form , wavecat = wavecat , output = output ) |
def incr ( self , key , incr_by = 1 ) :
"""Increment the key by the given amount .""" | return self . database . hincrby ( self . key , key , incr_by ) |
def fromrandom ( shape = ( 10 , 50 , 50 ) , npartitions = 1 , seed = 42 , engine = None ) :
"""Generate random image data .
Parameters
shape : tuple , optional , default = ( 10 , 50 , 50)
Dimensions of images .
npartitions : int , optional , default = 1
Number of partitions .
seed : int , optional , def... | seed = hash ( seed )
def generate ( v ) :
random . seed ( seed + v )
return random . randn ( * shape [ 1 : ] )
return fromlist ( range ( shape [ 0 ] ) , accessor = generate , npartitions = npartitions , engine = engine ) |
def comparator ( self , value ) :
"""sets the comparator ( with validation of input )""" | if not isinstance ( value , RangeCheckComparatorType ) :
raise AttributeError ( "%s comparator is invalid in RangeCheck." % ( value , ) )
self . _comparator = value |
def openImage ( filename , mode = 'readonly' , memmap = False , writefits = True , clobber = True , fitsname = None ) :
"""Opens file and returns PyFITS object . Works on both FITS and GEIS
formatted images .
Notes
If a GEIS or waivered FITS image is used as input , it will convert it to a
MEF object and on... | if not isinstance ( filename , fits . HDUList ) : # Insure that the filename is always fully expanded
# This will not affect filenames without paths or
# filenames specified with extensions .
filename = osfn ( filename )
# Extract the rootname and extension specification
# from input image name
_fname ,... |
def send_inline_bot_result ( self , chat_id : Union [ int , str ] , query_id : int , result_id : str , disable_notification : bool = None , reply_to_message_id : int = None , hide_via : bool = None ) :
"""Use this method to send an inline bot result .
Bot results can be retrieved using : obj : ` get _ inline _ bo... | return self . send ( functions . messages . SendInlineBotResult ( peer = self . resolve_peer ( chat_id ) , query_id = query_id , id = result_id , random_id = self . rnd_id ( ) , silent = disable_notification or None , reply_to_msg_id = reply_to_message_id , hide_via = hide_via or None ) ) |
def uuid ( self ) :
'''Universally unique identifier for an instance of a : class : ` Model ` .''' | pk = self . pkvalue ( )
if not pk :
raise self . DoesNotExist ( 'Object not saved. Cannot obtain universally unique id' )
return self . get_uuid ( pk ) |
def get_vector ( self , lr_motor : float , rr_motor : float , lf_motor : float , rf_motor : float ) -> typing . Tuple [ float , float ] :
""": param lr _ motor : Left rear motor value ( - 1 to 1 ) ; - 1 is forward
: param rr _ motor : Right rear motor value ( - 1 to 1 ) ; 1 is forward
: param lf _ motor : Left ... | if self . deadzone :
lf_motor = self . deadzone ( lf_motor )
lr_motor = self . deadzone ( lr_motor )
rf_motor = self . deadzone ( rf_motor )
rr_motor = self . deadzone ( rr_motor )
l = - ( lf_motor + lr_motor ) * 0.5 * self . speed
r = ( rf_motor + rr_motor ) * 0.5 * self . speed
# Motion equations
fwd ... |
def render_region ( widget = None , request = None , view = None , page = None , region = None ) :
"""returns rendered content
this is not too clear and little tricky ,
because external apps needs calling process method""" | # change the request
if not isinstance ( request , dict ) :
request . query_string = None
request . method = "GET"
if not hasattr ( request , '_feincms_extra_context' ) :
request . _feincms_extra_context = { }
leonardo_page = widget . parent if widget else page
render_region = widget . region if widget else... |
def sample_forward_transitions ( self , batch_size , batch_info , forward_steps : int , discount_factor : float ) -> Transitions :
"""Sample transitions from replay buffer with _ forward steps _ .
That is , instead of getting a transition s _ t - > s _ t + 1 with reward r ,
get a transition s _ t - > s _ t + n ... | probs , indexes , tree_idxs = self . backend . sample_batch_transitions ( batch_size , forward_steps )
return self . _get_transitions ( probs , indexes , tree_idxs , batch_info ) |
def get_plot ( self , normalize_rxn_coordinate = True , label_barrier = True ) :
"""Returns the NEB plot . Uses Henkelman ' s approach of spline fitting
each section of the reaction path based on tangent force and energies .
Args :
normalize _ rxn _ coordinate ( bool ) : Whether to normalize the
reaction co... | plt = pretty_plot ( 12 , 8 )
scale = 1 if not normalize_rxn_coordinate else 1 / self . r [ - 1 ]
x = np . arange ( 0 , np . max ( self . r ) , 0.01 )
y = self . spline ( x ) * 1000
relative_energies = self . energies - self . energies [ 0 ]
plt . plot ( self . r * scale , relative_energies * 1000 , 'ro' , x * scale , y... |
def consultar_status_operacional ( self ) :
"""Sobrepõe : meth : ` ~ satcfe . base . FuncoesSAT . consultar _ status _ operacional ` .
: return : Uma resposta SAT especializada em ` ` ConsultarStatusOperacional ` ` .
: rtype : satcfe . resposta . consultarstatusoperacional . RespostaConsultarStatusOperacional"... | resp = self . _http_post ( 'consultarstatusoperacional' )
conteudo = resp . json ( )
return RespostaConsultarStatusOperacional . analisar ( conteudo . get ( 'retorno' ) ) |
def _convert ( self , val ) :
"""Convert the type if necessary and return if a conversion happened .""" | if isinstance ( val , dict ) and not isinstance ( val , DotDict ) :
return DotDict ( val ) , True
elif isinstance ( val , list ) and not isinstance ( val , DotList ) :
return DotList ( val ) , True
return val , False |
def gelman_rubin ( chains , return_cdf = False ) :
"""Compute the Gelman - Rubin R - statistic from an ensemble of chains . ` chains `
is expected to have shape ` ( nsteps , nchains ) ` if samples are one dimensional ,
or ` ( nsteps , nchains , ndim ) ` if multidimensional . For multidimensional samples
R - s... | if len ( chains . shape ) > 2 :
results = [ gelman_rubin ( chains [ ... , param ] , return_cdf = return_cdf ) for param in range ( chains . shape [ - 1 ] ) ]
if return_cdf :
return zip ( * results )
else :
return results
nchains , nsteps = chains . shape [ 1 ] , chains . shape [ 0 ]
chain_me... |
def get_images ( self , results = 15 , start = 0 , license = None , cache = True ) :
"""Get a list of artist images
Args :
cache ( bool ) : A boolean indicating whether or not the cached value should be used ( if available ) . Defaults to True .
results ( int ) : An integer number of results to return
start... | if cache and ( 'images' in self . cache ) and results == 15 and start == 0 and license == None :
return self . cache [ 'images' ]
else :
response = self . get_attribute ( 'images' , results = results , start = start , license = license )
total = response . get ( 'total' ) or 0
if results == 15 and start... |
def motif4struct_bin ( A ) :
'''Structural motifs are patterns of local connectivity . Motif frequency
is the frequency of occurrence of motifs around a node .
Parameters
A : NxN np . ndarray
binary directed connection matrix
Returns
F : 199xN np . ndarray
motif frequency matrix
f : 199x1 np . ndarr... | from scipy import io
import os
fname = os . path . join ( os . path . dirname ( __file__ ) , motiflib )
mot = io . loadmat ( fname )
m4n = mot [ 'm4n' ]
id4 = mot [ 'id4' ] . squeeze ( )
n = len ( A )
f = np . zeros ( ( 199 , ) )
F = np . zeros ( ( 199 , n ) )
# frequency
A = binarize ( A , copy = True )
# ensure A is ... |
def month_interval ( year , month , milliseconds = False , return_string = False ) :
"""Return a start datetime and end datetime of a month .
: param milliseconds : Minimum time resolution .
: param return _ string : If you want string instead of datetime , set True
Usage Example : :
> > > start , end = rol... | if milliseconds : # pragma : no cover
delta = timedelta ( milliseconds = 1 )
else :
delta = timedelta ( seconds = 1 )
if month == 12 :
start = datetime ( year , month , 1 )
end = datetime ( year + 1 , 1 , 1 ) - delta
else :
start = datetime ( year , month , 1 )
end = datetime ( year , month + 1 ... |
def list_healthchecks ( self , service_id , version_number ) :
"""List all of the healthchecks for a particular service and version .""" | content = self . _fetch ( "/service/%s/version/%d/healthcheck" % ( service_id , version_number ) )
return map ( lambda x : FastlyHealthCheck ( self , x ) , content ) |
def get_levels_of_description ( self ) :
"""Returns an array of all levels of description defined in this Archivist ' s Toolkit instance .""" | if not hasattr ( self , "levels_of_description" ) :
cursor = self . db . cursor ( )
levels = set ( )
cursor . execute ( "SELECT distinct(resourceLevel) FROM Resources" )
for row in cursor :
levels . add ( row )
cursor . execute ( "SELECT distinct(resourceLevel) FROM ResourcesComponents" )
... |
def parse_quantization ( read_buffer , sqcd ) :
"""Tease out the quantization values .
Parameters
read _ buffer : sequence of bytes from the QCC and QCD segments .
Returns
tuple
Mantissa and exponents from quantization buffer .""" | numbytes = len ( read_buffer )
exponent = [ ]
mantissa = [ ]
if sqcd & 0x1f == 0 : # no quantization
data = struct . unpack ( '>' + 'B' * numbytes , read_buffer )
for j in range ( len ( data ) ) :
exponent . append ( data [ j ] >> 3 )
mantissa . append ( 0 )
else :
fmt = '>' + 'H' * int ( nu... |
def demean_forward_returns ( factor_data , grouper = None ) :
"""Convert forward returns to returns relative to mean
period wise all - universe or group returns .
group - wise normalization incorporates the assumption of a
group neutral portfolio constraint and thus allows allows the
factor to be evaluated ... | factor_data = factor_data . copy ( )
if not grouper :
grouper = factor_data . index . get_level_values ( 'date' )
cols = get_forward_returns_columns ( factor_data . columns )
factor_data [ cols ] = factor_data . groupby ( grouper ) [ cols ] . transform ( lambda x : x - x . mean ( ) )
return factor_data |
def ansi_c_quoting ( s ) :
'''shlex does not handle ANSI - C Quoting properly . Words of the form
$ ' string ' are treated specially . The word expands to string , with
backslash - escaped characters replaced as specified by the ANSI C
standard . This is a hacky workaround to parse these the way we want to .'... | in_single_quotes = False
in_double_quotes = False
maybe_ansi_c_quote = False
in_ansi_c_quote = False
to_del = [ ]
s = list ( s )
for index , ch in enumerate ( s ) :
if ch == '\'' :
if in_ansi_c_quote :
in_ansi_c_quote = toggle ( in_ansi_c_quote )
s [ index ] = '"'
else :
... |
def upgradeParentHook3to4 ( old ) :
"""Copy C { loginAccount } to C { subStore } and remove the installation marker .""" | new = old . upgradeVersion ( old . typeName , 3 , 4 , subStore = old . loginAccount )
uninstallFrom ( new , new . store )
return new |
def attach ( self , buffer , read_line = None ) :
"""Read buffer until end ( read ( ) returns ' ' ) and sends it to self . logger and self . job _ backend .
: param buffer : a buffer instance with block read ( ) or readline ( ) method
: param read _ line : callable or True to read line per line . If callable is... | bid = id ( buffer )
self . attach_last_messages [ bid ] = b''
def reader ( ) :
current_line = b''
def handle_line ( buf ) :
if chunk == b'' :
return
if read_line and callable ( read_line ) :
res = read_line ( buf )
if res is False :
return Fals... |
def record ( self ) : # type : ( ) - > bytes
'''A method to generate the string representing this UDF Terminating
Descriptor .
Parameters :
None .
Returns :
A string representing this UDF Terminating Descriptor .''' | if not self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'UDF Terminating Descriptor not initialized' )
rec = struct . pack ( self . FMT , b'\x00' * 16 , b'\x00' * 496 ) [ 16 : ]
return self . desc_tag . record ( rec ) + rec |
def send_command_return_multilines ( self , obj , command , * arguments ) :
"""Send command with no output .
: param obj : requested object .
: param command : command to send .
: param arguments : list of command arguments .
: return : list of command output lines .
: rtype : list ( str )""" | return self . _perform_command ( '{}/{}' . format ( self . session_url , obj . ref ) , command , OperReturnType . multiline_output , * arguments ) . json ( ) |
def scan_interface ( self , address ) :
"""Scan interface for Crazyflies""" | if self . _radio_manager is None :
try :
self . _radio_manager = _RadioManager ( 0 )
except Exception :
return [ ]
with self . _radio_manager as cradio : # FIXME : implements serial number in the Crazyradio driver !
serial = 'N/A'
logger . info ( 'v%s dongle with serial %s found' , cradi... |
def is_bgzf ( filename ) :
"""Pre : filename to test if it is a bgzf format
Post : True or False
: param filename :
: type filename : string
: return : if its a bgzf
: rtype : bool""" | with open ( filename , 'rb' ) as inf :
bytes1 = inf . read ( 12 )
if len ( bytes1 ) != 12 :
sys . stderr . write ( "File length ERROR\n" )
return False
try :
gzip_id1 , gzip_id2 , compression_method , flag , mtime , xfl , osval , xlen = struct . unpack ( '<BBBBIBBH' , bytes1 )
ex... |
def _dct_from_mro ( cls : type , attr_name : str ) -> dict :
"""" Get a merged dictionary from ` cls ` bases attribute ` attr _ name ` . MRO defines importance ( closest = strongest ) .""" | d = { }
for c in reversed ( cls . mro ( ) ) :
d . update ( getattr ( c , attr_name , { } ) )
return d |
def accept_moderator_invite ( self , subreddit ) :
"""Accept a moderator invite to the given subreddit .
Callable upon an instance of Subreddit with no arguments .
: returns : The json response from the server .""" | data = { 'r' : six . text_type ( subreddit ) }
# Clear moderated subreddits and cache
self . user . _mod_subs = None
# pylint : disable = W0212
self . evict ( self . config [ 'my_mod_subreddits' ] )
return self . request_json ( self . config [ 'accept_mod_invite' ] , data = data ) |
def get_revision ( cls , id , revision , api = None ) :
"""Get app revision .
: param id : App identifier .
: param revision : App revision
: param api : Api instance .
: return : App object .""" | api = api if api else cls . _API
extra = { 'resource' : cls . __name__ , 'query' : { 'id' : id , 'revision' : revision } }
logger . info ( 'Get revision' , extra = extra )
app = api . get ( url = cls . _URL [ 'get_revision' ] . format ( id = id , revision = revision ) ) . json ( )
return App ( api = api , ** app ) |
def get_actual_replica ( self , service_id : str ) -> str :
"""Get the actual replica level of a service .
Args :
service _ id ( str ) : docker swarm service id
Returns :
str , replicated level of the service""" | # Raise an exception if we are not a manager
if not self . _manager :
raise RuntimeError ( 'Only the Swarm manager node can retrieve ' 'replication level of the service' )
service_details = self . get_service_details ( service_id )
actual_replica = service_details [ "Spec" ] [ "Mode" ] [ "Replicated" ] [ "Replicas"... |
def show_zoning_enabled_configuration_output_enabled_configuration_cfg_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
show_zoning_enabled_configuration = ET . Element ( "show_zoning_enabled_configuration" )
config = show_zoning_enabled_configuration
output = ET . SubElement ( show_zoning_enabled_configuration , "output" )
enabled_configuration = ET . SubElement ( output , "enabled-configuration" )
cf... |
def create ( input_dataset , target , feature = None , validation_set = 'auto' , warm_start = 'auto' , batch_size = 256 , max_iterations = 100 , verbose = True ) :
"""Create a : class : ` DrawingClassifier ` model .
Parameters
dataset : SFrame
Input data . The columns named by the ` ` feature ` ` and ` ` targ... | import mxnet as _mx
from mxnet import autograd as _autograd
from . _model_architecture import Model as _Model
from . _sframe_loader import SFrameClassifierIter as _SFrameClassifierIter
from . . _mxnet import _mxnet_utils
start_time = _time . time ( )
accepted_values_for_warm_start = [ "auto" , "quickdraw_245_v0" , None... |
def run_fib_with_stats ( r ) :
"""Run Fibonacci generator r times .""" | for i in range ( r ) :
res = fib ( PythonInt ( FIB ) )
if RESULT != res :
raise ValueError ( "Expected %d, Got %d" % ( RESULT , res ) ) |
def _find_metadata_vars ( self , ds , refresh = False ) :
'''Returns a list of netCDF variable instances for those that are likely metadata variables
: param netCDF4 . Dataset ds : An open netCDF dataset
: param bool refresh : if refresh is set to True , the cache is
invalidated .
: rtype : list
: return ... | if self . _metadata_vars . get ( ds , None ) and refresh is False :
return self . _metadata_vars [ ds ]
self . _metadata_vars [ ds ] = [ ]
for name , var in ds . variables . items ( ) :
if name in self . _find_ancillary_vars ( ds ) or name in self . _find_coord_vars ( ds ) :
continue
if name in ( 'p... |
def secgroup_delete ( call = None , kwargs = None ) :
'''Deletes the given security group from OpenNebula . Either a name or a secgroup _ id
must be supplied .
. . versionadded : : 2016.3.0
name
The name of the security group to delete . Can be used instead of
` ` secgroup _ id ` ` .
secgroup _ id
The... | if call != 'function' :
raise SaltCloudSystemExit ( 'The secgroup_delete function must be called with -f or --function.' )
if kwargs is None :
kwargs = { }
name = kwargs . get ( 'name' , None )
secgroup_id = kwargs . get ( 'secgroup_id' , None )
if secgroup_id :
if name :
log . warning ( 'Both the \... |
def get_well ( self , uwi ) :
"""Returns a Well object identified by UWI
Args :
uwi ( string ) : the UWI string for the well .
Returns :
well""" | if uwi is None :
raise ValueError ( 'a UWI must be provided' )
matching_wells = [ w for w in self if w . uwi == uwi ]
return matching_wells [ 0 ] if len ( matching_wells ) >= 1 else None |
def _merge_values ( self , to_values , from_values ) :
"""Merges two dictionaries of values recursively . This is a very naive
implementation that expects the two dictionaries to be fairly similar
in structure .
@ param to _ values destination dictionary
@ param from _ values dictionary with values to copy"... | if from_values is not None :
for k , v in from_values . items ( ) :
if k in to_values and isinstance ( to_values [ k ] , dict ) :
self . _merge_values ( to_values [ k ] , v )
# merge
else :
to_values [ k ] = v
# replaces instead of merge
return to_valu... |
def tree2array ( tree , branches = None , selection = None , object_selection = None , start = None , stop = None , step = None , include_weight = False , weight_name = 'weight' , cache_size = - 1 ) :
"""Convert a tree into a numpy structured array .
Convert branches of strings and basic types such as bool , int ... | import ROOT
if not isinstance ( tree , ROOT . TTree ) :
raise TypeError ( "tree must be a ROOT.TTree" )
cobj = ROOT . AsCObject ( tree )
if isinstance ( branches , string_types ) : # single branch selected
flatten = branches
branches = [ branches ]
elif isinstance ( branches , tuple ) :
if len ( branche... |
def tgread_vector ( self ) :
"""Reads a vector ( a list ) of Telegram objects .""" | if 0x1cb5c415 != self . read_int ( signed = False ) :
raise RuntimeError ( 'Invalid constructor code, vector was expected' )
count = self . read_int ( )
return [ self . tgread_object ( ) for _ in range ( count ) ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.