signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def uuid_object ( title = "Reference" , description = "Select an object" , default = None , display = True ) :
"""Generates a regular expression controlled UUID field""" | uuid = { 'pattern' : '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{' '4}-[' 'a-fA-F0-9]{4}-[a-fA-F0-9]{12}$' , 'type' : 'string' , 'title' : title , 'description' : description , }
if not display :
uuid [ 'x-schema-form' ] = { 'condition' : "false" }
if default is not None :
uuid [ 'default' ] = default
return uu... |
def add_name ( self , name , lang = None ) :
"""Adds a new name variant to an author .
: param name : the name to be added
: param lang : the language of the name variant
: return : ` True ` if the name is added , ` False ` otherwise ( the name is a duplicate )""" | try :
assert ( lang , name ) not in self . get_names ( )
except Exception as e : # TODO : raise a custom exception
logger . warning ( "Duplicate name detected while adding \"%s (lang=%s)\"" % ( name , lang ) )
return False
newlabel = Literal ( name , lang = lang ) if lang is not None else Literal ( name )
n... |
def memoize_methodcalls ( func , pickle = False , dumps = pickle . dumps ) :
'''Cache the results of the function for each input it gets called with .''' | cache = func . _memoize_cache = { }
@ functools . wraps ( func )
def memoizer ( self , * args , ** kwargs ) :
if pickle :
key = dumps ( ( args , kwargs ) )
else :
key = args
if key not in cache :
cache [ key ] = func ( self , * args , ** kwargs )
return cache [ key ]
return memoi... |
def convert_predictions_to_image_summaries ( hook_args ) :
"""Optionally converts images from hooks _ args to image summaries .
Args :
hook _ args : DecodeHookArgs namedtuple
Returns :
summaries : list of tf . Summary values if hook _ args . decode _ hpara""" | decode_hparams = hook_args . decode_hparams
if not decode_hparams . display_decoded_images :
return [ ]
predictions = hook_args . predictions [ 0 ]
# Display ten random inputs and outputs so that tensorboard does not hang .
all_summaries = [ ]
rand_predictions = np . random . choice ( predictions , size = 10 )
for ... |
def log_likelihood_css ( self , y ) :
"""log likelihood based on conditional sum of squares
Source : http : / / www . nuffield . ox . ac . uk / economics / papers / 1997 / w6 / ma . pdf
Parameters
time series as a DenseVector
returns log likelihood as a double""" | likelihood = self . _jmodel . logLikelihoodCSS ( _py2java ( self . _ctx , y ) )
return _java2py ( self . _ctx , likelihood ) |
def use_color ( setting ) :
"""Choose whether to use color based on the command argument .
Args :
setting - Either ` auto ` , ` always ` , or ` never `""" | if setting not in COLOR_CHOICES :
raise InvalidColorSetting ( setting )
return ( setting == 'always' or ( setting == 'auto' and sys . stdout . isatty ( ) and terminal_supports_color ) ) |
def observable_method ( func , strategy = 'instances' ) :
"""I turn a method into something that can be observed by other callables .
You can use me as a decorator on a method , like this :
class Foo ( object ) :
_ _ init _ _ ( self , name ) :
self . name = name
@ observable _ method
def bar ( self , x ... | if strategy == 'instances' :
return ObservableMethodManager_PersistOnInstances ( func )
elif strategy == 'descriptor' :
return ObservableMethodManager_PersistOnDescriptor ( func )
else :
raise ValueError ( "Strategy %s not recognized" % ( strategy , ) ) |
def multiget ( self , pairs , ** params ) :
"""Fetches many keys in parallel via threads .
: param pairs : list of bucket _ type / bucket / key tuple triples
: type pairs : list
: param params : additional request flags , e . g . r , pr
: type params : dict
: rtype : list of : class : ` RiakObjects < riak... | if self . _multiget_pool :
params [ 'pool' ] = self . _multiget_pool
return riak . client . multi . multiget ( self , pairs , ** params ) |
def del_rules ( cls , * names , attr = None ) :
"""Delete algebraic rules used by : meth : ` create `
Remove the rules with the given ` names ` , or all rules if no names are
given
Args :
names ( str ) : Names of rules to delete
attr ( None or str ) : Name of the class attribute from which to
delete the... | if attr is None :
attr = cls . _rules_attr ( )
if len ( names ) == 0 :
getattr ( cls , attr )
# raise AttributeError if wrong attr
setattr ( cls , attr , OrderedDict ( ) )
else :
for name in names :
del getattr ( cls , attr ) [ name ] |
def randomBinaryField ( self ) :
"""Return random bytes format .""" | lst = [ b"hello world" , b"this is bytes" , b"awesome django" , b"djipsum is awesome" , b"\x00\x01\x02\x03\x04\x05\x06\x07" , b"\x0b\x0c\x0e\x0f" ]
return self . randomize ( lst ) |
def autoLayoutNodes ( self , nodes , padX = None , padY = None , direction = Qt . Horizontal , layout = 'Layered' , animate = 0 , centerOn = None , center = None , debug = False ) :
"""Automatically lays out all the nodes in the scene using the private autoLayoutNodes method .
: param nodes | [ < XNode > , . . ] ... | plugin = XNodeLayout . plugin ( layout )
if not plugin :
return 0
if not animate :
plugin . setTesting ( debug )
results = plugin . layout ( self , nodes , center , padX , padY , direction )
if centerOn :
self . mainView ( ) . centerOn ( centerOn )
return results
else :
anim_group = QPar... |
def get_state_change_with_balance_proof_by_balance_hash ( storage : sqlite . SQLiteStorage , canonical_identifier : CanonicalIdentifier , balance_hash : BalanceHash , sender : Address , ) -> sqlite . StateChangeRecord :
"""Returns the state change which contains the corresponding balance
proof .
Use this functi... | return storage . get_latest_state_change_by_data_field ( { 'balance_proof.canonical_identifier.chain_identifier' : str ( canonical_identifier . chain_identifier ) , 'balance_proof.canonical_identifier.token_network_address' : to_checksum_address ( canonical_identifier . token_network_address , ) , 'balance_proof.canoni... |
def draw ( self ) :
"""Draws the dragger at the current mouse location .
Should be called in every frame .""" | if not self . visible :
return
if self . isEnabled : # Draw the dragger ' s current appearance to the window .
if self . dragging :
self . window . blit ( self . surfaceDown , self . rect )
else : # mouse is up
if self . mouseOver :
self . window . blit ( self . surfaceOver , sel... |
def run ( self ) :
'''命令行交互程序''' | while ( True ) :
oiraw = cInput ( )
if ( len ( oiraw ) < 1 ) :
break
cutted = self . cut ( oiraw , text = True )
print ( cutted ) |
def operation ( self ) :
"""Extract operation if available ( lazy ) .
Operations : query , insert , update , remove , getmore , command""" | if not self . _operation_calculated :
self . _operation_calculated = True
self . _extract_operation_and_namespace ( )
return self . _operation |
def _parse_url ( url = None ) :
"""Split the path up into useful parts : bucket , obj _ key""" | if url is None :
return ( '' , '' )
scheme , netloc , path , _ , _ = parse . urlsplit ( url )
if scheme != 's3' :
raise InvalidURL ( url , "URL scheme must be s3://" )
if path and not netloc :
raise InvalidURL ( url )
return netloc , path [ 1 : ] |
def import_sip04_data ( data_filename ) :
"""Import RELEVANT data from the result files . Refer to the function
: func : ` reda . importers . sip04 . import _ sip04 _ data _ all ` for an importer that
imports ALL data .
Exported parameters :
key description
a First current electrode
b Second current ele... | df_all = import_sip04_data_all ( data_filename )
columns_to_keep = [ 'a' , 'b' , 'm' , 'n' , 'frequency' , 'Temp_1' , 'Temp_2' , 'Zm_1' , 'Zm_2' , 'Zm_3' , 'Zg_m' , 'zt' , 'Rs' , 'r' , 'rpha' , ]
df = df_all [ columns_to_keep ]
df = df . rename ( columns = { 'Rs' : 'ShuntResistance' , 'Zg_m' : 'ContactResistance' , 'Zm... |
def getEvents ( self , repo_user , repo_name , until_id = None ) :
"""Get all repository events , following paging , until the end
or until UNTIL _ ID is seen . Returns a Deferred .""" | done = False
page = 0
events = [ ]
while not done :
new_events = yield self . api . makeRequest ( [ 'repos' , repo_user , repo_name , 'events' ] , page )
# terminate if we find a matching ID
if new_events :
for event in new_events :
if event [ 'id' ] == until_id :
done = ... |
def read_mda ( attribute ) :
"""Read HDFEOS metadata and return a dict with all the key / value pairs .""" | lines = attribute . split ( '\n' )
mda = { }
current_dict = mda
path = [ ]
prev_line = None
for line in lines :
if not line :
continue
if line == 'END' :
break
if prev_line :
line = prev_line + line
key , val = line . split ( '=' )
key = key . strip ( )
val = val . strip ... |
def get_instance ( self , payload ) :
"""Build an instance of DocumentInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . preview . sync . service . document . DocumentInstance
: rtype : twilio . rest . preview . sync . service . document . DocumentInstance""" | return DocumentInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , ) |
def is_transition_matrix ( T , tol = 1e-10 ) :
"""Tests whether T is a transition matrix
Parameters
T : ndarray shape = ( n , n )
matrix to test
tol : float
tolerance to check with
Returns
Truth value : bool
True , if all elements are in interval [ 0 , 1]
and each row of T sums up to 1.
False , ... | if T . ndim != 2 :
return False
if T . shape [ 0 ] != T . shape [ 1 ] :
return False
dim = T . shape [ 0 ]
X = np . abs ( T ) - T
x = np . sum ( T , axis = 1 )
return np . abs ( x - np . ones ( dim ) ) . max ( ) < dim * tol and X . max ( ) < 2.0 * tol |
def save ( server_context , schema_name , query_name , domain , container_path = None ) : # type : ( ServerContext , str , str , Domain , str ) - > None
"""Saves the provided domain design
: param server _ context : A LabKey server context . See utils . create _ server _ context .
: param schema _ name : schema... | url = server_context . build_url ( 'property' , 'saveDomain.api' , container_path = container_path )
headers = { 'Content-Type' : 'application/json' }
payload = { 'domainDesign' : domain . to_json ( ) , 'queryName' : query_name , 'schemaName' : schema_name }
return server_context . make_request ( url , json_dumps ( pay... |
def _docker_machine_ssl_context ( ) :
"""Create a SSLContext object using DOCKER _ * env vars .""" | context = ssl . SSLContext ( ssl . PROTOCOL_TLS )
context . set_ciphers ( ssl . _RESTRICTED_SERVER_CIPHERS )
certs_path = os . environ . get ( "DOCKER_CERT_PATH" , None )
if certs_path is None :
raise ValueError ( "Cannot create ssl context, " "DOCKER_CERT_PATH is not set!" )
certs_path = Path ( certs_path )
contex... |
def permissions ( self ) :
"""Retrieve the permissions for this engine instance .
> > > from smc . core . engine import Engine
> > > engine = Engine ( ' myfirewall ' )
> > > for x in engine . permissions :
. . . print ( x )
AccessControlList ( name = ALL Elements )
AccessControlList ( name = ALL Firewal... | acl_list = list ( AccessControlList . objects . all ( ) )
def acl_map ( elem_href ) :
for elem in acl_list :
if elem . href == elem_href :
return elem
acls = self . make_request ( UnsupportedEngineFeature , resource = 'permissions' )
for acl in acls [ 'granted_access_control_list' ] :
yield ... |
def bind_addr ( self , value ) :
"""Set the interface on which to listen for connections .""" | if isinstance ( value , tuple ) and value [ 0 ] in ( '' , None ) : # Despite the socket module docs , using ' ' does not
# allow AI _ PASSIVE to work . Passing None instead
# returns ' 0.0.0.0 ' like we want . In other words :
# host AI _ PASSIVE result
# ' ' Y 192.168 . x . y
# ' ' N 192.168 . x . y
# None Y 0.0.0.0
#... |
def set_bind ( self ) :
"""Sets key bindings .""" | # Arrow keys and enter
self . bind ( '<Up>' , lambda e : self . on_key_press_repeat ( 'Up' ) )
self . bind ( '<Down>' , lambda e : self . on_key_press_repeat ( 'Down' ) )
self . bind ( '<Shift-Up>' , lambda e : self . on_key_press_repeat ( 'Shift-Up' ) )
self . bind ( '<Shift-Down>' , lambda e : self . on_key_press_rep... |
def render_to_string ( self , template , context = None , def_name = None , subdir = 'templates' ) :
'''App - specific render function that renders templates in the * current app * , attached to the request for convenience''' | template_adapter = self . get_template_loader ( subdir ) . get_template ( template )
return getattr ( template_adapter , 'render' ) ( context = context , request = self . request , def_name = def_name ) |
def update ( args ) :
"""cdstarcat update OID [ KEY = VALUE ] +
Update the metadata of an object .""" | with _catalog ( args ) as cat :
cat . update_metadata ( args . args [ 0 ] , dict ( [ arg . split ( '=' , 1 ) for arg in args . args [ 1 : ] ] ) ) |
def run_command ( self , data ) :
"""check the given command and send to the correct dispatcher""" | command = data . get ( "command" )
if self . debug :
self . py3_wrapper . log ( "Running remote command %s" % command )
if command == "refresh" :
self . refresh ( data )
elif command == "refresh_all" :
self . py3_wrapper . refresh_modules ( )
elif command == "click" :
self . click ( data ) |
def _r1r2_standard ( self , word , vowels ) :
"""Return the standard interpretations of the string regions R1 and R2.
R1 is the region after the first non - vowel following a vowel ,
or is the null region at the end of the word if there is no
such non - vowel .
R2 is the region after the first non - vowel f... | r1 = ""
r2 = ""
for i in range ( 1 , len ( word ) ) :
if word [ i ] not in vowels and word [ i - 1 ] in vowels :
r1 = word [ i + 1 : ]
break
for i in range ( 1 , len ( r1 ) ) :
if r1 [ i ] not in vowels and r1 [ i - 1 ] in vowels :
r2 = r1 [ i + 1 : ]
break
return ( r1 , r2 ) |
def returner ( ret ) :
'''Return data to a mysql server''' | # if a minion is returning a standalone job , get a jobid
if ret [ 'jid' ] == 'req' :
ret [ 'jid' ] = prep_jid ( nocache = ret . get ( 'nocache' , False ) )
save_load ( ret [ 'jid' ] , ret )
try :
with _get_serv ( ret , commit = True ) as cur :
sql = '''INSERT INTO `salt_returns`
... |
def run ( self , synchronous = True , ** kwargs ) :
"""Helper to run existing job template
: param synchronous : What should happen if the server returns an HTTP
202 ( accepted ) status code ? Wait for the task to complete if
` ` True ` ` . Immediately return the server ' s response otherwise .
: param kwar... | kwargs = kwargs . copy ( )
# shadow the passed - in kwargs
kwargs . update ( self . _server_config . get_client_kwargs ( ) )
if 'data' in kwargs :
if 'job_template_id' not in kwargs [ 'data' ] and 'feature' not in kwargs [ 'data' ] :
raise KeyError ( 'Provide either job_template_id or feature value' )
i... |
def show_raslog_output_show_all_raslog_number_of_entries ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
show_raslog = ET . Element ( "show_raslog" )
config = show_raslog
output = ET . SubElement ( show_raslog , "output" )
show_all_raslog = ET . SubElement ( output , "show-all-raslog" )
number_of_entries = ET . SubElement ( show_all_raslog , "number-of-entries" )
number_of_entries . text... |
def main ( ) :
"""% prog numbers1 . txt number2 . txt . . .
Print histogram of the data files . The data files contain one number per
line . If more than one file is inputted , the program will combine the
histograms into the same plot .""" | allowed_format = ( "emf" , "eps" , "pdf" , "png" , "ps" , "raw" , "rgba" , "svg" , "svgz" )
p = OptionParser ( main . __doc__ )
p . add_option ( "--skip" , default = 0 , type = "int" , help = "skip the first several lines [default: %default]" )
p . add_option ( "--col" , default = 0 , type = "int" , help = "Get the n-t... |
def system ( ** kwargs ) :
"""Generally , this will automatically be added to a newly initialized
: class : ` phoebe . frontend . bundle . Bundle `
: parameter * * kwargs : defaults for the values of any of the parameters
: return : a : class : ` phoebe . parameters . parameters . ParameterSet ` of all newly ... | params = [ ]
params += [ FloatParameter ( qualifier = 't0' , value = kwargs . get ( 't0' , 0.0 ) , default_unit = u . d , description = 'Time at which all values are provided' ) ]
# TODO : re - enable these once they ' re incorporated into orbits ( dynamics ) correctly .
params += [ FloatParameter ( qualifier = 'ra' , ... |
def init_pipette ( ) :
"""Finds pipettes attached to the robot currently and chooses the correct one
to add to the session .
: return : The pipette type and mount chosen for deck calibration""" | global session
pipette_info = set_current_mount ( session . adapter , session )
pipette = pipette_info [ 'pipette' ]
res = { }
if pipette :
session . current_model = pipette_info [ 'model' ]
if not feature_flags . use_protocol_api_v2 ( ) :
mount = pipette . mount
session . current_mount = mount
... |
def network_io_counters ( interface = None ) :
'''Return network I / O statistics .
CLI Example :
. . code - block : : bash
salt ' * ' ps . network _ io _ counters
salt ' * ' ps . network _ io _ counters interface = eth0''' | if not interface :
return dict ( psutil . net_io_counters ( ) . _asdict ( ) )
else :
stats = psutil . net_io_counters ( pernic = True )
if interface in stats :
return dict ( stats [ interface ] . _asdict ( ) )
else :
return False |
def update_keyjar ( keyjar ) :
"""Go through the whole key jar , key bundle by key bundle and update them one
by one .
: param keyjar : The key jar to update""" | for iss , kbl in keyjar . items ( ) :
for kb in kbl :
kb . update ( ) |
def featureServers ( self ) :
"""gets the hosting feature AGS Server""" | if self . urls == { } :
return { }
featuresUrls = self . urls [ 'urls' ] [ 'features' ]
if 'https' in featuresUrls :
res = featuresUrls [ 'https' ]
elif 'http' in featuresUrls :
res = featuresUrls [ 'http' ]
else :
return None
services = [ ]
for urlHost in res :
if self . isPortal :
services... |
def ensembl ( args ) :
"""% prog ensembl species
Retrieve genomes and annotations from ensembl FTP . Available species
listed below . Use comma to give a list of species to download . For example :
$ % prog ensembl danio _ rerio , gasterosteus _ aculeatus""" | p = OptionParser ( ensembl . __doc__ )
p . add_option ( "--version" , default = "75" , help = "Ensembl version [default: %default]" )
opts , args = p . parse_args ( args )
version = opts . version
url = "ftp://ftp.ensembl.org/pub/release-{0}/" . format ( version )
fasta_url = url + "fasta/"
valid_species = [ x for x in... |
def set_name_email ( configurator , question , answer ) :
'''prepare " Full Name " < email @ eg . com > " string''' | name = configurator . variables [ 'author.name' ]
configurator . variables [ 'author.name_email' ] = '"{0}" <{1}>' . format ( name , answer )
return answer |
def add_local_lb ( self , price_item_id , datacenter ) :
"""Creates a local load balancer in the specified data center .
: param int price _ item _ id : The price item ID for the load balancer
: param string datacenter : The datacenter to create the loadbalancer in
: returns : A dictionary containing the prod... | product_order = { 'complexType' : 'SoftLayer_Container_Product_Order_Network_' 'LoadBalancer' , 'quantity' : 1 , 'packageId' : 0 , "location" : self . _get_location ( datacenter ) , 'prices' : [ { 'id' : price_item_id } ] }
return self . client [ 'Product_Order' ] . placeOrder ( product_order ) |
def insert ( self , button ) :
"""Insert button to last row
: param button :
: return : self
: rtype : : obj : ` types . ReplyKeyboardMarkup `""" | if self . keyboard and len ( self . keyboard [ - 1 ] ) < self . row_width :
self . keyboard [ - 1 ] . append ( button )
else :
self . add ( button )
return self |
def select ( self , cmd , * args , ** kwargs ) :
"""Execute the SQL command and return the data rows as tuples""" | self . cursor . execute ( cmd , * args , ** kwargs )
return self . cursor . fetchall ( ) |
def difference_nested_tuples ( tuple1 , tuple2 ) :
"""This function calculates the differences between elements of two given nested tuples .
Examples :
difference _ nested _ tuples ( ( ( 1 , 3 ) , ( 4 , 5 ) , ( 2 , 9 ) , ( 1 , 10 ) ) , ( ( 6 , 7 ) , ( 3 , 9 ) , ( 1 , 1 ) , ( 7 , 3 ) ) )
- > ( ( - 5 , - 4 ) , ... | result = tuple ( ( tuple ( ( elem1 - elem2 ) for elem1 , elem2 in zip ( tup1 , tup2 ) ) ) for tup1 , tup2 in zip ( tuple1 , tuple2 ) )
return result |
def kill ( arg1 , arg2 ) :
"""Stops a proces that contains arg1 and is filtered by arg2""" | from subprocess import Popen , PIPE
# Wait until ready
t0 = time . time ( )
# Wait no more than these many seconds
time_out = 30
running = True
while running and time . time ( ) - t0 < time_out :
if os . name == 'nt' :
p = Popen ( 'tasklist | find "%s"' % arg1 , shell = True , stdin = PIPE , stdout = PIPE ,... |
def scatter_contour ( x , y , z , ncontours = 50 , colorbar = True , fig = None , ax = None , cmap = None , outfile = None ) :
"""Contour plot on scattered data ( x , y , z ) and
plots the positions of the points ( x , y ) on top .
Parameters
x : ndarray ( T )
x - coordinates
y : ndarray ( T )
y - coord... | _warn ( 'scatter_contour is deprected; use plot_contour instead' ' and manually add a scatter plot on top.' , DeprecationWarning )
ax = contour ( x , y , z , ncontours = ncontours , colorbar = colorbar , fig = fig , ax = ax , cmap = cmap )
# scatter points
ax . scatter ( x , y , marker = 'o' , c = 'b' , s = 5 )
# show ... |
def sendmess ( self , msgtype , payload , flags = 0 , size = 0 , offset = 0 , timeout = 0 ) :
"""retcode , data = sendmess ( msgtype , payload )
send generic message and returns retcode , data""" | # reuse last valid connection or create new
conn = self . conn or self . _new_connection ( )
# invalidate last connection
self . conn = None
flags |= self . flags
assert ( flags & FLG_PERSISTENCE )
ret , rflags , data = conn . req ( msgtype , payload , flags , size , offset , timeout )
if rflags & FLG_PERSISTENCE : # p... |
def convert_particle_units ( self , * args ) :
"""Will convert the units for the simulation ( i . e . convert G ) as well as the particles ' cartesian elements .
Must have set sim . units ahead of calling this function so REBOUND knows what units to convert from .
Parameters
3 strings corresponding to units o... | if self . python_unit_l == 0 or self . python_unit_m == 0 or self . python_unit_t == 0 :
raise AttributeError ( "Must set sim.units before calling convert_particle_units in order to know what units to convert from." )
new_l , new_t , new_m = check_units ( args )
for p in self . particles :
units_convert_particl... |
def slicenet_range1 ( ranged_hparams ) :
"""Small range of hyperparameters .""" | rhp = ranged_hparams
rhp . set_float ( "clip_grad_norm" , 1.0 , 10.0 , scale = rhp . LOG_SCALE )
rhp . set_float ( "learning_rate" , 0.02 , 1.0 , scale = rhp . LOG_SCALE )
rhp . set_float ( "optimizer_adam_beta2" , 0.995 , 0.998 )
rhp . set_float ( "weight_decay" , 1.0 , 5.0 ) |
def decode_offset_fetch_response ( cls , data ) :
"""Decode bytes to an OffsetFetchResponse
: param bytes data : bytes to decode""" | ( ( correlation_id , ) , cur ) = relative_unpack ( '>i' , data , 0 )
( ( num_topics , ) , cur ) = relative_unpack ( '>i' , data , cur )
for _i in range ( num_topics ) :
( topic , cur ) = read_short_ascii ( data , cur )
( ( num_partitions , ) , cur ) = relative_unpack ( '>i' , data , cur )
for _i in range ( ... |
def read ( self , stream ) :
"""Reads the topology from a stream or file .""" | def read_it ( stream ) :
bytes = stream . read ( )
transportIn = TMemoryBuffer ( bytes )
protocolIn = TBinaryProtocol . TBinaryProtocol ( transportIn )
topology = StormTopology ( )
topology . read ( protocolIn )
return topology
if isinstance ( stream , six . string_types ) :
with open ( stre... |
def eventFilter ( self , object , event ) :
"""Resizes this overlay as the widget resizes .
: param object | < QtCore . QObject >
event | < QtCore . QEvent >
: return < bool >""" | if object == self . parent ( ) and event . type ( ) == QtCore . QEvent . Resize :
self . resize ( event . size ( ) )
elif event . type ( ) == QtCore . QEvent . Close :
self . setResult ( 0 )
return False |
def _updateB ( oldB , B , W , degrees , damping , inds , backinds ) : # pragma : no cover
'''belief update function .''' | for j , d in enumerate ( degrees ) :
kk = inds [ j ]
bk = backinds [ j ]
if d == 0 :
B [ kk , bk ] = - np . inf
continue
belief = W [ kk , bk ] + W [ j ]
oldBj = oldB [ j ]
if d == oldBj . shape [ 0 ] :
bth = quickselect ( - oldBj , d - 1 )
bplus = - 1
else :
... |
def _set_range_common ( self , k_sugar , k_start , k_end , value ) :
"""Checks to see if the client - side convenience key is present , and if so
converts the sugar convenience key into its real server - side
equivalents .
: param string k _ sugar : The client - side convenience key
: param string k _ start... | if not isinstance ( value , ( list , tuple , _Unspec ) ) :
raise ArgumentError . pyexc ( "Range specification for {0} must be a list, tuple or UNSPEC" . format ( k_sugar ) )
if self . _user_options . get ( k_start , UNSPEC ) is not UNSPEC or ( self . _user_options . get ( k_end , UNSPEC ) is not UNSPEC ) :
rais... |
def cublasDsymm ( handle , side , uplo , m , n , alpha , A , lda , B , ldb , beta , C , ldc ) :
"""Matrix - matrix product for real symmetric matrix .""" | status = _libcublas . cublasDsymm_v2 ( handle , _CUBLAS_SIDE_MODE [ side ] , _CUBLAS_FILL_MODE [ uplo ] , m , n , ctypes . byref ( ctypes . c_double ( alpha ) ) , int ( A ) , lda , int ( B ) , ldb , ctypes . byref ( ctypes . c_double ( beta ) ) , int ( C ) , ldc )
cublasCheckStatus ( status ) |
def _fstring_parse ( s , i , level , parts , exprs ) :
"""Roughly Python / ast . c : fstring _ find _ literal _ and _ expr""" | while True :
i , parse_expr = _find_literal ( s , i , level , parts , exprs )
if i == len ( s ) or s [ i ] == '}' :
return i
if parse_expr :
i = _find_expr ( s , i , level , parts , exprs ) |
def get_config_string_option ( parser : ConfigParser , section : str , option : str , default : str = None ) -> str :
"""Retrieves a string value from a parser .
Args :
parser : instance of : class : ` ConfigParser `
section : section name within config file
option : option ( variable ) name within that sec... | if not parser . has_section ( section ) :
raise ValueError ( "config missing section: " + section )
return parser . get ( section , option , fallback = default ) |
def fit ( self , X , y , cost_mat ) :
"""Build a example - dependent cost - sensitive logistic regression from the training set ( X , y , cost _ mat )
Parameters
X : array - like of shape = [ n _ samples , n _ features ]
The input samples .
y : array indicator matrix
Ground truth ( correct ) labels .
co... | # TODO : Check input
n_features = X . shape [ 1 ]
if self . fit_intercept :
w0 = np . zeros ( n_features + 1 )
else :
w0 = np . zeros ( n_features )
if self . solver == 'ga' : # TODO : add n _ jobs
res = GeneticAlgorithmOptimizer ( _logistic_cost_loss , w0 . shape [ 0 ] , iters = self . max_iter , type_ = '... |
def get_response ( _code ) :
"""Return xx1x response for xx0x codes ( e . g . 0810 for 0800)""" | if _code :
code = str ( _code )
return code [ : - 2 ] + str ( int ( code [ - 2 : - 1 ] ) + 1 ) + code [ - 1 ]
else :
return None |
def global_matches ( self , text ) :
"""Compute matches when text is a simple name .
Return a list of all keywords , built - in functions and names currently
defined in self . namespace that match .""" | import keyword
matches = [ ]
seen = { "__builtins__" }
n = len ( text )
for word in keyword . kwlist :
if word [ : n ] == text :
seen . add ( word )
matches . append ( word )
for nspace in [ self . namespace , builtins . __dict__ ] :
for word , val in nspace . items ( ) :
if word [ : n ]... |
def _get_scalexy ( self , ims_width , ims_height ) :
"""Returns scale _ x , scale _ y for bitmap display""" | # Get cell attributes
cell_attributes = self . code_array . cell_attributes [ self . key ]
angle = cell_attributes [ "angle" ]
if abs ( angle ) == 90 :
scale_x = self . rect [ 3 ] / float ( ims_width )
scale_y = self . rect [ 2 ] / float ( ims_height )
else : # Normal case
scale_x = self . rect [ 2 ] / floa... |
def verifyChainFromCAPath ( self , capath , untrusted_file = None ) :
"""Does the same job as . verifyChainFromCAFile ( ) but using the list
of anchors in capath directory . The directory should ( only ) contain
certificates files in PEM format . As for . verifyChainFromCAFile ( ) ,
a list of untrusted certif... | try :
anchors = [ ]
for cafile in os . listdir ( capath ) :
anchors . append ( Cert ( open ( os . path . join ( capath , cafile ) , "rb" ) . read ( ) ) )
# noqa : E501
except Exception :
raise Exception ( "capath provided is not a valid cert path" )
untrusted = None
if untrusted_file :
t... |
def make_link ( title , url , blank = False ) :
"""Make a HTML link out of an URL .
Args :
title ( str ) : Text to show for the link .
url ( str ) : URL the link will point to .
blank ( bool ) : If True , appends target = _ blank , noopener and noreferrer to
the < a > element . Defaults to False .""" | attrs = 'href="%s"' % url
if blank :
attrs += ' target="_blank" rel="noopener noreferrer"'
return '<a %s>%s</a>' % ( attrs , title ) |
def append ( self , name , data ) :
"""Append ' data ' to the current node d _ data
This method appends ' data ' to the current contents in the
key named ' name ' . The append assumes that the operation
makes sense and that the data types can be appended to
each other .""" | b_OK = True
self . snode_current . d_data [ name ] = self . snode_current . d_data [ name ] + data
return b_OK |
def flush ( name , table = 'filter' , family = 'ipv4' , ** kwargs ) :
'''. . versionadded : : 2014.1.0
Flush current iptables state
table
The table that owns the chain that should be modified
family
Networking family , either ipv4 or ipv6''' | ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' }
for ignore in _STATE_INTERNAL_KEYWORDS :
if ignore in kwargs :
del kwargs [ ignore ]
if 'chain' not in kwargs :
kwargs [ 'chain' ] = ''
if __opts__ [ 'test' ] :
ret [ 'comment' ] = 'iptables rules in {0} table {1} chain {2}... |
def index_within_subset ( self , indexable , subset_request , sort_indices = False ) :
"""Index an indexable object within the context of this subset .
Parameters
indexable : indexable object
The object to index through .
subset _ request : : class : ` list ` or : class : ` slice `
List of positive intege... | # Translate the request within the context of this subset to a
# request to the indexable object
if isinstance ( subset_request , numbers . Integral ) :
request , = self [ [ subset_request ] ]
else :
request = self [ subset_request ]
# Integer or slice requests can be processed directly .
if isinstance ( reques... |
def getContinuousSet ( self , id_ ) :
"""Returns the ContinuousSet with the specified id , or raises a
ContinuousSetNotFoundException otherwise .""" | if id_ not in self . _continuousSetIdMap :
raise exceptions . ContinuousSetNotFoundException ( id_ )
return self . _continuousSetIdMap [ id_ ] |
def complete ( text , state ) :
"""Auto complete scss constructions in interactive mode .""" | for cmd in COMMANDS :
if cmd . startswith ( text ) :
if not state :
return cmd
else :
state -= 1 |
def get_num_shares ( self ) -> Decimal :
"""Returns the number of shares at this time""" | from pydatum import Datum
today = Datum ( ) . today ( )
return self . get_num_shares_on ( today ) |
def get_crime_category ( self , id , date = None ) :
"""Get a particular crime category by ID , valid at a particular date . Uses
the crime - categories _ API call .
: rtype : CrimeCategory
: param str id : The ID of the crime category to get .
: param date : The date that the given crime category is valid ... | try :
return self . _get_crime_categories ( date = date ) [ id ]
except KeyError :
raise InvalidCategoryException ( 'Category %s not found for %s' % ( id , date ) ) |
def is_disconnected ( self , node_id ) :
"""Check whether the node connection has been disconnected or failed .
A disconnected node has either been closed or has failed . Connection
failures are usually transient and can be resumed in the next ready ( )
call , but there are cases where transient failures need... | conn = self . _conns . get ( node_id )
if conn is None :
return False
return conn . disconnected ( ) |
def SetBackingStore ( cls , backing ) :
"""Set the global backing type used by the ComponentRegistry from this point forward
This function must be called before any operations that use the registry are initiated
otherwise they will work from different registries that will likely contain different data""" | if backing not in [ 'json' , 'sqlite' , 'memory' ] :
raise ArgumentError ( "Unknown backing store type that is not json or sqlite" , backing = backing )
if backing == 'json' :
cls . BackingType = JSONKVStore
cls . BackingFileName = 'component_registry.json'
elif backing == 'memory' :
cls . BackingType =... |
def _add_proposed ( ) :
"""Add the PROPOSED _ POCKET as / etc / apt / source . list . d / proposed . list
Uses get _ distrib _ codename to determine the correct stanza for
the deb line .
For intel architecutres PROPOSED _ POCKET is used for the release , but for
other architectures PROPOSED _ PORTS _ POCKET... | release = get_distrib_codename ( )
arch = platform . machine ( )
if arch not in six . iterkeys ( ARCH_TO_PROPOSED_POCKET ) :
raise SourceConfigError ( "Arch {} not supported for (distro-)proposed" . format ( arch ) )
with open ( '/etc/apt/sources.list.d/proposed.list' , 'w' ) as apt :
apt . write ( ARCH_TO_PROP... |
def print_ctx ( ctx ) :
"""Print given context ' s info .
: param ctx : Context object .
: return : None .""" | # Print title
print_title ( 'ctx attributes' )
# Print context object ' s attributes
print_text ( dir ( ctx ) )
# Print end title
print_title ( 'ctx attributes' , is_end = True )
# Print title
print_title ( 'ctx.options' )
# Print context options dict
print_text ( pformat ( vars ( ctx . options ) , indent = 4 , width =... |
def acme_renew_certificates ( ) :
'''Renew certificates with acme _ tiny for let ' s encrypt''' | for csr in glob ( os . path . join ( CERTIFICATES_PATH , '*.csr' ) ) :
common_name = os . path . basename ( csr )
common_name = os . path . splitext ( common_name ) [ 0 ]
certificate_path = "{}.crt" . format ( common_name )
certificate_path = os . path . join ( CERTIFICATES_PATH , certificate_path )
... |
def compute_distance_matrix ( self , input_sample , num_samples , num_params , num_groups = None , local_optimization = False ) :
"""Computes the distance between each and every trajectory
Each entry in the matrix represents the sum of the geometric distances
between all the pairs of points of the two trajector... | if num_groups :
self . check_input_sample ( input_sample , num_groups , num_samples )
else :
self . check_input_sample ( input_sample , num_params , num_samples )
index_list = self . _make_index_list ( num_samples , num_params , num_groups )
distance_matrix = np . zeros ( ( num_samples , num_samples ) , dtype =... |
def user_projects ( request ) :
"""Return all the projects for which the user is a sole owner""" | projects_owned = ( request . db . query ( Project . id ) . join ( Role . project ) . filter ( Role . role_name == "Owner" , Role . user == request . user ) . subquery ( ) )
with_sole_owner = ( request . db . query ( Role . project_id ) . join ( projects_owned ) . filter ( Role . role_name == "Owner" ) . group_by ( Role... |
def get_source ( self , objtxt ) :
"""Get object source""" | obj , valid = self . _eval ( objtxt )
if valid :
return getsource ( obj ) |
def cross ( self , rhs ) :
"""Return the cross product of this vector and * rhs * .""" | return Vector ( self . y * rhs . z - self . z * rhs . y , self . z * rhs . x - self . x * rhs . z , self . x * rhs . y - self . y * rhs . x ) |
def input_data_ports ( self , input_data_ports ) :
"""Property for the _ input _ data _ ports field
See Property .
: param dict input _ data _ ports : Dictionary that maps : class : ` int ` data _ port _ ids onto values of type
: class : ` rafcon . core . state _ elements . data _ port . InputDataPort `
: r... | if not isinstance ( input_data_ports , dict ) :
raise TypeError ( "input_data_ports must be of type dict" )
if [ port_id for port_id , port in input_data_ports . items ( ) if not port_id == port . data_port_id ] :
raise AttributeError ( "The key of the input dictionary and the id of the data port do not match" ... |
def end_index ( self ) :
"""Returns the 1 - based index of the last object on this page ,
relative to total objects found ( hits ) .""" | return ( ( self . number - 1 ) * self . paginator . per_page + len ( self . object_list ) ) |
def getMeanVoltages ( params , numunits = 100 , filepattern = os . path . join ( 'simulation_output_default' , 'voltages' ) ) :
'''return a dict with the per population mean and std synaptic current ,
averaging over numcells recorded units from each population in the
network
Returned currents are in unit of n... | data = { }
# loop over network - populations
for i , Y in enumerate ( params . Y ) :
if i % SIZE == RANK : # read in read data and assess units , up to numunits
fname = glob . glob ( filepattern + '*' + Y + '*' ) [ 0 ]
print fname
rawdata = np . array ( helpers . read_gdf ( fname ) )
... |
def get_type_data ( name ) :
"""Return dictionary representation of type .
Can be used to initialize primordium . type . primitives . Type""" | try :
return { 'authority' : 'birdland.mit.edu' , 'namespace' : 'Genus Types' , 'identifier' : name , 'domain' : 'Generic Types' , 'display_name' : OBJECTIVE_TYPES [ name ] + ' Genus Type' , 'display_label' : OBJECTIVE_TYPES [ name ] , 'description' : ( 'The ' + OBJECTIVE_TYPES [ name ] + ' Genus Type.' ) }
except ... |
def has_app ( name , check_platform = True ) :
"""Check whether the application < name > is installed .""" | if check_platform :
Environment . _platform_is_windows ( )
return which ( str ( name ) ) is not None |
def importCASignedCertificate ( self , alias , caSignedCertificate ) :
"""This operation imports a certificate authority ( CA ) - signed SSL certificate into the key store .""" | url = self . _url + "/sslcertificates/importCASignedCertificate"
files = { }
files [ 'caSignedCertificate' ] = caSignedCertificate
params = { "f" : "json" , "alias" : alias }
return self . _post ( url = url , param_dict = params , securityHandler = self . _securityHandler , files = files , proxy_url = self . _proxy_url... |
def attempt_file_write ( path : str , contents : typing . Union [ str , bytes ] , mode : str = 'w' , offset : int = 0 ) -> typing . Union [ None , Exception ] :
"""Attempts to write the specified contents to a file and returns None if
successful , or the raised exception if writing failed .
: param path :
The... | try :
data = contents . encode ( )
except Exception :
data = contents
if offset > 0 :
with open ( path , 'rb' ) as f :
existing = f . read ( offset )
else :
existing = None
append = 'a' in mode
write_mode = 'wb' if offset > 0 or not append else 'ab'
try :
with open ( path , write_mode ) as f... |
def _listen_inbox_messages ( self ) :
"""Start listening to messages , using a separate thread .""" | # Collect messages in a queue
inbox_queue = Queue ( maxsize = self . _n_jobs * 4 )
threads = [ ]
# type : List [ BotQueueWorker ]
try : # Create n _ jobs inbox threads
for i in range ( self . _n_jobs ) :
t = BotQueueWorker ( name = 'InboxThread-t-{}' . format ( i ) , jobs = inbox_queue , target = self . _pr... |
def end_of ( self , event_id , import_options = True ) :
"""Set Date - Picker as the end - date of a date - range .
Args :
- event _ id ( string ) : User - defined unique id for linking two fields
- import _ options ( bool ) : inherit options from start - date input ,
default : TRUE""" | event_id = str ( event_id )
if event_id in DatePickerDictionary . items :
linked_picker = DatePickerDictionary . items [ event_id ]
self . config [ 'linked_to' ] = linked_picker . config [ 'id' ]
if import_options :
backup_moment_format = self . config [ 'options' ] [ 'format' ]
self . confi... |
def register ( self , function ) :
"""Register a function in the function registry .
The function will be automatically instantiated if not already an
instance .""" | function = inspect . isclass ( function ) and function ( ) or function
name = function . name
self [ name ] = function |
def copy ( self , target ) :
"""Copies this file the ` target ` , which might be a directory .
The permissions are copied .""" | shutil . copy ( self . path , self . _to_backend ( target ) ) |
def thumb ( self , size = BIGTHUMB ) :
'''Get a thumbnail as string or None if the file isnt an image
size would be one of JFSFile . BIGTHUMB , . MEDIUMTHUMB , . SMALLTHUMB or . XLTHUMB''' | if not self . is_image ( ) :
return None
if not size in ( self . BIGTHUMB , self . MEDIUMTHUMB , self . SMALLTHUMB , self . XLTHUMB ) :
raise JFSError ( 'Invalid thumbnail size: %s for image %s' % ( size , self . path ) )
# return self . jfs . raw ( ' % s ? mode = thumb & ts = % s ' % ( self . path , size ) )
r... |
def click_at_coordinates ( self , x , y ) :
"""Click at ( x , y ) coordinates .""" | self . device . click ( int ( x ) , int ( y ) ) |
def filter_opt ( opt ) :
"""Remove ` ` None ` ` values from a dictionary .""" | return { k : GLib . Variant ( * v ) for k , v in opt . items ( ) if v [ 1 ] is not None } |
def gen_unique_id ( ) :
"""Generate a unique id , having - hopefully - a very small chance of
collission .
For now this is provided by : func : ` uuid . uuid4 ` .""" | # Workaround for http : / / bugs . python . org / issue4607
if ctypes and _uuid_generate_random :
buffer = ctypes . create_string_buffer ( 16 )
_uuid_generate_random ( buffer )
return str ( UUID ( bytes = buffer . raw ) )
return str ( uuid4 ( ) ) |
def random_choices ( self , elements = ( 'a' , 'b' , 'c' ) , length = None ) :
"""Returns a list of random , non - unique elements from a passed object .
If ` elements ` is a dictionary , the value will be used as
a weighting element . For example : :
random _ element ( { " { { variable _ 1 } } " : 0.5 , " { ... | return self . random_elements ( elements , length , unique = False ) |
def start ( self ) :
'''Stop server''' | # Set flask
self . app = Flask ( 'RestServer' )
self . add_endpoint ( )
# Create a thread to deal with flask
self . run_thread = Thread ( target = self . run )
self . run_thread . start ( ) |
def to_superuser ( email_class , ** data ) :
"""Email superusers""" | for user in get_user_model ( ) . objects . filter ( is_superuser = True ) :
try :
email_class ( ) . send ( [ user . email ] , user . language , ** data )
except AttributeError :
email_class ( ) . send ( [ user . email ] , translation . get_language ( ) , ** data ) |
def _argumentForLoader ( loaderClass ) :
"""Create an AMP argument for ( de - ) serializing instances of C { loaderClass } .
@ param loaderClass : A type object with a L { load } class method that takes
some bytes and returns an instance of itself , and a L { dump } instance
method that returns some bytes .
... | def decorator ( argClass ) :
class LoadableArgument ( String ) :
def toString ( self , arg ) :
assert isinstance ( arg , loaderClass ) , ( "%r not %r" % ( arg , loaderClass ) )
return String . toString ( self , arg . dump ( ) )
def fromString ( self , arg ) :
retu... |
def setup_temp_logger ( log_level = 'error' ) :
'''Setup the temporary console logger''' | if is_temp_logging_configured ( ) :
logging . getLogger ( __name__ ) . warning ( 'Temporary logging is already configured' )
return
if log_level is None :
log_level = 'warning'
level = LOG_LEVELS . get ( log_level . lower ( ) , logging . ERROR )
handler = None
for handler in logging . root . handlers :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.