signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def dispatchEvent ( self , event , * args ) :
"""Fire all callbacks assigned to a particular event . To be called by
derivative classes .
: param * args : Additional arguments to be passed to the callback
function .""" | for callback in self . listeners [ event ] :
yield callback ( event , self , * args ) |
def validate_sum ( parameter_container , validation_message , ** kwargs ) :
"""Validate the sum of parameter value ' s .
: param parameter _ container : The container that use this validator .
: type parameter _ container : ParameterContainer
: param validation _ message : The message if there is validation e... | parameters = parameter_container . get_parameters ( False )
values = [ ]
for parameter in parameters :
if parameter . selected_option_type ( ) in [ SINGLE_DYNAMIC , STATIC ] :
values . append ( parameter . value )
sum_threshold = kwargs . get ( 'max' , 1 )
if None in values : # If there is None , just check... |
def make_slack_blueprint ( client_id = None , client_secret = None , scope = None , redirect_url = None , redirect_to = None , login_url = None , authorized_url = None , session_class = None , storage = None , ) :
"""Make a blueprint for authenticating with Slack using OAuth 2 . This requires
a client ID and clie... | scope = scope or [ "identify" , "chat:write:bot" ]
slack_bp = SlackBlueprint ( "slack" , __name__ , client_id = client_id , client_secret = client_secret , scope = scope , base_url = "https://slack.com/api/" , authorization_url = "https://slack.com/oauth/authorize" , token_url = "https://slack.com/api/oauth.access" , r... |
def trades ( self , cursor = None , order = 'asc' , limit = 10 , sse = False ) :
"""Retrieve the trades JSON from this instance ' s Horizon server .
Retrieve the trades JSON response for the account associated with
this : class : ` Address ` .
: param cursor : A paging token , specifying where to start return... | return self . horizon . account_trades ( self . address , cursor = cursor , order = order , limit = limit , sse = sse ) |
def get_requirement_warn ( self , line ) :
"""Gets name of test case that was not successfully imported .""" | res = self . REQ_WARN_SEARCH . search ( line )
try :
return LogItem ( res . group ( 1 ) , None , None )
except ( AttributeError , IndexError ) :
return None |
def assignmentComplete ( ) :
"""ASSIGNMENT COMPLETE Section 9.1.3""" | a = TpPd ( pd = 0x6 )
b = MessageType ( mesType = 0x29 )
# 00101001
c = RrCause ( )
packet = a / b / c
return packet |
def _reset_docs ( self ) :
"""Helper to clear the docs on RESET or filter mismatch .""" | _LOGGER . debug ( "resetting documents" )
self . change_map . clear ( )
self . resume_token = None
# Mark each document as deleted . If documents are not deleted
# they will be sent again by the server .
for snapshot in self . doc_tree . keys ( ) :
name = snapshot . reference . _document_path
self . change_map ... |
def load ( pathtovector , wordlist = ( ) , num_to_load = None , truncate_embeddings = None , unk_word = None , sep = " " ) :
r"""Read a file in word2vec . txt format .
The load function will raise a ValueError when trying to load items
which do not conform to line lengths .
Parameters
pathtovector : string ... | vectors , items = Reach . _load ( pathtovector , wordlist , num_to_load , truncate_embeddings , sep )
if unk_word is not None :
if unk_word not in set ( items ) :
unk_vec = np . zeros ( ( 1 , vectors . shape [ 1 ] ) )
vectors = np . concatenate ( [ unk_vec , vectors ] , 0 )
items = [ unk_wor... |
def _extract_array ( self , kwargs_list ) :
"""inverse of _ update _ kwargs
: param kwargs _ list :
: return :""" | if self . _solver_type == 'PROFILE_SHEAR' :
e1 = kwargs_list [ 1 ] [ 'e1' ]
e2 = kwargs_list [ 1 ] [ 'e2' ]
phi_ext , gamma_ext = param_util . ellipticity2phi_gamma ( e1 , e2 )
else :
phi_ext = 0
lens_model = self . _lens_mode_list [ 0 ]
if lens_model in [ 'SPEP' , 'SPEMD' , 'SIE' , 'NIE' ] :
e1 = k... |
def control ( self , on = [ ] , off = [ ] ) :
"""This method serves as the primary interaction point
to the controls interface .
- The ' on ' and ' off ' arguments can either be a list or a single string .
This allows for both individual device control and batch controls .
Note :
Both the onlist and offli... | controls = { "light" , "valve" , "fan" , "pump" }
def cast_arg ( arg ) :
if type ( arg ) is str :
if arg == "all" :
return controls
else :
return { arg } & controls
else :
return set ( arg ) & controls
# User has requested individual controls .
for item in cast_ar... |
def asyncPipeItembuilder ( context = None , _INPUT = None , conf = None , ** kwargs ) :
"""A source that asynchronously builds an item . Loopable .
Parameters
context : pipe2py . Context object
_ INPUT : asyncPipe like object ( twisted Deferred iterable of items )
conf : {
' attrs ' : [
{ ' key ' : { ' ... | pkwargs = cdicts ( opts , kwargs )
asyncFuncs = yield asyncGetSplits ( None , conf [ 'attrs' ] , ** pkwargs )
_input = yield _INPUT
finite = utils . finitize ( _input )
inputs = imap ( DotDict , finite )
pieces = yield asyncImap ( asyncFuncs [ 0 ] , inputs )
results = imap ( utils . parse_params , pieces )
_OUTPUT = im... |
def start_listener ( self ) :
'''start listening for packets''' | if self . sock is not None :
self . sock . close ( )
self . sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM , socket . IPPROTO_UDP )
self . sock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 )
self . sock . bind ( ( '' , self . asterix_settings . port ) )
self . sock . setblocking (... |
def dump ( self , f ) :
"""Dump data to a file .
: param f : file - like object or path to file
: type f : file or str""" | self . validate ( )
with _open_file_obj ( f , "w" ) as f :
parser = self . _get_parser ( )
self . serialize ( parser )
self . build_file ( parser , f ) |
def get_projects ( self , ** kwargs ) :
"""Get a user ' s project .
: param str login : User ' s login ( Default : self . _ login )
: return : JSON""" | _login = kwargs . get ( 'login' , self . _login )
search_url = SEARCH_URL . format ( login = _login )
return self . _request_api ( url = search_url ) . json ( ) |
def get_index ( self , value ) :
"""Return the index ( or indices ) of the given value ( or values ) in
` state _ values ` .
Parameters
value
Value ( s ) to get the index ( indices ) for .
Returns
idx : int or ndarray ( int )
Index of ` value ` if ` value ` is a single state value ; array
of indices... | if self . state_values is None :
state_values_ndim = 1
else :
state_values_ndim = self . state_values . ndim
values = np . asarray ( value )
if values . ndim <= state_values_ndim - 1 :
return self . _get_index ( value )
elif values . ndim == state_values_ndim : # array of values
k = values . shape [ 0 ]... |
def validator ( flag_name , message = 'Flag validation failed' , flag_values = _flagvalues . FLAGS ) :
"""A function decorator for defining a flag validator .
Registers the decorated function as a validator for flag _ name , e . g .
@ flags . validator ( ' foo ' )
def _ CheckFoo ( foo ) :
See register _ val... | def decorate ( function ) :
register_validator ( flag_name , function , message = message , flag_values = flag_values )
return function
return decorate |
def crop ( self , vector , resolution = None , masked = None , bands = None , resampling = Resampling . cubic ) :
"""crops raster outside vector ( convex hull )
: param vector : GeoVector , GeoFeature , FeatureCollection
: param resolution : output resolution , None for full resolution
: param resampling : re... | bounds , window = self . _vector_to_raster_bounds ( vector . envelope , boundless = self . _image is None )
if resolution :
xsize , ysize = self . _resolution_to_output_shape ( bounds , resolution )
else :
xsize , ysize = ( None , None )
return self . pixel_crop ( bounds , xsize , ysize , window = window , mask... |
def get_address_transactions ( self , account_id , address_id , ** params ) :
"""https : / / developers . coinbase . com / api / v2 # list - address39s - transactions""" | response = self . _get ( 'v2' , 'accounts' , account_id , 'addresses' , address_id , 'transactions' , params = params )
return self . _make_api_object ( response , Transaction ) |
def _register_server ( self , server , timeout = 30 ) :
'''Register a new SiriDB Server .
This method is used by the SiriDB manage tool and should not be used
otherwise . Full access rights are required for this request .''' | result = self . _loop . run_until_complete ( self . _protocol . send_package ( CPROTO_REQ_REGISTER_SERVER , data = server , timeout = timeout ) )
return result |
def is_name_zonefile_hash ( name , zonefile_hash , hostport = None , proxy = None ) :
"""Determine if a name set a given zone file hash .
Return { ' result ' : True / False } if so
Return { ' error ' : . . . } on error""" | assert hostport or proxy , 'Need hostport or proxy'
if proxy is None :
proxy = connect_hostport ( hostport )
zonefile_check_schema = { 'type' : 'object' , 'properties' : { 'result' : { 'type' : 'boolean' } } , 'required' : [ 'result' ] }
schema = json_response_schema ( zonefile_check_schema )
resp = { }
try :
r... |
def save_share_list ( self , url , path , password = None , filter_callback = None ) :
"""保存分享文件列表到自己的网盘 , 支持密码 , 支持文件过滤的回调函数
: param url : 分享的url
: type url : str
: param path 保存到自己网盘的位置
: type path : str
: param password 分享密码 , 如果没有分享资源没有密码则不用填
: type password : str
: param filter _ callback 过滤文件列表中... | # 这里无论是短链接还是长链接如果带密码 , 则都被重定向到长链接 , 可以直接取出shareid , uk
# 而如果是不带密码的分享 , 则此时还不需要shareid , uk
respond = self . _request ( None , url = url )
target_url = respond . url
surl = re . search ( r"surl=([a-zA-Z\d]+)" , target_url )
if surl is None :
surl = re . search ( r"s/([a-zA-Z\d]+)" , target_url ) . group ( 1 ) [ 1 : ... |
def p_int ( self , tree ) :
'''V : : = INTEGER''' | tree . value = int ( tree . attr )
tree . svalue = tree . attr |
def read ( self , length , timeout_ms = 0 , blocking = False ) :
"""Read an Input report from a HID device with timeout .
Input reports are returned to the host through the ` INTERRUPT IN `
endpoint . The first byte will contain the Report number if the device
uses numbered reports .
By default reads are no... | self . _check_device_status ( )
bufp = ffi . new ( "unsigned char[]" , length )
if not timeout_ms and blocking :
timeout_ms = - 1
if timeout_ms :
rv = hidapi . hid_read_timeout ( self . _device , bufp , length , timeout_ms )
else :
rv = hidapi . hid_read ( self . _device , bufp , length )
if rv == - 1 :
... |
def get_now_datetime_filestamp ( longTime = False ) :
"""* A datetime stamp to be appended to the end of filenames : ` ` YYYYMMDDtHHMMSS ` ` *
* * Key Arguments : * *
- ` ` longTime ` ` - - make time string longer ( more change of filenames being unique )
* * Return : * *
- ` ` now ` ` - - current time and ... | # # > IMPORTS # #
from datetime import datetime , date , time
now = datetime . now ( )
if longTime :
now = now . strftime ( "%Y%m%dt%H%M%S%f" )
else :
now = now . strftime ( "%Y%m%dt%H%M%S" )
return now |
def _remove_leading_dots_for_smtp_transparency_support ( self , input_data ) :
"""Uses the input data to recover the original payload ( includes
transparency support as specified in RFC 821 , Section 4.5.2 ) .""" | regex = re . compile ( '^\.\.' , re . MULTILINE )
data_without_transparency_dots = regex . sub ( '.' , input_data )
return re . sub ( '\r\n' , '\n' , data_without_transparency_dots ) |
def ends_at ( self , time_point ) :
"""Returns ` ` True ` ` if this interval ends at the given time point .
: param time _ point : the time point to test
: type time _ point : : class : ` ~ aeneas . exacttiming . TimeValue `
: raises TypeError : if ` ` time _ point ` ` is not an instance of ` ` TimeValue ` ` ... | if not isinstance ( time_point , TimeValue ) :
raise TypeError ( u"time_point is not an instance of TimeValue" )
return self . end == time_point |
def distance_sphere ( self , other , radius = 6371.0 ) :
'''- - Deprecated in v0.70 . Use distance ( other , ellipse = ' sphere ' ) instead - -
Returns great circle distance between two lat / lon coordinates on a sphere
using the Haversine formula . The default radius corresponds to the FAI sphere
with units ... | warnings . warn ( "Deprecated in v0.70. Use distance(other, ellipse = 'sphere') instead" , DeprecationWarning )
lat1 , lon1 = self . lat . decimal_degree , self . lon . decimal_degree
lat2 , lon2 = other . lat . decimal_degree , other . lon . decimal_degree
pi = math . pi / 180.
# phi is 90 - latitude
phi1 = ( 90. - la... |
def list ( context , resource , ** kwargs ) :
"""List all resources""" | data = utils . sanitize_kwargs ( ** kwargs )
id = data . pop ( 'id' , None )
subresource = data . pop ( 'subresource' , None )
if subresource :
uri = '%s/%s/%s/%s' % ( context . dci_cs_api , resource , id , subresource )
else :
uri = '%s/%s' % ( context . dci_cs_api , resource )
return context . session . get (... |
def post ( self ) :
"""Register a new model ( models )""" | self . set_header ( "Content-Type" , "application/json" )
key = uuid . uuid4 ( ) . hex
metadata = json . loads ( self . request . body . decode ( ) )
metadata [ "uuid" ] = key
self . database [ key ] = metadata
result = json . dumps ( { "uuid" : key } )
self . write ( result ) |
def plot_related_data ( x , y , code , ylabel , fileName , options ) :
"""Plot Z1 and Z2 in function of IBS2 * ratio .
: param x : the x axis of the plot ( ` ` IBS2 ratio ` ` ) .
: param y : the y axis of the plot ( either ` ` z1 ` ` or ` ` z2 ` ` ) .
: param code : the code of the relatedness of each sample ... | import matplotlib as mpl
if mpl . get_backend ( ) != "agg" :
mpl . use ( "Agg" )
import matplotlib . pyplot as plt
plt . ioff ( )
fig = plt . figure ( )
ax = fig . add_subplot ( 111 )
# Setting the title , the X and Y label
ax . set_title ( ( r"%d pairs with $IBS2^\ast_{ratio} >$ " r"%f" % ( len ( code ) , options ... |
def next_batch ( self , n = 1 ) :
"""Return the next requests that should be dispatched .""" | if len ( self . queue ) == 0 :
return [ ]
batch = list ( reversed ( ( self . queue [ - n : ] ) ) )
self . queue = self . queue [ : - n ]
return batch |
def model_data ( self ) :
"""str : The model location in S3 . Only set if Estimator has been ` ` fit ( ) ` ` .""" | if self . latest_training_job is not None :
model_uri = self . sagemaker_session . sagemaker_client . describe_training_job ( TrainingJobName = self . latest_training_job . name ) [ 'ModelArtifacts' ] [ 'S3ModelArtifacts' ]
else :
logging . warning ( 'No finished training job found associated with this estimato... |
def read_file ( self , infile ) :
"""Read a reST file into a string .""" | try :
with open ( infile , 'rt' ) as file :
return file . read ( )
except UnicodeDecodeError as e :
err_exit ( 'Error reading %s: %s' % ( infile , e ) )
except ( IOError , OSError ) as e :
err_exit ( 'Error reading %s: %s' % ( infile , e . strerror or e ) ) |
def save_devices ( self ) :
"""save devices that have been obtained from LaMetric cloud
to a local file""" | log . debug ( "saving devices to ''..." . format ( self . _devices_filename ) )
if self . _devices != [ ] :
with codecs . open ( self . _devices_filename , "wb" , "utf-8" ) as f :
json . dump ( self . _devices , f ) |
def scatter ( * args , ** kwargs ) :
"""This will plot a scatterplot of x and y , iterating over the ColorBrewer
" Set2 " color cycle unless a color is specified . The symbols produced are
empty circles , with the outline in the color specified by either ' color '
or ' edgecolor ' . If you want to fill the ci... | # Force ' color ' to indicate the edge color , so the middle of the
# scatter patches are empty . Can specify
ax , args , kwargs = utils . maybe_get_ax ( * args , ** kwargs )
if 'color' not in kwargs : # Assume that color means the edge color . You can assign the
color_cycle = ax . _get_lines . color_cycle
kwar... |
def parse_param_signature ( sig ) :
"""Parse a parameter signature of the form : type name ( = default ) ?""" | match = PARAM_SIG_RE . match ( sig . strip ( ) )
if not match :
raise RuntimeError ( 'Parameter signature invalid, got ' + sig )
groups = match . groups ( )
modifiers = groups [ 0 ] . split ( )
typ , name , _ , default = groups [ - 4 : ]
return ParamTuple ( name = name , typ = typ , default = default , modifiers = ... |
async def probe ( self ) :
"""Probe for devices .
This method will probe all adapters that can probe and will send a
notification for all devices that we have seen from all adapters .
See : meth : ` AbstractDeviceAdapter . probe ` .""" | for adapter in self . adapters :
if adapter . get_config ( 'probe_supported' , False ) :
await adapter . probe ( ) |
def alter_old_distutils_request ( request : WSGIRequest ) :
"""Alter the request body for compatibility with older distutils clients
Due to a bug in the Python distutils library , the request post is sent
using \n as a separator instead of the \r \n that the HTTP spec demands .
This breaks the Django form par... | # We first need to retrieve the body before accessing POST or FILES since
# it can only be read once .
body = request . body
if request . POST or request . FILES :
return
new_body = BytesIO ( )
# Split the response in the various parts based on the boundary string
content_type , opts = parse_header ( request . META... |
def cluster_nodes ( self ) :
"""Each node in a Redis Cluster has its view of the current cluster
configuration , given by the set of known nodes , the state of the
connection we have with such nodes , their flags , properties and
assigned slots , and so forth .
` ` CLUSTER NODES ` ` provides all this inform... | def format_response ( result ) :
values = [ ]
for row in result . decode ( 'utf-8' ) . split ( '\n' ) :
if not row :
continue
parts = row . split ( ' ' )
slots = [ ]
for slot in parts [ 8 : ] :
if '-' in slot :
sparts = slot . split ( '-' )... |
def language_name ( self , language = DEFAULT_LANGUAGE , min_score : int = 75 ) -> str :
"""Give the name of the language ( not the entire tag , just the language part )
in a natural language . The target language can be given as a string or
another Language object .
By default , things are named in English :... | return self . _get_name ( 'language' , language , min_score ) |
def get_definitions ( self , project , name = None , repository_id = None , repository_type = None , query_order = None , top = None , continuation_token = None , min_metrics_time = None , definition_ids = None , path = None , built_after = None , not_built_after = None , include_all_properties = None , include_latest_... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
query_parameters = { }
if name is not None :
query_parameters [ 'name' ] = self . _serialize . query ( 'name' , name , 'str' )
if repository_id is not None :
query_parameters [ 'r... |
def parse_preview ( self , raw_content ) :
"""Parse the preview part of the content ,
and return the parsed string and whether there is more content or not .
If the preview part is equal to the whole part ,
the second element of the returned tuple will be False , else True .
: param raw _ content : raw cont... | if self . _read_more_exp is None :
return self . parse_whole ( raw_content ) , False
sp = self . _read_more_exp . split ( raw_content , maxsplit = 1 )
if len ( sp ) == 2 and sp [ 0 ] :
has_more_content = True
result = sp [ 0 ] . rstrip ( )
else :
has_more_content = False
result = raw_content
# since... |
def quote ( query ) :
'''Quote query with sign ( ' )''' | if query . startswith ( '\'' ) is not True :
query = '\'' + query
if query . endswith ( '\'' ) is not True :
query = query + '\''
return query |
def make_spatialmap_source ( name , Spatial_Filename , spectrum ) :
"""Construct and return a ` fermipy . roi _ model . Source ` object""" | data = dict ( Spatial_Filename = Spatial_Filename , ra = 0.0 , dec = 0.0 , SpatialType = 'SpatialMap' , Source_Name = name )
if spectrum is not None :
data . update ( spectrum )
return roi_model . Source ( name , data ) |
def get_bool_resources ( self , package_name , locale = '\x00\x00' ) :
"""Get the XML ( as string ) of all resources of type ' bool ' .
Read more about bool resources :
https : / / developer . android . com / guide / topics / resources / more - resources . html # Bool
: param package _ name : the package name... | self . _analyse ( )
buff = '<?xml version="1.0" encoding="utf-8"?>\n'
buff += '<resources>\n'
try :
for i in self . values [ package_name ] [ locale ] [ "bool" ] :
buff += '<bool name="{}">{}</bool>\n' . format ( i [ 0 ] , i [ 1 ] )
except KeyError :
pass
buff += '</resources>\n'
return buff . encode ( ... |
def update ( cls , card_id , card_generated_cvc2_id , type_ = None , custom_headers = None ) :
""": type user _ id : int
: type card _ id : int
: type card _ generated _ cvc2 _ id : int
: param type _ : The type of generated cvc2 . Can be STATIC or GENERATED .
: type type _ : str
: type custom _ headers :... | if custom_headers is None :
custom_headers = { }
api_client = client . ApiClient ( cls . _get_api_context ( ) )
request_map = { cls . FIELD_TYPE : type_ }
request_map_string = converter . class_to_json ( request_map )
request_map_string = cls . _remove_field_for_request ( request_map_string )
request_bytes = reques... |
def read_file_1st_col_only ( fname ) :
"""read a CSV file ( ref _ classes . csv ) and return the
list of names""" | lst = [ ]
with open ( fname , 'r' ) as f :
_ = f . readline ( )
# read the header and ignore it
for line in f :
lst . append ( line . split ( ',' ) [ 0 ] )
return lst |
def set_min_requests_per_connection ( self , host_distance , min_requests ) :
"""Sets a threshold for concurrent requests per connection , below which
connections will be considered for disposal ( down to core connections ;
see : meth : ` ~ Cluster . set _ core _ connections _ per _ host ` ) .
Pertains to con... | if self . protocol_version >= 3 :
raise UnsupportedOperation ( "Cluster.set_min_requests_per_connection() only has an effect " "when using protocol_version 1 or 2." )
if min_requests < 0 or min_requests > 126 or min_requests >= self . _max_requests_per_connection [ host_distance ] :
raise ValueError ( "min_requ... |
def on_message ( self , unused_channel , basic_deliver , properties , body ) :
"""Invoked by pika when a message is delivered from RabbitMQ . The
channel is passed for your convenience . The basic _ deliver object that
is passed in carries the exchange , routing key , delivery tag and
a redelivered flag for t... | _logger . debug ( 'Received message # %s from %s: %s' , basic_deliver . delivery_tag , properties . app_id , body )
if self . ws and body :
self . messages . append ( body )
_logger . debug ( 'out ws : %s' , len ( self . ws ) )
_logger . debug ( 'out messages : %s' , len ( self . messages ) )
self . acknowledge_mes... |
def visit_comprehension ( self , node ) :
"""return an astroid . Comprehension node as string""" | ifs = "" . join ( " if %s" % n . accept ( self ) for n in node . ifs )
return "for %s in %s%s" % ( node . target . accept ( self ) , node . iter . accept ( self ) , ifs , ) |
def validateDocumentFinal ( self , doc ) :
"""Does the final step for the document validation once all
the incremental validation steps have been completed
basically it does the following checks described by the XML
Rec Check all the IDREF / IDREFS attributes definition for
validity""" | if doc is None :
doc__o = None
else :
doc__o = doc . _o
ret = libxml2mod . xmlValidateDocumentFinal ( self . _o , doc__o )
return ret |
def show_print_dialog ( self ) :
"""Open the print dialog""" | if not self . impact_function : # Now try to read the keywords and show them in the dock
try :
active_layer = self . iface . activeLayer ( )
keywords = self . keyword_io . read_keywords ( active_layer )
provenances = keywords . get ( 'provenance_data' , { } )
extra_keywords = keyword... |
def add_edge ( self , fr , to ) :
"""Add an outward edge to a vertex
: param fr : The source vertex .
: param to : The name of the outward edge .""" | if fr not in set ( self . graph . vs ) : # ToDo : find out why item can be in set but not dict
raise ValueError ( 'can not connect unknown vertices in n-partite graphs, {!r} missing' . format ( fr ) )
elif to not in set ( self . graph . vs ) :
raise ValueError ( 'can not connect unknown vertices in n-partite gr... |
def read_int64 ( self , little_endian = True ) :
"""Read 8 bytes as a signed integer value from the stream .
Args :
little _ endian ( bool ) : specify the endianness . ( Default ) Little endian .
Returns :
int :""" | if little_endian :
endian = "<"
else :
endian = ">"
return self . unpack ( '%sq' % endian , 8 ) |
def CountHuntFlows ( self , hunt_id , filter_condition = db . HuntFlowsCondition . UNSET , cursor = None ) :
"""Counts hunt flows matching given conditions .""" | hunt_id_int = db_utils . HuntIDToInt ( hunt_id )
query = ( "SELECT COUNT(*) FROM flows " "FORCE INDEX(flows_by_hunt) " "WHERE parent_hunt_id = %s AND parent_flow_id IS NULL " "{filter_condition}" )
filter_query , extra_args = self . _HuntFlowCondition ( filter_condition )
args = [ hunt_id_int ] + extra_args
query = que... |
def get ( name : str , required : bool = False , default : Union [ Type [ empty ] , T ] = empty , type : Type [ T ] = None ) -> T :
"""Generic getter for environment variables . Handles defaults ,
required - ness , and what type to expect .
: param name : The name of the environment variable be pulled
: type ... | fns = { 'int' : env_int , int : env_int , # ' float ' : env _ float ,
# float : env _ float ,
'bool' : env_bool , bool : env_bool , 'string' : env_string , str : env_string , 'list' : env_list , list : env_list , }
# type : Dict [ Union [ str , Type [ Any ] ] , Callable [ . . . , Any ] ]
fn = fns . get ( type , env_str... |
def rebase_opt ( self ) :
"""Determine which option name to use .""" | if not hasattr ( self , '_rebase_opt' ) : # out = b " MAJOR . MINOR . REVISION " / / b " 3.4.19 " or b " 4.0.0"
out , err = Popen ( [ 'cleancss' , '--version' ] , stdout = PIPE ) . communicate ( )
ver = int ( out [ : out . index ( b'.' ) ] )
self . _rebase_opt = [ '--root' , self . root ] if ver == 3 else [... |
def channels_voice_phone_number_show ( self , id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / voice - api / phone _ numbers # show - phone - number" | api_path = "/api/v2/channels/voice/phone_numbers/{id}.json"
api_path = api_path . format ( id = id )
return self . call ( api_path , ** kwargs ) |
def _checkFileExists ( self ) :
"""Verifies that the underlying file exists and sets the _ exception attribute if not
Returns True if the file exists .
If self . _ fileName is None , nothing is checked and True is returned .""" | if self . _fileName and not os . path . exists ( self . _fileName ) :
msg = "File not found: {}" . format ( self . _fileName )
logger . error ( msg )
self . setException ( IOError ( msg ) )
return False
else :
return True |
def build_gui ( self , container ) :
"""Build GUI such that image list area is maximized .""" | vbox , sw , orientation = Widgets . get_oriented_box ( container )
captions = ( ( 'Channel:' , 'label' , 'Channel Name' , 'combobox' , 'Modified only' , 'checkbutton' ) , )
w , b = Widgets . build_info ( captions , orientation = orientation )
self . w . update ( b )
b . channel_name . set_tooltip ( 'Channel for locatin... |
def map_compute_fov ( m : tcod . map . Map , x : int , y : int , radius : int = 0 , light_walls : bool = True , algo : int = FOV_RESTRICTIVE , ) -> None :
"""Compute the field - of - view for a map instance .
. . deprecated : : 4.5
Use : any : ` tcod . map . Map . compute _ fov ` instead .""" | m . compute_fov ( x , y , radius , light_walls , algo ) |
def project_events ( self , initial_state , domain_events ) :
"""Evolves initial state using the sequence of domain events and a mutator function .""" | return reduce ( self . _mutator_func or self . mutate , domain_events , initial_state ) |
def _set ( self , obj , value ) :
"""Internal method to set state , called by meth : ` StateTransition . _ _ call _ _ `""" | if value not in self . lenum :
raise ValueError ( "Not a valid value: %s" % value )
type ( obj ) . __dict__ [ self . propname ] . __set__ ( obj , value ) |
def delete_example ( self , example_id , url = 'https://api.shanbay.com/bdc/example/{example_id}/' ) :
"""删除例句""" | url = url . format ( example_id = example_id )
return self . _request ( url , method = 'delete' ) . json ( ) |
def derivative ( self , point ) :
r"""Derivative of this operator in ` ` point ` ` .
` ` NormOperator ( ) . derivative ( y ) ( x ) = = ( y / y . norm ( ) ) . inner ( x ) ` `
This is only applicable in inner product spaces .
Parameters
point : ` domain ` ` element - like `
Point in which to take the deriva... | point = self . domain . element ( point )
norm = point . norm ( )
if norm == 0 :
raise ValueError ( 'not differentiable in 0' )
return InnerProductOperator ( point / norm ) |
def sendNotification ( snmpEngine , authData , transportTarget , contextData , notifyType , * varBinds , ** options ) :
"""Creates a generator to send SNMP notification .
When iterator gets advanced by : py : mod : ` asyncio ` main loop ,
SNMP TRAP or INFORM notification is send ( : RFC : ` 1905 # section - 4.2... | def __cbFun ( snmpEngine , sendRequestHandle , errorIndication , errorStatus , errorIndex , varBinds , cbCtx ) :
lookupMib , future = cbCtx
if future . cancelled ( ) :
return
try :
varBindsUnmade = VB_PROCESSOR . unmakeVarBinds ( snmpEngine . cache , varBinds , lookupMib )
except Excepti... |
def _Pluralize ( value , unused_context , args ) :
"""Formatter to pluralize words .""" | if len ( args ) == 0 :
s , p = '' , 's'
elif len ( args ) == 1 :
s , p = '' , args [ 0 ]
elif len ( args ) == 2 :
s , p = args
else : # Should have been checked at compile time
raise AssertionError
if value > 1 :
return p
else :
return s |
def get_items ( self ) :
"""Return items ( excluding top level items )""" | itemlist = [ ]
def add_to_itemlist ( item ) :
for index in range ( item . childCount ( ) ) :
citem = item . child ( index )
itemlist . append ( citem )
add_to_itemlist ( citem )
for tlitem in self . get_top_level_items ( ) :
add_to_itemlist ( tlitem )
return itemlist |
def from_yaml ( self , path ) :
"""Register bundles from a YAML configuration file""" | bundles = YAMLLoader ( path ) . load_bundles ( )
for name in bundles :
self . register ( name , bundles [ name ] ) |
def read_very_lazy ( self ) :
"""Return any data available in the cooked queue ( very lazy ) .
Raise EOFError if connection closed and no data available .
Return ' ' if no cooked data available otherwise . Don ' t block .""" | buf = self . cookedq . getvalue ( )
self . cookedq . seek ( 0 )
self . cookedq . truncate ( )
if not buf and self . eof and not self . rawq :
raise EOFError ( 'telnet connection closed' )
return buf |
def reassign_comment_to_book ( self , comment_id , from_book_id , to_book_id ) :
"""Moves a ` ` Credit ` ` from one ` ` Book ` ` to another .
Mappings to other ` ` Books ` ` are unaffected .
arg : comment _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Comment ` `
arg : from _ book _ id ( osid . id . Id )... | # Implemented from template for
# osid . resource . ResourceBinAssignmentSession . reassign _ resource _ to _ bin
self . assign_comment_to_book ( comment_id , to_book_id )
try :
self . unassign_comment_from_book ( comment_id , from_book_id )
except : # something went wrong , roll back assignment to to _ book _ id
... |
def _are_coordinates_valid ( self ) :
"""Check if the coordinates are valid .
: return : True if coordinates are valid otherwise False .
: type : bool""" | try :
QgsPointXY ( self . x_minimum . value ( ) , self . y_maximum . value ( ) )
QgsPointXY ( self . x_maximum . value ( ) , self . y_minimum . value ( ) )
except ValueError :
return False
return True |
def write_temporary_file ( content , prefix = '' , suffix = '' ) :
"""Generating a temporary file with content .
Args :
content ( str ) : file content ( usually a script , Dockerfile , playbook or config file )
prefix ( str ) : the filename starts with this prefix ( default : no prefix )
suffix ( str ) : th... | temp = tempfile . NamedTemporaryFile ( prefix = prefix , suffix = suffix , mode = 'w+t' , delete = False )
temp . writelines ( content )
temp . close ( )
return temp . name |
def posterior ( self , x , s = 1. ) :
"""Model is X _ 1 , . . . , X _ n ~ N ( theta , s ^ 2 ) , theta ~ self , s fixed""" | pr0 = 1. / self . sigma ** 2
# prior precision
prd = x . size / s ** 2
# data precision
varp = 1. / ( pr0 + prd )
# posterior variance
mu = varp * ( pr0 * self . mu + prd * x . mean ( ) )
return TruncNormal ( mu = mu , sigma = np . sqrt ( varp ) , a = self . a , b = self . b ) |
def send ( self , value ) :
"""Send text to stdin . Can only be used on non blocking commands
Args :
value ( str ) : the text to write on stdin
Raises :
TypeError : If command is blocking
Returns :
ShellCommand : return this ShellCommand instance for chaining""" | if not self . block and self . _stdin is not None :
self . writer . write ( "{}\n" . format ( value ) )
return self
else :
raise TypeError ( NON_BLOCKING_ERROR_MESSAGE ) |
def mutate_label ( label ) :
"""BigQuery field _ name should start with a letter or underscore and contain only
alphanumeric characters . Labels that start with a number are prefixed with an
underscore . Any unsupported characters are replaced with underscores and an
md5 hash is added to the end of the label ... | label_hashed = '_' + hashlib . md5 ( label . encode ( 'utf-8' ) ) . hexdigest ( )
# if label starts with number , add underscore as first character
label_mutated = '_' + label if re . match ( r'^\d' , label ) else label
# replace non - alphanumeric characters with underscores
label_mutated = re . sub ( r'[^\w]+' , '_' ... |
def setRedYellowGreenState ( self , tlsID , state ) :
"""setRedYellowGreenState ( string , string ) - > None
Sets the named tl ' s state as a tuple of light definitions from
rugGyYuoO , for red , red - yellow , green , yellow , off , where lower case letters mean that the stream has to decelerate .""" | self . _connection . _sendStringCmd ( tc . CMD_SET_TL_VARIABLE , tc . TL_RED_YELLOW_GREEN_STATE , tlsID , state ) |
def get_Object_or_None ( klass , * args , ** kwargs ) :
"""Uses get ( ) to return an object , or None if the object does not exist .
klass may be a Model , Manager , or QuerySet object . All other passed
arguments and keyword arguments are used in the get ( ) query .
Note : Like with get ( ) , an MultipleObje... | queryset = _get_queryset ( klass )
try :
if args :
return queryset . using ( args [ 0 ] ) . get ( ** kwargs )
else :
return queryset . get ( * args , ** kwargs )
except queryset . model . DoesNotExist :
return None |
def _server_property ( self , attr_name ) :
"""An attribute of the current server ' s description .
If the client is not connected , this will block until a connection is
established or raise ServerSelectionTimeoutError if no server is
available .
Not threadsafe if used multiple times in a single method , s... | server = self . _topology . select_server ( writable_server_selector )
return getattr ( server . description , attr_name ) |
def mpim_close ( self , * , channel : str , ** kwargs ) -> SlackResponse :
"""Closes a multiparty direct message channel .
Args :
channel ( str ) : Multiparty Direct message channel to close . e . g . ' G1234567890'""" | kwargs . update ( { "channel" : channel } )
return self . api_call ( "mpim.close" , json = kwargs ) |
def plot_diagrams ( results , configs , compiler , out_dir ) :
"""Plot all diagrams specified by the configs""" | compiler_fn = make_filename ( compiler )
total = psutil . virtual_memory ( ) . total
# pylint : disable = I0011 , E1101
memory = int ( math . ceil ( byte_to_gb ( total ) ) )
images_dir = os . path . join ( out_dir , 'images' )
for config in configs :
out_prefix = '{0}_{1}' . format ( config [ 'name' ] , compiler_fn... |
def info ( text , * args , ** kwargs ) :
'''Display informations''' | text = text . format ( * args , ** kwargs )
print ( ' ' . join ( ( purple ( '>>>' ) , text ) ) )
sys . stdout . flush ( ) |
def last_available_business_date ( self , asset_manager_id , asset_ids , page_no = None , page_size = None ) :
"""Returns the last available business date for the assets so we know the
starting date for new data which needs to be downloaded from data providers .
This method can only be invoked by system user""" | self . logger . info ( 'Retrieving last available business dates for assets' )
url = '%s/last-available-business-date' % self . endpoint
params = { 'asset_manager_ids' : [ asset_manager_id ] , 'asset_ids' : ',' . join ( asset_ids ) }
if page_no :
params [ 'page_no' ] = page_no
if page_size :
params [ 'page_size... |
def Lehrer ( m , Dtank , Djacket , H , Dinlet , rho , Cp , k , mu , muw = None , isobaric_expansion = None , dT = None , inlettype = 'tangential' , inletlocation = 'auto' ) :
r'''Calculates average heat transfer coefficient for a jacket around a
vessel according to [ 1 ] _ as described in [ 2 ] _ .
. . math : :... | delta = ( Djacket - Dtank ) / 2.
Q = m / rho
Pr = Cp * mu / k
vs = Q / H / delta
vo = Q / ( pi / 4 * Dinlet ** 2 )
if dT and isobaric_expansion and inlettype == 'radial' and inletlocation :
if dT > 0 : # Heating jacket fluid
if inletlocation == 'auto' or inletlocation == 'bottom' :
va = 0.5 * ( ... |
def handle_transport_fail ( self , exception = None , ** kwargs ) :
"""Failure handler called by the transport on send failure""" | message = str ( exception )
logger . error ( "Failed to submit message: %r" , message , exc_info = getattr ( exception , "print_trace" , True ) )
self . state . set_fail ( ) |
def load_retaildata ( ) :
"""Monthly retail trade data from census . gov .""" | # full = ' https : / / www . census . gov / retail / mrts / www / mrtssales92 - present . xls '
# indiv = ' https : / / www . census . gov / retail / marts / www / timeseries . html '
db = { "Auto, other Motor Vehicle" : "https://www.census.gov/retail/marts/www/adv441x0.txt" , "Building Material and Garden Equipment an... |
def _edges2conns ( G , edge_data = False ) :
"""Create a mapping from graph edges to agent connections to be created .
: param G :
NetworkX ' s Graph or DiGraph which has : attr : ` addr ` attribute for each
node .
: param bool edge _ data :
If ` ` True ` ` , stores also edge data to the returned dictiona... | cm = { }
for n in G . nodes ( data = True ) :
if edge_data :
cm [ n [ 1 ] [ 'addr' ] ] = [ ( G . node [ nb ] [ 'addr' ] , G [ n [ 0 ] ] [ nb ] ) for nb in G [ n [ 0 ] ] ]
else :
cm [ n [ 1 ] [ 'addr' ] ] = [ ( G . node [ nb ] [ 'addr' ] , { } ) for nb in G [ n [ 0 ] ] ]
return cm |
def validate_regexp ( pattern , flags = 0 ) :
"""Validate the field matches the given regular expression .
Should work with anything that supports ' = = ' operator .
: param pattern : Regular expresion to match . String or regular expression instance .
: param pattern : Flags for the regular expression .
: ... | regex = re . compile ( pattern , flags ) if isinstance ( pattern , str ) else pattern
def regexp_validator ( field , data ) :
if field . value is None :
return
if regex . match ( str ( field . value ) ) is None :
raise ValidationError ( 'regexp' , pattern = pattern )
return regexp_validator |
def _pack ( self , content ) :
"""pack the content using serializer and compressor""" | if self . serializer :
content = self . serializer . serialize ( content )
if self . compressor :
content = self . compressor . compress ( content )
return content |
def _ellipse_phantom_2d ( space , ellipses ) :
"""Create a phantom of ellipses in 2d space .
Parameters
space : ` DiscreteLp `
Uniformly discretized space in which the phantom should be generated .
If ` ` space . shape ` ` is 1 in an axis , a corresponding slice of the
phantom is created ( instead of squa... | # Blank image
p = np . zeros ( space . shape , dtype = space . dtype )
minp = space . grid . min_pt
maxp = space . grid . max_pt
# Create the pixel grid
grid_in = space . grid . meshgrid
# move points to [ - 1 , 1]
grid = [ ]
for i in range ( 2 ) :
mean_i = ( minp [ i ] + maxp [ i ] ) / 2.0
# Where space . shap... |
def stem ( self , word ) :
"""Perform stemming on an input word .""" | if self . stemmer :
return unicode_to_ascii ( self . _stemmer . stem ( word ) )
else :
return word |
def add ( self , items , force = True , fprogress = lambda * args : None , path_rewriter = None , write = True , write_extension_data = False ) :
"""Add files from the working tree , specific blobs or BaseIndexEntries
to the index .
: param items :
Multiple types of items are supported , types can be mixed wi... | # sort the entries into strings and Entries , Blobs are converted to entries
# automatically
# paths can be git - added , for everything else we use git - update - index
paths , entries = self . _preprocess_add_items ( items )
entries_added = [ ]
# This code needs a working tree , therefore we try not to run it unless ... |
def Mult ( self , x , factor ) :
"""Scales the freq / prob associated with the value x .
Args :
x : number value
factor : how much to multiply by""" | self . d [ x ] = self . d . get ( x , 0 ) * factor |
def get_session ( self ) :
"""Create Session to store credentials .
Returns
( Session )
A Session object with OAuth 2.0 credentials .""" | response = request_access_token ( grant_type = auth . CLIENT_CREDENTIAL_GRANT , client_id = self . client_id , client_secret = self . client_secret , scopes = self . scopes , )
oauth2credential = OAuth2Credential . make_from_response ( response = response , grant_type = auth . CLIENT_CREDENTIAL_GRANT , client_id = self... |
def _validate ( self ) :
'''Internal function to validate the transformer before applying all internal transformers .''' | if self . f_labels is None :
raise NotFittedError ( 'FeatureRepMix' )
if not self . transformers :
return
names , transformers , _ = zip ( * self . transformers )
# validate names
self . _validate_names ( names )
# validate transformers
for trans in transformers :
if not isinstance ( trans , FeatureRep ) :
... |
def smooth_shakemap ( shakemap_layer_path , output_file_path = '' , active_band = 1 , smoothing_method = NUMPY_SMOOTHING , smoothing_sigma = 0.9 ) :
"""Make a smoother shakemap layer from a shake map .
: param shakemap _ layer _ path : The shake map raster layer path .
: type shakemap _ layer _ path : basestrin... | # Set output path
if not output_file_path :
output_file_path = unique_filename ( suffix = '.tiff' , dir = temp_dir ( ) )
# convert to numpy
shakemap_file = gdal . Open ( shakemap_layer_path )
shakemap_array = np . array ( shakemap_file . GetRasterBand ( active_band ) . ReadAsArray ( ) )
# do smoothing
if smoothing_... |
def _resolve_placeholders ( self ) :
"""Resolve objects that have been imported from elsewhere .""" | modules = { }
for module in self . paths . values ( ) :
children = { child [ "name" ] : child for child in module [ "children" ] }
modules [ module [ "name" ] ] = ( module , children )
resolved = set ( )
for module_name in modules :
visit_path = collections . OrderedDict ( )
_resolve_module_placeholders... |
def json_serial ( obj ) :
"""Custom JSON serializer for objects not serializable by default .""" | if isinstance ( obj , ( datetime . datetime , datetime . date ) ) :
return obj . isoformat ( )
raise TypeError ( 'Type {} not serializable.' . format ( type ( obj ) ) ) |
def conv2d ( self , filter_size , output_channels , stride = 1 , padding = 'SAME' , stoch = None , bn = True , test = False , activation_fn = tf . nn . relu , b_value = 0.0 , s_value = 1.0 ) :
"""2D Convolutional Layer .
: param filter _ size : int . assumes square filter
: param output _ channels : int
: par... | self . count [ 'conv' ] += 1
scope = 'conv_' + str ( self . count [ 'conv' ] )
with tf . variable_scope ( scope ) : # Conv function
input_channels = self . input . get_shape ( ) [ 3 ]
if filter_size == 0 : # outputs a 1x1 feature map ; used for FCN
filter_size = self . input . get_shape ( ) [ 2 ]
... |
def writefile ( filename , data , binary = False ) :
"""Write the provided data to the file .
` filename `
Filename to write .
` data `
Data buffer to write .
` binary `
Set to ` ` True ` ` to indicate a binary file .
Returns boolean .""" | try :
flags = 'w' if not binary else 'wb'
with open ( filename , flags ) as _file :
_file . write ( data )
_file . flush ( )
return True
except ( OSError , IOError ) :
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.