signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def log ( cls , message ) :
"""Display info message if verbose level allows it .""" | if cls . verbose > 0 :
msg = '[INFO] %s' % message
cls . echo ( msg ) |
def file_can_be_written ( path ) :
"""Return ` ` True ` ` if a file can be written at the given ` ` path ` ` .
: param string path : the file path
: rtype : bool
. . warning : : This function will attempt to open the given ` ` path ` `
in write mode , possibly destroying the file previously existing there .... | if path is None :
return False
try :
with io . open ( path , "wb" ) as test_file :
pass
delete_file ( None , path )
return True
except ( IOError , OSError ) :
pass
return False |
def filter_values ( cls , part_info ) : # type : ( Type [ T ] , PartInfo ) - > List [ T ]
"""Filter the part _ info dict list looking for instances of our class
Args :
part _ info ( dict ) : { part _ name : [ Info ] or None } as returned from
Controller . run _ hook ( )
Returns :
list : [ info ] where inf... | filtered = [ ]
for info_list in cls . filter_parts ( part_info ) . values ( ) :
filtered += info_list
return filtered |
def pendingTasks ( self , * args , ** kwargs ) :
"""Get Number of Pending Tasks
Get an approximate number of pending tasks for the given ` provisionerId `
and ` workerType ` .
The underlying Azure Storage Queues only promises to give us an estimate .
Furthermore , we cache the result in memory for 20 second... | return self . _makeApiCall ( self . funcinfo [ "pendingTasks" ] , * args , ** kwargs ) |
def get_consistent_resource ( self ) :
""": return a refund that you can trust .
: rtype Refund""" | http_client = HttpClient ( )
response , _ = http_client . get ( routes . url ( routes . REFUND_RESOURCE , resource_id = self . id , payment_id = self . payment_id ) )
return Refund ( ** response ) |
def prefix2ns ( self , prefix : YangIdentifier , mid : ModuleId ) -> YangIdentifier :
"""Return the namespace corresponding to a prefix .
Args :
prefix : Prefix associated with a module and its namespace .
mid : Identifier of the module in which the prefix is declared .
Raises :
ModuleNotRegistered : If `... | try :
mdata = self . modules [ mid ]
except KeyError :
raise ModuleNotRegistered ( * mid ) from None
try :
return mdata . prefix_map [ prefix ] [ 0 ]
except KeyError :
raise UnknownPrefix ( prefix , mid ) from None |
def assert_subset ( self , subset , superset , failure_message = 'Expected collection "{}" to be a subset of "{}' ) :
"""Asserts that a superset contains all elements of a subset""" | assertion = lambda : set ( subset ) . issubset ( set ( superset ) )
failure_message = unicode ( failure_message ) . format ( superset , subset )
self . webdriver_assert ( assertion , failure_message ) |
def set_from_file ( self , filename : str , is_padded : bool = True , oov_token : str = DEFAULT_OOV_TOKEN , namespace : str = "tokens" ) :
"""If you already have a vocabulary file for a trained model somewhere , and you really want to
use that vocabulary file instead of just setting the vocabulary from a dataset ... | if is_padded :
self . _token_to_index [ namespace ] = { self . _padding_token : 0 }
self . _index_to_token [ namespace ] = { 0 : self . _padding_token }
else :
self . _token_to_index [ namespace ] = { }
self . _index_to_token [ namespace ] = { }
with codecs . open ( filename , 'r' , 'utf-8' ) as input_f... |
def search ( self , search_term , column = "title" , number_results = 25 ) :
"""TODO :
Add documentation
DONE - > Search multiple pages untile the number _ results is meet or the end .
Check for strange encodings , other langauges chinese , etc . .
Simplify , simplify , simply . . . For exemple the book dic... | request = { "req" : search_term , "column" : column }
self . __choose_mirror ( )
if sys . version_info [ 0 ] < 3 :
url = self . __selected_mirror + "/search.php?" + urllib . urlencode ( request )
else :
url = self . __selected_mirror + "/search.php?" + urllib . parse . urlencode ( request )
self . grabber . go ... |
async def open_wallet_search ( wallet_handle : int , type_ : str , query_json : str , options_json : str ) -> int :
"""Search for wallet records
: param wallet _ handle : wallet handler ( created by open _ wallet ) .
: param type _ : allows to separate different record types collections
: param query _ json :... | logger = logging . getLogger ( __name__ )
logger . debug ( "open_wallet_search: >>> wallet_handle: %r, type_: %r, query_json: %r, options_json: %r" , wallet_handle , type_ , query_json , options_json )
if not hasattr ( open_wallet_search , "cb" ) :
logger . debug ( "open_wallet_search: Creating callback" )
open... |
def send ( self ) :
"""Sends the object to the watch . Block until completion , or raises : exc : ` . PutBytesError ` on failure .
During transmission , a " progress " event will be periodically emitted with the following signature : : :
( sent _ this _ interval , sent _ so _ far , total _ object _ size )""" | # Prepare the watch to receive something .
cookie = self . _prepare ( )
# Send it .
self . _send_object ( cookie )
# Commit it .
self . _commit ( cookie )
# Install it .
self . _install ( cookie ) |
def _calculate_cloud_ice_perc ( self ) :
"""Return the percentage of pixels that are either cloud or snow with
high confidence ( > 67 % ) .""" | self . output ( 'Calculating cloud and snow coverage from QA band' , normal = True , arrow = True )
a = rasterio . open ( join ( self . scene_path , self . _get_full_filename ( 'QA' ) ) ) . read_band ( 1 )
cloud_high_conf = int ( '1100000000000000' , 2 )
snow_high_conf = int ( '0000110000000000' , 2 )
fill_pixels = int... |
def get_auth_url ( self , s_pappid , order_id , money , timestamp , source , ticket , auth_type , redirect_url = None ) :
"""获取授权页链接
详情请参考
https : / / mp . weixin . qq . com / wiki ? id = mp1497082828 _ r1cI2
: param s _ pappid : 开票平台在微信的标识号 , 商户需要找开票平台提供
: param order _ id : 订单id , 在商户内单笔开票请求的唯一识别号
: par... | if source not in { 'app' , 'web' , 'wap' } :
raise ValueError ( 'Unsupported source. Valid sources are "app", "web" or "wap"' )
if source == 'web' and redirect_url is None :
raise ValueError ( 'redirect_url is required if source is web' )
if not ( 0 <= auth_type <= 2 ) :
raise ValueError ( 'Unsupported auth... |
def _RunInTransaction ( self , function , readonly = False ) :
"""Runs function within a transaction .
Allocates a connection , begins a transaction on it and passes the connection
to function .
If function finishes without raising , the transaction is committed .
If function raises , the transaction will b... | start_query = "START TRANSACTION;"
if readonly :
start_query = "START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY;"
for retry_count in range ( _MAX_RETRY_COUNT ) :
with contextlib . closing ( self . pool . get ( ) ) as connection :
try :
with contextlib . closing ( connection . cursor ( ... |
def _create ( self ) :
"""Creates a new and empty database .""" | from . tools import makedirs_safe
# create directory for sql database
makedirs_safe ( os . path . dirname ( self . _database ) )
# create all the tables
Base . metadata . create_all ( self . _engine )
logger . debug ( "Created new empty database '%s'" % self . _database ) |
def get_release_definition ( self , project , definition_id , property_filters = None ) :
"""GetReleaseDefinition .
[ Preview API ] Get a release definition .
: param str project : Project ID or project name
: param int definition _ id : Id of the release definition .
: param [ str ] property _ filters : A ... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if definition_id is not None :
route_values [ 'definitionId' ] = self . _serialize . url ( 'definition_id' , definition_id , 'int' )
query_parameters = { }
if property_filters is not ... |
def _get_data ( self ) :
"""Process the IGRA2 text file for observations at site _ id matching time .
Return :
: class : ` pandas . DataFrame ` containing the body data .
: class : ` pandas . DataFrame ` containing the header data .""" | # Split the list of times into begin and end dates . If only
# one date is supplied , set both begin and end dates equal to that date .
body , header , dates_long , dates = self . _get_data_raw ( )
params = self . _get_fwf_params ( )
df_body = pd . read_fwf ( StringIO ( body ) , ** params [ 'body' ] )
df_header = pd . ... |
def retrieve ( self , state = None , favorite = None , tag = None , contentType = None , sort = None , detailType = None , search = None , domain = None , since = None , count = None , offset = None ) :
"""Retrieve the list of your articles
See : https : / / getpocket . com / developer / docs / v3 / retrieve
: ... | return self . _make_request ( 'get' ) |
def get_many ( self , keys ) :
"""Fetch a bunch of keys from the cache . For certain backends ( memcached ,
pgsql ) this can be * much * faster when fetching multiple values .
Return a dict mapping each key in keys to its value . If the given
key is missing , it will be missing from the response dict .""" | d = { }
for k in keys :
val = self . get ( k )
if val is not None :
d [ k ] = val
return d |
def apool ( self , k_height , k_width , d_height = 2 , d_width = 2 , mode = "VALID" , input_layer = None , num_channels_in = None ) :
"""Construct an average pooling layer .""" | return self . _pool ( "apool" , pooling_layers . average_pooling2d , k_height , k_width , d_height , d_width , mode , input_layer , num_channels_in ) |
def validate_config ( cls , config ) :
"""Runs a check on the given config to make sure that ` port ` / ` ports ` and
` discovery ` is defined .""" | if "discovery" not in config :
raise ValueError ( "No discovery method defined." )
if not any ( [ item in config for item in [ "port" , "ports" ] ] ) :
raise ValueError ( "No port(s) defined." )
cls . validate_check_configs ( config ) |
def process_text ( self , t : str , tok : BaseTokenizer ) -> List [ str ] :
"Process one text ` t ` with tokenizer ` tok ` ." | for rule in self . pre_rules :
t = rule ( t )
toks = tok . tokenizer ( t )
for rule in self . post_rules :
toks = rule ( toks )
return toks |
def music_url ( ids = [ ] ) :
"""通过歌曲 ID 获取歌曲下载地址
: param ids : 歌曲 ID 的 list""" | if not isinstance ( ids , list ) :
raise ParamsError ( )
r = NCloudBot ( )
r . method = 'MUSIC_URL'
r . data = { 'ids' : ids , 'br' : 999000 , "csrf_token" : "" }
r . send ( )
return r . response |
def report_fit ( self ) :
"""Print a report of the fit results .""" | if not self . fitted :
print ( 'Model not yet fit.' )
return
print ( 'Null Log-liklihood: {0:.3f}' . format ( self . log_likelihoods [ 'null' ] ) )
print ( 'Log-liklihood at convergence: {0:.3f}' . format ( self . log_likelihoods [ 'convergence' ] ) )
print ( 'Log-liklihood Ratio: {0:.3f}\n' . format ( self . l... |
def Run ( self , args ) :
"""Lists a directory .""" | try :
directory = vfs . VFSOpen ( args . pathspec , progress_callback = self . Progress )
except ( IOError , OSError ) as e :
self . SetStatus ( rdf_flows . GrrStatus . ReturnedStatus . IOERROR , e )
return
files = list ( directory . ListFiles ( ) )
files . sort ( key = lambda x : x . pathspec . path )
for ... |
def role_add ( self , role = None , login = None , envs = [ ] , query = '/roles/' ) :
"""` login ` - Login or username of user to add to ` role `
` role ` - Role to add user to
Add user to role""" | data = { 'login' : self . args . login }
juicer . utils . Log . log_debug ( "Add Role '%s' to '%s'" , role , login )
for env in self . args . envs :
if not juicer . utils . role_exists_p ( role , self . connectors [ env ] ) :
juicer . utils . Log . log_info ( "role `%s` doesn't exist in %s... skipping!" , (... |
def status ( self ) :
"""Return a tuple with current processing status code and message .""" | status = self . receiver . status ( self )
return status if status else ( self . response_code , self . response . get ( 'message' ) ) |
def bind_filter ( self , direction , filter_name ) :
"""Adds a packet filter to this NIO .
Filter " freq _ drop " drops packets .
Filter " capture " captures packets .
: param direction : " in " , " out " or " both "
: param filter _ name : name of the filter to apply""" | if direction not in self . _dynamips_direction :
raise DynamipsError ( "Unknown direction {} to bind filter {}:" . format ( direction , filter_name ) )
dynamips_direction = self . _dynamips_direction [ direction ]
yield from self . _hypervisor . send ( "nio bind_filter {name} {direction} {filter}" . format ( name =... |
def decoded_output_boxes ( self ) :
"""Returns : N x # class x 4""" | anchors = tf . tile ( tf . expand_dims ( self . proposals . boxes , 1 ) , [ 1 , cfg . DATA . NUM_CLASS , 1 ] )
# N x # class x 4
decoded_boxes = decode_bbox_target ( self . box_logits / self . bbox_regression_weights , anchors )
return decoded_boxes |
def existing_node_input ( ) :
"""Get an existing node id by name or id .
Return - 1 if invalid""" | input_from_user = raw_input ( "Existing node name or id: " )
node_id = INVALID_NODE
if not input_from_user :
return node_id
# int or str ?
try :
parsed_input = int ( input_from_user )
except ValueError :
parsed_input = input_from_user
if isinstance ( parsed_input , int ) :
result = db . execute ( text (... |
def filter_cat ( self , axis , cat_index , cat_name ) :
'''Filter the matrix based on their category . cat _ index is the index of the category , the first category has index = 1.''' | run_filter . filter_cat ( self , axis , cat_index , cat_name ) |
def get_soa_record ( client , zone_id , zone_name ) :
"""Gets the SOA record for zone _ name from zone _ id .
Args :
client ( : class : ` botocore . client . Route53 ` ) : The connection used to
interact with Route53 ' s API .
zone _ id ( string ) : The AWS Route53 zone id of the hosted zone to query .
zo... | response = client . list_resource_record_sets ( HostedZoneId = zone_id , StartRecordName = zone_name , StartRecordType = "SOA" , MaxItems = "1" )
return SOARecord ( response [ "ResourceRecordSets" ] [ 0 ] ) |
def push_failure_state ( self ) :
"""Returns a tuple : the boolean for whether or not pushes succeed , and the
entire object returned by a call to push _ failure on the phylesystem - api .
This should only be called with wrappers around remote services ( RuntimeError
will be raised if you call this with a loc... | if self . _src_code == _GET_LOCAL :
raise RuntimeError ( 'push_failure_state only pertains to work with remote phyleysystem instances' )
r = self . _remote_push_failure ( )
return r [ 'pushes_succeeding' ] , r |
def find_module_registrations ( c_file ) :
"""Find any MP _ REGISTER _ MODULE definitions in the provided c file .
: param str c _ file : path to c file to check
: return : List [ ( module _ name , obj _ module , enabled _ define ) ]""" | global pattern
if c_file is None : # No c file to match the object file , skip
return set ( )
with io . open ( c_file , encoding = 'utf-8' ) as c_file_obj :
return set ( re . findall ( pattern , c_file_obj . read ( ) ) ) |
def history ( ctx , account , limit , type , csv , exclude , raw ) :
"""Show history of an account""" | from bitsharesbase . operations import getOperationNameForId
t = [ [ "#" , "time (block)" , "operation" , "details" ] ]
for a in account :
account = Account ( a , bitshares_instance = ctx . bitshares )
for b in account . history ( limit = limit , only_ops = type , exclude_ops = exclude ) :
block = Block... |
def build_sample_smoother_problem_friedman82 ( N = 200 ) :
"""Sample problem from supersmoother publication .""" | x = numpy . random . uniform ( size = N )
err = numpy . random . standard_normal ( N )
y = numpy . sin ( 2 * math . pi * ( 1 - x ) ** 2 ) + x * err
return x , y |
def list_devices ( ) :
"""List devices via HTTP GET .""" | output = { }
for device_id , device in devices . items ( ) :
output [ device_id ] = { 'host' : device . host , 'state' : device . state }
return jsonify ( devices = output ) |
def parseSetEnv ( l ) :
"""Parses a list of strings of the form " NAME = VALUE " or just " NAME " into a dictionary . Strings
of the latter from will result in dictionary entries whose value is None .
: type l : list [ str ]
: rtype : dict [ str , str ]
> > > parseSetEnv ( [ ] )
> > > parseSetEnv ( [ ' a ... | d = dict ( )
for i in l :
try :
k , v = i . split ( '=' , 1 )
except ValueError :
k , v = i , None
if not k :
raise ValueError ( 'Empty name' )
d [ k ] = v
return d |
def error ( self , message ) :
"""error ( message : string )
Prints a usage message incorporating the message to stderr and
exits .
If you override this in a subclass , it should not return - - it
should either exit or raise an exception .""" | self . print_usage ( _sys . stderr )
self . exit ( 2 , _ ( '%s: error: %s\n' ) % ( self . prog , message ) ) |
def valid_totp ( self , code , period = 30 , timestamp = None ) :
"""Valid a TOTP code .
: param code : A number that is less than 6 characters .
: param period : A period that a TOTP code is valid in seconds
: param timestamp : Validate TOTP at this given timestamp""" | if not valid_code ( code ) :
return False
return compare_digest ( bytes ( self . totp ( period , timestamp ) ) , bytes ( int ( code ) ) ) |
def _set_link_error_disable ( self , v , load = False ) :
"""Setter method for link _ error _ disable , mapped from YANG variable / interface / ethernet / link _ error _ disable ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ link _ error _ disable is cons... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = link_error_disable . link_error_disable , is_container = 'container' , presence = False , yang_name = "link-error-disable" , rest_name = "link-error-disable" , parent = self , path_helper = self . _path_helper , extmethods = ... |
def save_instance ( self , instance , using_transactions = True , dry_run = False ) :
"""Takes care of saving the object to the database .
Keep in mind that this is done by calling ` ` instance . save ( ) ` ` , so
objects are not created in bulk !""" | self . before_save_instance ( instance , using_transactions , dry_run )
if not using_transactions and dry_run : # we don ' t have transactions and we want to do a dry _ run
pass
else :
instance . save ( )
self . after_save_instance ( instance , using_transactions , dry_run ) |
def variable ( name , shape = None , dtype = tf . float32 , initializer = None , regularizer = None , trainable = True , collections = None , device = '' , restore = True ) :
"""Gets an existing variable with these parameters or creates a new one .
It also add itself to a group with its name .
Args :
name : t... | collections = list ( collections or [ ] )
# Make sure variables are added to tf . GraphKeys . GLOBAL _ VARIABLES and MODEL _ VARIABLES
collections += [ tf . GraphKeys . GLOBAL_VARIABLES , MODEL_VARIABLES ]
# Add to VARIABLES _ TO _ RESTORE if necessary
if restore :
collections . append ( VARIABLES_TO_RESTORE )
# Re... |
def download_attachments ( self , dataset_identifier , content_type = "json" , download_dir = "~/sodapy_downloads" ) :
'''Download all of the attachments associated with a dataset . Return the paths of downloaded
files .''' | metadata = self . get_metadata ( dataset_identifier , content_type = content_type )
files = [ ]
attachments = metadata [ 'metadata' ] . get ( "attachments" )
if not attachments :
logging . info ( "No attachments were found or downloaded." )
return files
download_dir = os . path . join ( os . path . expanduser (... |
def import_setting ( file_path , qsettings = None ) :
"""Import InaSAFE ' s setting from a file .
: param file _ path : The file to read the imported setting .
: type file _ path : basestring
: param qsettings : A custom QSettings to use . If it ' s not defined , it will
use the default one .
: type qsett... | with open ( file_path , 'r' ) as f :
inasafe_settings = json . load ( f )
if not qsettings :
qsettings = QSettings ( )
# Clear the previous setting
qsettings . beginGroup ( 'inasafe' )
qsettings . remove ( '' )
qsettings . endGroup ( )
for key , value in list ( inasafe_settings . items ( ) ) :
set_setting (... |
def filename_to_module ( filename ) :
"""convert a filename like html5lib - 0.999 . egg - info to html5lib""" | find = re . compile ( r"^[^.|-]*" )
name = re . search ( find , filename ) . group ( 0 )
return name |
def assert_await_all_transforms_exist ( cli , transform_paths , does_exist = DEFAULT_TRANSFORM_EXISTS , timeout_seconds = DEFAULT_TIMEOUT_SECONDS ) :
"""Asserts that we successfully awaited for all transforms to exist based on does _ exist . If the timeout passes
or the expression is _ registered ! = actual state... | result = commands . await_all_transforms_exist ( cli , transform_paths , does_exist , timeout_seconds )
assert result is True
return result |
def invertible_total_flatten ( unflat_list ) :
r"""Args :
unflat _ list ( list ) :
Returns :
tuple : ( flat _ list , invert _ levels )
CommandLine :
python - m utool . util _ list - - exec - invertible _ total _ flatten - - show
Example :
> > > # DISABLE _ DOCTEST
> > > from utool . util _ list impo... | import utool as ut
next_list = unflat_list
scalar_flags = [ not ut . isiterable ( item ) for item in next_list ]
invert_stack = [ ]
# print ( ' unflat _ list = % r ' % ( unflat _ list , ) )
while not all ( scalar_flags ) :
unflattenized = [ [ item ] if flag else item for flag , item in zip ( scalar_flags , next_lis... |
def cli ( yamlfile , inline , format ) :
"""Generate JSON Schema representation of a biolink model""" | print ( JsonSchemaGenerator ( yamlfile , format ) . serialize ( inline = inline ) ) |
def reverse_url ( self , datatype , url , verb = 'GET' , urltype = 'single' , api_version = None ) :
"""Extracts parameters from a populated URL
: param datatype : a string identifying the data the url accesses .
: param url : the fully - qualified URL to extract parameters from .
: param verb : the HTTP verb... | api_version = api_version or 'v1'
templates = getattr ( self , 'URL_TEMPLATES__%s' % api_version )
# this is fairly simplistic , if necessary we could use the parse lib
template_url = r"https://(?P<api_host>.+)/services/api/(?P<api_version>.+)"
template_url += re . sub ( r'{([^}]+)}' , r'(?P<\1>.+)' , templates [ datat... |
def an_text_url ( identifiant , code ) :
"""Port of the PHP function used by the National Assembly :
public function urlOpaque ( $ identifiant , $ codeType = NULL )
$ datas = array (
' PRJL ' = > array ( ' repertoire ' = > ' projets ' , ' prefixe ' = > ' pl ' , ' suffixe ' = > ' ' ) ,
' PION ' = > array ( '... | datas = { 'PRJL' : { 'repertoire' : 'projets' , 'prefixe' : 'pl' , 'suffixe' : '' , } , 'PION' : { 'repertoire' : 'propositions' , 'prefixe' : 'pion' , 'suffixe' : '' , } , 'PNRECOMENQ' : { 'repertoire' : 'propositions' , 'prefixe' : 'pion' , 'suffixe' : '' , } , 'PNREAPPART341' : { 'repertoire' : 'propositions' , 'pre... |
def _get_processed_dataframe ( self , dataframe ) :
"""Generate required dataframe for results from raw dataframe
: param pandas . DataFrame dataframe : the raw dataframe
: return : a dict containing raw , compiled , and summary dataframes from original dataframe
: rtype : dict""" | dataframe . index = pd . to_datetime ( dataframe [ 'epoch' ] , unit = 's' , utc = True )
del dataframe [ 'epoch' ]
summary = dataframe . describe ( percentiles = [ .80 , .90 , .95 ] ) . transpose ( ) . loc [ 'scriptrun_time' ]
df_grp = dataframe . groupby ( pd . TimeGrouper ( '{}S' . format ( self . interval ) ) )
df_f... |
def client_pause ( self , timeout ) :
"""Stop processing commands from clients for * timeout * milliseconds .
: raises TypeError : if timeout is not int
: raises ValueError : if timeout is less than 0""" | if not isinstance ( timeout , int ) :
raise TypeError ( "timeout argument must be int" )
if timeout < 0 :
raise ValueError ( "timeout must be greater equal 0" )
fut = self . execute ( b'CLIENT' , b'PAUSE' , timeout )
return wait_ok ( fut ) |
def user_create ( name , password , email , tenant_id = None , enabled = True , profile = None , project_id = None , description = None , ** connection_args ) :
'''Create a user ( keystone user - create )
CLI Examples :
. . code - block : : bash
salt ' * ' keystone . user _ create name = jack password = zero ... | kstone = auth ( profile , ** connection_args )
if _OS_IDENTITY_API_VERSION > 2 :
if tenant_id and not project_id :
project_id = tenant_id
item = kstone . users . create ( name = name , password = password , email = email , project_id = project_id , enabled = enabled , description = description )
else :
... |
def get_voltage_delta_branch ( grid , tree , node , r_preceeding , x_preceeding ) :
"""Determine voltage for a preceeding branch ( edge ) of node
Parameters
grid : LVGridDing0
Ding0 grid object
tree : : networkx : ` NetworkX Graph Obj < > `
Tree of grid topology
node : graph node
Node to determine vol... | cos_phi_load = cfg_ding0 . get ( 'assumptions' , 'cos_phi_load' )
cos_phi_feedin = cfg_ding0 . get ( 'assumptions' , 'cos_phi_gen' )
v_nom = cfg_ding0 . get ( 'assumptions' , 'lv_nominal_voltage' )
omega = 2 * math . pi * 50
# add resitance / reactance to preceeding
in_edge = [ _ for _ in grid . graph_branches_from_nod... |
def _search_for_function_hints ( self , successor_state ) :
"""Scan for constants that might be used as exit targets later , and add them into pending _ exits .
: param SimState successor _ state : A successing state .
: return : A list of discovered code addresses .
: rtype : list""" | function_hints = [ ]
for action in successor_state . history . recent_actions :
if action . type == 'reg' and action . offset == self . project . arch . ip_offset : # Skip all accesses to IP registers
continue
elif action . type == 'exit' : # only consider read / write actions
continue
# Enu... |
def prune ( self , keep_channels = True , * , verbose = True ) :
"""Remove unused variables and ( optionally ) channels from the Data object .
Unused variables are those that are not included in either axes or constants .
Unused channels are those not specified in keep _ channels , or the first channel .
Para... | for v in self . variables :
for var in wt_kit . flatten_list ( [ ax . variables for ax in self . _axes + self . _constants ] ) :
if v == var :
break
else :
self . remove_variable ( v . natural_name , implied = False , verbose = verbose )
if keep_channels is not True :
try :
... |
def handle_scoping_input ( self , continue_flag , cmd , text ) :
"""handles what to do with a scoping gesture""" | default_split = text . partition ( SELECT_SYMBOL [ 'scope' ] ) [ 2 ] . split ( )
cmd = cmd . replace ( SELECT_SYMBOL [ 'scope' ] , '' )
continue_flag = True
if not default_split :
self . default_command = ""
print ( 'unscoping all' , file = self . output )
return continue_flag , cmd
while default_split :
... |
def check_encoding_chars ( encoding_chars ) :
"""Validate the given encoding chars
: type encoding _ chars : ` ` dict ` `
: param encoding _ chars : the encoding chars ( see : func : ` hl7apy . set _ default _ encoding _ chars ` )
: raises : : exc : ` hl7apy . exceptions . InvalidEncodingChars ` if the given ... | if not isinstance ( encoding_chars , collections . MutableMapping ) :
raise InvalidEncodingChars
required = { 'FIELD' , 'COMPONENT' , 'SUBCOMPONENT' , 'REPETITION' , 'ESCAPE' }
missing = required - set ( encoding_chars . keys ( ) )
if missing :
raise InvalidEncodingChars ( 'Missing required encoding chars' )
va... |
def info ( self , name , args ) :
"""Interfaces with the info dumpers ( DBGFInfo ) .
This feature is not implemented in the 4.0.0 release but it may show up
in a dot release .
in name of type str
The name of the info item .
in args of type str
Arguments to the info dumper .
return info of type str
T... | if not isinstance ( name , basestring ) :
raise TypeError ( "name can only be an instance of type basestring" )
if not isinstance ( args , basestring ) :
raise TypeError ( "args can only be an instance of type basestring" )
info = self . _call ( "info" , in_p = [ name , args ] )
return info |
def result ( self ) :
"""Get the table used for the results of the query . If the query is incomplete , this blocks .
Raises :
Exception if we timed out waiting for results or the query failed .""" | self . wait ( )
if self . failed :
raise Exception ( 'Query failed: %s' % str ( self . errors ) )
return self . _table |
def probe_characteristics ( self , conn_id , handle , services ) :
"""Probe a device for all characteristics defined in its GATT table
This routine must be called after probe _ services and passed the services dictionary
produced by that method .
Args :
handle ( int ) : a handle to the connection on the BLE... | self . _command_task . async_command ( [ '_probe_characteristics' , handle , services ] , self . _probe_characteristics_finished , { 'connection_id' : conn_id , 'handle' : handle , 'services' : services } ) |
def init_app ( self , app ) :
'''Initialize this Flask extension for given app .''' | self . app = app
if not hasattr ( app , 'extensions' ) :
app . extensions = { }
app . extensions [ 'plugin_manager' ] = self
self . reload ( ) |
def passengers ( self ) -> Set [ "PassengerUnit" ] :
"""Units inside a Bunker , CommandCenter , Nydus , Medivac , WarpPrism , Overlord""" | return { PassengerUnit ( unit , self . _game_data ) for unit in self . _proto . passengers } |
def set_access_credentials ( self , scope , access_token , refresh_token = None , update_user = True ) :
"""Set the credentials used for OAuth2 authentication .
Calling this function will overwrite any currently existing access
credentials .
: param scope : A set of reddit scopes the tokens provide access to ... | if isinstance ( scope , ( list , tuple ) ) :
scope = set ( scope )
elif isinstance ( scope , six . string_types ) :
scope = set ( scope . split ( ) )
if not isinstance ( scope , set ) :
raise TypeError ( '`scope` parameter must be a set' )
self . clear_authentication ( )
# Update authentication settings
sel... |
def getMessage ( self ) :
"""Return the message for this LogRecord .
Return the message for this LogRecord after merging any user - supplied arguments with the message .""" | if isinstance ( self . msg , numpy . ndarray ) :
msg = self . array2string ( self . msg )
else :
msg = str ( self . msg )
if self . args :
a2s = self . array2string
if isinstance ( self . args , Dict ) :
args = { k : ( a2s ( v ) if isinstance ( v , numpy . ndarray ) else v ) for ( k , v ) in sel... |
def lc ( ** kwargs ) :
"""Create parameters for a new light curve dataset .
Generally , this will be used as an input to the kind argument in
: meth : ` phoebe . frontend . bundle . Bundle . add _ dataset `
: parameter * * kwargs : defaults for the values of any of the parameters
: return : a : class : ` ph... | obs_params = [ ]
syn_params , constraints = lc_syn ( syn = False , ** kwargs )
obs_params += syn_params . to_list ( )
# obs _ params + = lc _ dep ( * * kwargs ) . to _ list ( )
# ~ obs _ params + = [ FloatArrayParameter ( qualifier = ' flag ' , value = kwargs . get ( ' flag ' , [ ] ) , default _ unit = None , descripti... |
def check_version_2 ( dataset ) :
"""Checks if json - stat version attribute exists and is equal or greater than 2.0 for a given dataset .
Args :
dataset ( OrderedDict ) : data in JSON - stat format , previously deserialized to a python object by json . load ( ) or json . loads ( ) ,
Returns :
bool : True i... | if float ( dataset . get ( 'version' ) ) >= 2.0 if dataset . get ( 'version' ) else False :
return True
else :
return False |
def _step4 ( self , word ) :
"""step4 ( ) takes off - ant , - ence etc . , in context < c > vcvc < v > .""" | if len ( word ) <= 1 : # Only possible at this stage given unusual inputs to stem _ word like ' oed '
return word
ch = word [ - 2 ]
if ch == 'a' :
if word . endswith ( "al" ) :
return word [ : - 2 ] if self . _m ( word , len ( word ) - 3 ) > 1 else word
else :
return word
elif ch == 'c' :
... |
def set_color_hsv ( self , hue , saturation , value ) :
"""Turn the bulb on with the given values as HSV .""" | try :
data = "action=on&color={};{};{}" . format ( hue , saturation , value )
request = requests . post ( '{}/{}/{}' . format ( self . resource , URI , self . _mac ) , data = data , timeout = self . timeout )
if request . status_code == 200 :
self . data [ 'on' ] = True
except requests . exceptions ... |
def candidate ( self , cand_func , args = None , kwargs = None , name = 'Candidate' , context = None ) :
'''Adds a candidate function to an experiment . Can be used multiple times for
multiple candidates .
: param callable cand _ func : your control function
: param iterable args : positional arguments to pas... | self . _candidates . append ( { 'func' : cand_func , 'args' : args or [ ] , 'kwargs' : kwargs or { } , 'name' : name , 'context' : context or { } , } ) |
def _get_args ( cls , args ) : # type : ( tuple ) - > Tuple [ type , slice , Callable ]
"""Return the parameters necessary to check type boundaries .
Args :
args : A slice representing the minimum and maximum lengths allowed
for values of that string .
Returns :
A tuple with three parameters : a type , a ... | if isinstance ( args , tuple ) :
raise TypeError ( "{}[...] takes exactly one argument." . format ( cls . __name__ ) )
return super ( _StringMeta , cls ) . _get_args ( ( _STR_TYPE , args ) ) |
def build_model ( self ) :
'''Find out the type of model configured and dispatch the request to the appropriate method''' | if self . model_config [ 'model-type' ] :
self . model = self . build_fred ( )
elif self . model_config [ 'model-type' ] :
self . model = self . buidl_hred ( )
else :
raise Error ( "Unrecognized model type '{}'" . format ( self . model_config [ 'model-type' ] ) ) |
def chown ( self , paths , owner , recurse = False ) :
'''Change the owner for paths . The owner can be specified as ` user ` or ` user : group `
: param paths : List of paths to chmod
: type paths : list
: param owner : New owner
: type owner : string
: param recurse : Recursive chown
: type recurse : ... | if not isinstance ( paths , list ) :
raise InvalidInputException ( "Paths should be a list" )
if not paths :
raise InvalidInputException ( "chown: no path given" )
if not owner :
raise InvalidInputException ( "chown: no owner given" )
processor = lambda path , node , owner = owner : self . _handle_chown ( p... |
def post ( self , request , * args , ** kwargs ) :
"""Handler for HTTP POST requests .""" | context = self . get_context_data ( ** kwargs )
workflow = context [ self . context_object_name ]
try : # Check for the VALIDATE _ STEP * headers , if they are present
# and valid integers , return validation results as JSON ,
# otherwise proceed normally .
validate_step_start = int ( self . request . META . get ( ... |
def append_result ( self , results , num_matches ) :
"""Real - time update of search results""" | filename , lineno , colno , match_end , line = results
if filename not in self . files :
file_item = FileMatchItem ( self , filename , self . sorting , self . text_color )
file_item . setExpanded ( True )
self . files [ filename ] = file_item
self . num_files += 1
search_text = self . search_text
title ... |
def save_state_recursively ( state , base_path , parent_path , as_copy = False ) :
"""Recursively saves a state to a json file
It calls this method on all its substates .
: param state : State to be stored
: param base _ path : Path to the state machine
: param parent _ path : Path to the parent state
: p... | from rafcon . core . states . execution_state import ExecutionState
from rafcon . core . states . container_state import ContainerState
state_path = os . path . join ( parent_path , get_storage_id_for_state ( state ) )
state_path_full = os . path . join ( base_path , state_path )
if not os . path . exists ( state_path_... |
def handle_userinfo_request ( self , request = None , http_headers = None ) : # type : ( Optional [ str ] , Optional [ Mapping [ str , str ] ] ) - > oic . oic . message . OpenIDSchema
"""Handles a userinfo request .
: param request : urlencoded request ( either query string or POST body )
: param http _ headers... | if http_headers is None :
http_headers = { }
userinfo_request = dict ( parse_qsl ( request ) )
bearer_token = extract_bearer_token_from_http_request ( userinfo_request , http_headers . get ( 'Authorization' ) )
introspection = self . authz_state . introspect_access_token ( bearer_token )
if not introspection [ 'act... |
def find_package_docs ( package_dir , skippedNames = None ) :
"""Find documentation directories in a package using ` ` manifest . yaml ` ` .
Parameters
package _ dir : ` str `
Directory of an EUPS package .
skippedNames : ` list ` of ` str ` , optional
List of package or module names to skip when creating... | logger = logging . getLogger ( __name__ )
if skippedNames is None :
skippedNames = [ ]
doc_dir = os . path . join ( package_dir , 'doc' )
modules_yaml_path = os . path . join ( doc_dir , 'manifest.yaml' )
if not os . path . exists ( modules_yaml_path ) :
raise NoPackageDocs ( 'Manifest YAML not found: {0}' . fo... |
def _safe_read ( path , length ) :
"""Read file contents .""" | if not os . path . exists ( os . path . join ( HERE , path ) ) :
return ''
file_handle = codecs . open ( os . path . join ( HERE , path ) , encoding = 'utf-8' )
contents = file_handle . read ( length )
file_handle . close ( )
return contents |
def GetParametro ( self , clave , clave1 = None , clave2 = None , clave3 = None , clave4 = None ) :
"Devuelve un parámetro de salida ( establecido por llamada anterior )" | # útil para parámetros de salida ( por ej . campos de TransaccionPlainWS )
valor = self . params_out . get ( clave )
# busco datos " anidados " ( listas / diccionarios )
for clave in ( clave1 , clave2 , clave3 , clave4 ) :
if clave is not None and valor is not None :
if isinstance ( clave1 , basestring ) ... |
def dump ( self , file : TextIO , ** kwargs ) -> None :
"""Dump this protocol to a file in JSON .""" | return json . dump ( self . to_json ( ) , file , ** kwargs ) |
def remove_object_from_list ( self , obj , list_element ) :
"""Remove an object from a list element .
Args :
obj : Accepts JSSObjects , id ' s , and names
list _ element : Accepts an Element or a string path to that
element""" | list_element = self . _handle_location ( list_element )
if isinstance ( obj , JSSObject ) :
results = [ item for item in list_element . getchildren ( ) if item . findtext ( "id" ) == obj . id ]
elif isinstance ( obj , ( int , basestring ) ) :
results = [ item for item in list_element . getchildren ( ) if item .... |
def rgb_to_hexa ( * args ) :
"""Convert RGB ( A ) color to hexadecimal .""" | if len ( args ) == 3 :
return ( "#%2.2x%2.2x%2.2x" % tuple ( args ) ) . upper ( )
elif len ( args ) == 4 :
return ( "#%2.2x%2.2x%2.2x%2.2x" % tuple ( args ) ) . upper ( )
else :
raise ValueError ( "Wrong number of arguments." ) |
def _get_result_paths ( self , data ) :
"""Set the result paths""" | result = { }
result [ 'Output' ] = ResultPath ( Path = self . Parameters [ '--output' ] . Value , IsWritten = self . Parameters [ '--output' ] . isOn ( ) )
result [ 'ClusterFile' ] = ResultPath ( Path = self . Parameters [ '--uc' ] . Value , IsWritten = self . Parameters [ '--uc' ] . isOn ( ) )
# uchime 3 - way global ... |
def get_slice_bound ( self , label , side , kind ) :
"""Calculate slice bound that corresponds to given label .
Returns leftmost ( one - past - the - rightmost if ` ` side = = ' right ' ` ` ) position
of given label .
Parameters
label : object
side : { ' left ' , ' right ' }
kind : { ' ix ' , ' loc ' , ... | assert kind in [ 'ix' , 'loc' , 'getitem' , None ]
if side not in ( 'left' , 'right' ) :
raise ValueError ( "Invalid value for side kwarg," " must be either 'left' or 'right': %s" % ( side , ) )
original_label = label
# For datetime indices label may be a string that has to be converted
# to datetime boundary accor... |
async def prover_get_credentials_for_proof_req ( wallet_handle : int , proof_request_json : str ) -> str :
"""Gets human readable credentials matching the given proof request .
NOTE : This method is deprecated because immediately returns all fetched credentials .
Use < prover _ search _ credentials _ for _ proo... | logger = logging . getLogger ( __name__ )
logger . debug ( "prover_get_credentials_for_proof_req: >>> wallet_handle: %r, proof_request_json: %r" , wallet_handle , proof_request_json )
if not hasattr ( prover_get_credentials_for_proof_req , "cb" ) :
logger . debug ( "prover_get_credentials_for_proof_req: Creating ca... |
def split ( name , x , reverse = False , eps = None , eps_std = None , cond_latents = None , hparams = None , state = None , condition = False , temperature = 1.0 ) :
"""Splits / concatenates x into x1 and x2 across number of channels .
For the forward pass , x2 is assumed be gaussian ,
i . e P ( x2 | x1 ) ~ N ... | # TODO ( mechcoder ) Change the return type to be a dict .
with tf . variable_scope ( name , reuse = tf . AUTO_REUSE ) :
if not reverse :
x1 , x2 = tf . split ( x , num_or_size_splits = 2 , axis = - 1 )
# objective : P ( x2 | x1 ) ~ N ( x2 ; NN ( x1 ) )
prior_dist , state = compute_prior ( "... |
def add_fields ( self , log_record , record , message_dict ) :
"""add _ fields
: param log _ record : log record
: param record : log message
: param message _ dict : message dict""" | super ( SplunkFormatter , self ) . add_fields ( log_record , record , message_dict )
if not log_record . get ( 'timestamp' ) :
now = datetime . datetime . utcnow ( ) . strftime ( '%Y-%m-%dT%H:%M:%S.%fZ' )
log_record [ 'timestamp' ] = now |
def acquire ( self , block = True ) :
"""Acquire lock . Blocks until acquired if ` block ` is ` True ` , otherwise returns ` False ` if the lock could not be acquired .""" | while True : # Try to set the lock
if self . redis . set ( self . name , self . value , px = self . timeout , nx = True ) : # It ' s ours until the timeout now
return True
# Lock is taken
if not block :
return False
# If blocking , try again in a bit
time . sleep ( self . sleep ) |
def assemble_rom_code ( self , asm ) :
"""assemble the given code and program the ROM""" | stream = StringIO ( asm )
worker = assembler . Assembler ( self . processor , stream )
try :
result = worker . assemble ( )
except BaseException as e :
return e , None
self . rom . program ( result )
return None , result |
def deallocate ( self ) :
"""Releases all resources .""" | if self . _domain is not None :
domain_delete ( self . _domain , self . logger )
if self . _network is not None :
self . _network_delete ( )
if self . _storage_pool is not None :
self . _storage_pool_delete ( )
if self . _hypervisor is not None :
self . _hypervisor_delete ( ) |
def key ( self , frame ) :
"Return the sort key for the given frame ." | def keytuple ( primary ) :
if frame . frameno is None :
return ( primary , 1 )
return ( primary , 0 , frame . frameno )
# Look up frame by exact match
if type ( frame ) in self . frame_keys :
return keytuple ( self . frame_keys [ type ( frame ) ] )
# Look up parent frame for v2.2 frames
if frame . _... |
def get_wfdb_plot_items ( record , annotation , plot_sym ) :
"""Get items to plot from wfdb objects""" | # Get record attributes
if record :
if record . p_signal is not None :
signal = record . p_signal
elif record . d_signal is not None :
signal = record . d_signal
else :
raise ValueError ( 'The record has no signal to plot' )
fs = record . fs
sig_name = record . sig_name
s... |
def _set_interface_fe ( self , v , load = False ) :
"""Setter method for interface _ fe , mapped from YANG variable / rule / command / interface _ fe ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ interface _ fe is considered as a private
method . Backe... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = interface_fe . interface_fe , is_container = 'container' , presence = False , yang_name = "interface-fe" , rest_name = "" , parent = self , choice = ( u'cmdlist' , u'interface-t' ) , path_helper = self . _path_helper , extmet... |
def _handle_successor ( self , job , successor , all_successors ) :
"""Process each successor generated by the job , and return a new list of succeeding jobs .
: param VFGJob job : The VFGJob instance .
: param SimState successor : The succeeding state .
: param list all _ successors : A list of all successor... | # Initialize parameters
addr = job . addr
jumpkind = successor . history . jumpkind
# Get instruction pointer
if job . is_return_jump :
ret_target = job . call_stack . current_return_target
if ret_target is None : # We have no where to go according to our call stack . However , the callstack might be corrupted
... |
def generate_noise ( dimensions , stimfunction_tr , tr_duration , template , mask = None , noise_dict = None , temporal_proportion = 0.5 , iterations = None , fit_thresh = 0.05 , fit_delta = 0.5 , ) :
"""Generate the noise to be added to the signal .
Default noise parameters will create a noise volume with a stan... | # Check the input data
if template . max ( ) > 1.1 :
raise ValueError ( 'Template out of range' )
# Change to be an empty dictionary if it is None
if noise_dict is None :
noise_dict = { }
# Take in the noise dictionary and add any missing information
noise_dict = _noise_dict_update ( noise_dict )
# How many ite... |
def query_data_providers ( self , query , scope_name = None , scope_value = None ) :
"""QueryDataProviders .
[ Preview API ]
: param : class : ` < DataProviderQuery > < azure . devops . v5_0 . contributions . models . DataProviderQuery > ` query :
: param str scope _ name :
: param str scope _ value :
: r... | route_values = { }
if scope_name is not None :
route_values [ 'scopeName' ] = self . _serialize . url ( 'scope_name' , scope_name , 'str' )
if scope_value is not None :
route_values [ 'scopeValue' ] = self . _serialize . url ( 'scope_value' , scope_value , 'str' )
content = self . _serialize . body ( query , 'D... |
def get_type ( bind ) :
"""Detect the ideal type for the data , either using the explicit type
definition or the format ( for date , date - time , not supported by JSON ) .""" | types = bind . types + [ bind . schema . get ( 'format' ) ]
for type_name in ( 'date-time' , 'date' , 'decimal' , 'integer' , 'boolean' , 'number' , 'string' ) :
if type_name in types :
return type_name
return 'string' |
def load ( fh , encoding = None , is_verbose = False ) :
"""load a pickle , with a provided encoding
if compat is True :
fake the old class hierarchy
if it works , then return the new type objects
Parameters
fh : a filelike object
encoding : an optional encoding
is _ verbose : show exception output""" | try :
fh . seek ( 0 )
if encoding is not None :
up = Unpickler ( fh , encoding = encoding )
else :
up = Unpickler ( fh )
up . is_verbose = is_verbose
return up . load ( )
except ( ValueError , TypeError ) :
raise |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.