code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def append_cluster(self, cluster, data=None, canvas=0, marker='.', markersize=None, color=None):
"""!
@brief Appends cluster to canvas for drawing.
@param[in] cluster (list): cluster that may consist of indexes of objects from the data or object itself.
@param[in] data (lis... | def function[append_cluster, parameter[self, cluster, data, canvas, marker, markersize, color]]:
constant[!
@brief Appends cluster to canvas for drawing.
@param[in] cluster (list): cluster that may consist of indexes of objects from the data or object itself.
@param[in] data (li... | keyword[def] identifier[append_cluster] ( identifier[self] , identifier[cluster] , identifier[data] = keyword[None] , identifier[canvas] = literal[int] , identifier[marker] = literal[string] , identifier[markersize] = keyword[None] , identifier[color] = keyword[None] ):
literal[string]
keyword[... | def append_cluster(self, cluster, data=None, canvas=0, marker='.', markersize=None, color=None):
"""!
@brief Appends cluster to canvas for drawing.
@param[in] cluster (list): cluster that may consist of indexes of objects from the data or object itself.
@param[in] data (list): If de... |
def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None,
pred_labels=None, title=None, normalize=False,
hide_zeros=False, x_tick_rotation=0, ax=None,
figsize=None, cmap='Blues', title_fontsize="large",
... | def function[plot_confusion_matrix, parameter[y_true, y_pred, labels, true_labels, pred_labels, title, normalize, hide_zeros, x_tick_rotation, ax, figsize, cmap, title_fontsize, text_fontsize]]:
constant[Generates confusion matrix plot from predictions and true labels
Args:
y_true (array-like, shap... | keyword[def] identifier[plot_confusion_matrix] ( identifier[y_true] , identifier[y_pred] , identifier[labels] = keyword[None] , identifier[true_labels] = keyword[None] ,
identifier[pred_labels] = keyword[None] , identifier[title] = keyword[None] , identifier[normalize] = keyword[False] ,
identifier[hide_zeros] = ke... | def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None, pred_labels=None, title=None, normalize=False, hide_zeros=False, x_tick_rotation=0, ax=None, figsize=None, cmap='Blues', title_fontsize='large', text_fontsize='medium'):
"""Generates confusion matrix plot from predictions and true labels
... |
def directed_account(transition, direction, mechanisms=False, purviews=False,
allow_neg=False):
"""Return the set of all |CausalLinks| of the specified direction."""
if mechanisms is False:
mechanisms = utils.powerset(transition.mechanism_indices(direction),
... | def function[directed_account, parameter[transition, direction, mechanisms, purviews, allow_neg]]:
constant[Return the set of all |CausalLinks| of the specified direction.]
if compare[name[mechanisms] is constant[False]] begin[:]
variable[mechanisms] assign[=] call[name[utils].powerset, ... | keyword[def] identifier[directed_account] ( identifier[transition] , identifier[direction] , identifier[mechanisms] = keyword[False] , identifier[purviews] = keyword[False] ,
identifier[allow_neg] = keyword[False] ):
literal[string]
keyword[if] identifier[mechanisms] keyword[is] keyword[False] :
... | def directed_account(transition, direction, mechanisms=False, purviews=False, allow_neg=False):
"""Return the set of all |CausalLinks| of the specified direction."""
if mechanisms is False:
mechanisms = utils.powerset(transition.mechanism_indices(direction), nonempty=True) # depends on [control=['if'],... |
def to_array(self):
"""Returns a 1-dimensional |numpy| |numpy.ndarray| with thirteen
entries first defining the start date, secondly defining the end
date and thirdly the step size in seconds.
"""
values = numpy.empty(13, dtype=float)
values[:6] = self.firstdate.to_array(... | def function[to_array, parameter[self]]:
constant[Returns a 1-dimensional |numpy| |numpy.ndarray| with thirteen
entries first defining the start date, secondly defining the end
date and thirdly the step size in seconds.
]
variable[values] assign[=] call[name[numpy].empty, paramet... | keyword[def] identifier[to_array] ( identifier[self] ):
literal[string]
identifier[values] = identifier[numpy] . identifier[empty] ( literal[int] , identifier[dtype] = identifier[float] )
identifier[values] [: literal[int] ]= identifier[self] . identifier[firstdate] . identifier[to_array] ... | def to_array(self):
"""Returns a 1-dimensional |numpy| |numpy.ndarray| with thirteen
entries first defining the start date, secondly defining the end
date and thirdly the step size in seconds.
"""
values = numpy.empty(13, dtype=float)
values[:6] = self.firstdate.to_array()
values... |
def update(self, campaign_id, budget, nick=None):
'''xxxxx.xxxxx.campaign.budget.update
===================================
更新一个推广计划的日限额'''
request = TOPRequest('xxxxx.xxxxx.campaign.budget.update')
request['campaign_id'] = campaign_id
request['budget'] = budget
i... | def function[update, parameter[self, campaign_id, budget, nick]]:
constant[xxxxx.xxxxx.campaign.budget.update
===================================
更新一个推广计划的日限额]
variable[request] assign[=] call[name[TOPRequest], parameter[constant[xxxxx.xxxxx.campaign.budget.update]]]
call[name[re... | keyword[def] identifier[update] ( identifier[self] , identifier[campaign_id] , identifier[budget] , identifier[nick] = keyword[None] ):
literal[string]
identifier[request] = identifier[TOPRequest] ( literal[string] )
identifier[request] [ literal[string] ]= identifier[campaign_id]
... | def update(self, campaign_id, budget, nick=None):
"""xxxxx.xxxxx.campaign.budget.update
===================================
更新一个推广计划的日限额"""
request = TOPRequest('xxxxx.xxxxx.campaign.budget.update')
request['campaign_id'] = campaign_id
request['budget'] = budget
if nick != None:
... |
def authorized(validator):
"""Decorate a RequestHandler or method to require that a request is authorized
If decorating a coroutine make sure coroutine decorator is first.
eg.::
class Handler(tornado.web.RequestHandler):
@authorized(validator)
@coroutine
def ge... | def function[authorized, parameter[validator]]:
constant[Decorate a RequestHandler or method to require that a request is authorized
If decorating a coroutine make sure coroutine decorator is first.
eg.::
class Handler(tornado.web.RequestHandler):
@authorized(validator)
... | keyword[def] identifier[authorized] ( identifier[validator] ):
literal[string]
keyword[def] identifier[_authorized_decorator] ( identifier[method] ):
@ identifier[gen] . identifier[coroutine]
keyword[def] identifier[wrapper] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ... | def authorized(validator):
"""Decorate a RequestHandler or method to require that a request is authorized
If decorating a coroutine make sure coroutine decorator is first.
eg.::
class Handler(tornado.web.RequestHandler):
@authorized(validator)
@coroutine
def ge... |
def prepend_global_admin_user(other_users, server):
"""
When making lists of administrative users -- e.g., seeding a new server --
it's useful to put the credentials supplied on the command line at the head
of the queue.
"""
cred0 = get_global_login_user(server, "admin")
if cred0 and cred0["... | def function[prepend_global_admin_user, parameter[other_users, server]]:
constant[
When making lists of administrative users -- e.g., seeding a new server --
it's useful to put the credentials supplied on the command line at the head
of the queue.
]
variable[cred0] assign[=] call[name[ge... | keyword[def] identifier[prepend_global_admin_user] ( identifier[other_users] , identifier[server] ):
literal[string]
identifier[cred0] = identifier[get_global_login_user] ( identifier[server] , literal[string] )
keyword[if] identifier[cred0] keyword[and] identifier[cred0] [ literal[string] ] keywor... | def prepend_global_admin_user(other_users, server):
"""
When making lists of administrative users -- e.g., seeding a new server --
it's useful to put the credentials supplied on the command line at the head
of the queue.
"""
cred0 = get_global_login_user(server, 'admin')
if cred0 and cred0['... |
def configure_db(app):
"""
0.10 is the first version of ARA that ships with a stable database schema.
We can identify a database that originates from before this by checking if
there is an alembic revision available.
If there is no alembic revision available, assume we are running the first
revi... | def function[configure_db, parameter[app]]:
constant[
0.10 is the first version of ARA that ships with a stable database schema.
We can identify a database that originates from before this by checking if
there is an alembic revision available.
If there is no alembic revision available, assume we... | keyword[def] identifier[configure_db] ( identifier[app] ):
literal[string]
identifier[models] . identifier[db] . identifier[init_app] ( identifier[app] )
identifier[log] = identifier[logging] . identifier[getLogger] ( literal[string] )
identifier[log] . identifier[debug] ( literal[string] )
... | def configure_db(app):
"""
0.10 is the first version of ARA that ships with a stable database schema.
We can identify a database that originates from before this by checking if
there is an alembic revision available.
If there is no alembic revision available, assume we are running the first
revi... |
def config_to_string(config):
"""Nice output string for the config, which is a nested defaultdict.
Args:
config (defaultdict(defaultdict)): The configuration information.
Returns:
str: A human-readable output string detailing the contents of the config.
"""
output = []
for secti... | def function[config_to_string, parameter[config]]:
constant[Nice output string for the config, which is a nested defaultdict.
Args:
config (defaultdict(defaultdict)): The configuration information.
Returns:
str: A human-readable output string detailing the contents of the config.
]
... | keyword[def] identifier[config_to_string] ( identifier[config] ):
literal[string]
identifier[output] =[]
keyword[for] identifier[section] , identifier[section_content] keyword[in] identifier[config] . identifier[items] ():
identifier[output] . identifier[append] ( literal[string] . identif... | def config_to_string(config):
"""Nice output string for the config, which is a nested defaultdict.
Args:
config (defaultdict(defaultdict)): The configuration information.
Returns:
str: A human-readable output string detailing the contents of the config.
"""
output = []
for (sect... |
def map_across_blocks(self, map_func):
"""Applies `map_func` to every partition.
Args:
map_func: The function to apply.
Returns:
A new BaseFrameManager object, the type of object that called this.
"""
preprocessed_map_func = self.preprocess_func(map_func... | def function[map_across_blocks, parameter[self, map_func]]:
constant[Applies `map_func` to every partition.
Args:
map_func: The function to apply.
Returns:
A new BaseFrameManager object, the type of object that called this.
]
variable[preprocessed_map_fu... | keyword[def] identifier[map_across_blocks] ( identifier[self] , identifier[map_func] ):
literal[string]
identifier[preprocessed_map_func] = identifier[self] . identifier[preprocess_func] ( identifier[map_func] )
identifier[new_partitions] = identifier[np] . identifier[array] (
[
... | def map_across_blocks(self, map_func):
"""Applies `map_func` to every partition.
Args:
map_func: The function to apply.
Returns:
A new BaseFrameManager object, the type of object that called this.
"""
preprocessed_map_func = self.preprocess_func(map_func)
ne... |
def translate_url(context, language):
"""
Translates the current URL for the given language code, eg:
{% translate_url de %}
"""
try:
request = context["request"]
except KeyError:
return ""
view = resolve(request.path)
current_language = translation.get_language()
... | def function[translate_url, parameter[context, language]]:
constant[
Translates the current URL for the given language code, eg:
{% translate_url de %}
]
<ast.Try object at 0x7da18bc70fd0>
variable[view] assign[=] call[name[resolve], parameter[name[request].path]]
variable[c... | keyword[def] identifier[translate_url] ( identifier[context] , identifier[language] ):
literal[string]
keyword[try] :
identifier[request] = identifier[context] [ literal[string] ]
keyword[except] identifier[KeyError] :
keyword[return] literal[string]
identifier[view] = identi... | def translate_url(context, language):
"""
Translates the current URL for the given language code, eg:
{% translate_url de %}
"""
try:
request = context['request'] # depends on [control=['try'], data=[]]
except KeyError:
return '' # depends on [control=['except'], data=[]]
... |
def WriteClientActionRequests(self, requests):
"""Writes messages that should go to the client to the db."""
for r in requests:
req_dict = self.flow_requests.get((r.client_id, r.flow_id), {})
if r.request_id not in req_dict:
request_keys = [(r.client_id, r.flow_id, r.request_id) for r in req... | def function[WriteClientActionRequests, parameter[self, requests]]:
constant[Writes messages that should go to the client to the db.]
for taget[name[r]] in starred[name[requests]] begin[:]
variable[req_dict] assign[=] call[name[self].flow_requests.get, parameter[tuple[[<ast.Attribute obj... | keyword[def] identifier[WriteClientActionRequests] ( identifier[self] , identifier[requests] ):
literal[string]
keyword[for] identifier[r] keyword[in] identifier[requests] :
identifier[req_dict] = identifier[self] . identifier[flow_requests] . identifier[get] (( identifier[r] . identifier[client_... | def WriteClientActionRequests(self, requests):
"""Writes messages that should go to the client to the db."""
for r in requests:
req_dict = self.flow_requests.get((r.client_id, r.flow_id), {})
if r.request_id not in req_dict:
request_keys = [(r.client_id, r.flow_id, r.request_id) for ... |
def registerEventHandlers(self):
"""
Registers the up and down handlers.
Also registers a scheduled function every 60th of a second, causing pyglet to redraw your window with 60fps.
"""
# Crouch/fly down
self.peng.keybinds.add(self.peng.cfg["controls.controls.cro... | def function[registerEventHandlers, parameter[self]]:
constant[
Registers the up and down handlers.
Also registers a scheduled function every 60th of a second, causing pyglet to redraw your window with 60fps.
]
call[name[self].peng.keybinds.add, parameter[call[name[self]... | keyword[def] identifier[registerEventHandlers] ( identifier[self] ):
literal[string]
identifier[self] . identifier[peng] . identifier[keybinds] . identifier[add] ( identifier[self] . identifier[peng] . identifier[cfg] [ literal[string] ], literal[string] % identifier[self] . identifier[act... | def registerEventHandlers(self):
"""
Registers the up and down handlers.
Also registers a scheduled function every 60th of a second, causing pyglet to redraw your window with 60fps.
"""
# Crouch/fly down
self.peng.keybinds.add(self.peng.cfg['controls.controls.crouch'], 'peng... |
def get_opener(self, name):
"""Retrieve an opener for the given protocol
:param name: name of the opener to open
:type name: string
:raises NoOpenerError: if no opener has been registered of that name
"""
if name not in self.registry:
raise NoOpenerError("No... | def function[get_opener, parameter[self, name]]:
constant[Retrieve an opener for the given protocol
:param name: name of the opener to open
:type name: string
:raises NoOpenerError: if no opener has been registered of that name
]
if compare[name[name] <ast.NotIn object ... | keyword[def] identifier[get_opener] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[registry] :
keyword[raise] identifier[NoOpenerError] ( literal[string] % identifier[name] )
ide... | def get_opener(self, name):
"""Retrieve an opener for the given protocol
:param name: name of the opener to open
:type name: string
:raises NoOpenerError: if no opener has been registered of that name
"""
if name not in self.registry:
raise NoOpenerError('No opener for ... |
def assemble_chain(leaf, store):
"""Assemble the trust chain.
This assembly method uses the certificates subject and issuer common name and
should be used for informational purposes only. It does *not*
cryptographically verify the chain!
:param OpenSSL.crypto.X509 leaf: The leaf certificate from which to bu... | def function[assemble_chain, parameter[leaf, store]]:
constant[Assemble the trust chain.
This assembly method uses the certificates subject and issuer common name and
should be used for informational purposes only. It does *not*
cryptographically verify the chain!
:param OpenSSL.crypto.X509 leaf: The ... | keyword[def] identifier[assemble_chain] ( identifier[leaf] , identifier[store] ):
literal[string]
identifier[store_dict] ={}
keyword[for] identifier[cert] keyword[in] identifier[store] :
identifier[store_dict] [ identifier[cert] . identifier[get_subject] (). identifier[CN] ]= identifier[cert]
i... | def assemble_chain(leaf, store):
"""Assemble the trust chain.
This assembly method uses the certificates subject and issuer common name and
should be used for informational purposes only. It does *not*
cryptographically verify the chain!
:param OpenSSL.crypto.X509 leaf: The leaf certificate from which to ... |
def scrub_output_pre_save(model, **kwargs):
"""scrub output before saving notebooks"""
# only run on notebooks
if model['type'] != 'notebook':
return
# only run on nbformat v4
if model['content']['nbformat'] != 4:
return
for cell in model['content']['cells']:
if cell['ce... | def function[scrub_output_pre_save, parameter[model]]:
constant[scrub output before saving notebooks]
if compare[call[name[model]][constant[type]] not_equal[!=] constant[notebook]] begin[:]
return[None]
if compare[call[call[name[model]][constant[content]]][constant[nbformat]] not_equal[!... | keyword[def] identifier[scrub_output_pre_save] ( identifier[model] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[model] [ literal[string] ]!= literal[string] :
keyword[return]
keyword[if] identifier[model] [ literal[string] ][ literal[string] ]!= literal[in... | def scrub_output_pre_save(model, **kwargs):
"""scrub output before saving notebooks"""
# only run on notebooks
if model['type'] != 'notebook':
return # depends on [control=['if'], data=[]]
# only run on nbformat v4
if model['content']['nbformat'] != 4:
return # depends on [control=... |
def modify_item(self, item_uri, metadata):
"""Modify the metadata on an item
"""
md = json.dumps({'metadata': metadata})
response = self.api_request(item_uri, method='PUT', data=md)
return self.__check_success(response) | def function[modify_item, parameter[self, item_uri, metadata]]:
constant[Modify the metadata on an item
]
variable[md] assign[=] call[name[json].dumps, parameter[dictionary[[<ast.Constant object at 0x7da1b222fa00>], [<ast.Name object at 0x7da1b222ddb0>]]]]
variable[response] assign[=] c... | keyword[def] identifier[modify_item] ( identifier[self] , identifier[item_uri] , identifier[metadata] ):
literal[string]
identifier[md] = identifier[json] . identifier[dumps] ({ literal[string] : identifier[metadata] })
identifier[response] = identifier[self] . identifier[api_request] ( ... | def modify_item(self, item_uri, metadata):
"""Modify the metadata on an item
"""
md = json.dumps({'metadata': metadata})
response = self.api_request(item_uri, method='PUT', data=md)
return self.__check_success(response) |
def secret_absent(name, namespace='default', **kwargs):
'''
Ensures that the named secret is absent from the given namespace.
name
The name of the secret
namespace
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
... | def function[secret_absent, parameter[name, namespace]]:
constant[
Ensures that the named secret is absent from the given namespace.
name
The name of the secret
namespace
The name of the namespace
]
variable[ret] assign[=] dictionary[[<ast.Constant object at 0x7da2044c2... | keyword[def] identifier[secret_absent] ( identifier[name] , identifier[namespace] = literal[string] ,** identifier[kwargs] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] :{},
literal[string] : keyword[False] ,
literal[string] : literal[string] }
... | def secret_absent(name, namespace='default', **kwargs):
"""
Ensures that the named secret is absent from the given namespace.
name
The name of the secret
namespace
The name of the namespace
"""
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
secret = __s... |
def create_rpc_request_header(self):
'''Creates and serializes a delimited RpcRequestHeaderProto message.'''
rpcheader = RpcRequestHeaderProto()
rpcheader.rpcKind = 2 # rpcheaderproto.RpcKindProto.Value('RPC_PROTOCOL_BUFFER')
rpcheader.rpcOp = 0 # rpcheaderproto.RpcPayloadOperationProt... | def function[create_rpc_request_header, parameter[self]]:
constant[Creates and serializes a delimited RpcRequestHeaderProto message.]
variable[rpcheader] assign[=] call[name[RpcRequestHeaderProto], parameter[]]
name[rpcheader].rpcKind assign[=] constant[2]
name[rpcheader].rpcOp assign[=]... | keyword[def] identifier[create_rpc_request_header] ( identifier[self] ):
literal[string]
identifier[rpcheader] = identifier[RpcRequestHeaderProto] ()
identifier[rpcheader] . identifier[rpcKind] = literal[int]
identifier[rpcheader] . identifier[rpcOp] = literal[int]
iden... | def create_rpc_request_header(self):
"""Creates and serializes a delimited RpcRequestHeaderProto message."""
rpcheader = RpcRequestHeaderProto()
rpcheader.rpcKind = 2 # rpcheaderproto.RpcKindProto.Value('RPC_PROTOCOL_BUFFER')
rpcheader.rpcOp = 0 # rpcheaderproto.RpcPayloadOperationProto.Value('RPC_FIN... |
def pid(self, value):
"""Process ID setter."""
self.bytearray[self._get_slicers(0)] = bytearray(c_int32(value or 0)) | def function[pid, parameter[self, value]]:
constant[Process ID setter.]
call[name[self].bytearray][call[name[self]._get_slicers, parameter[constant[0]]]] assign[=] call[name[bytearray], parameter[call[name[c_int32], parameter[<ast.BoolOp object at 0x7da1b2637340>]]]] | keyword[def] identifier[pid] ( identifier[self] , identifier[value] ):
literal[string]
identifier[self] . identifier[bytearray] [ identifier[self] . identifier[_get_slicers] ( literal[int] )]= identifier[bytearray] ( identifier[c_int32] ( identifier[value] keyword[or] literal[int] )) | def pid(self, value):
"""Process ID setter."""
self.bytearray[self._get_slicers(0)] = bytearray(c_int32(value or 0)) |
def delete_as(access_token, subscription_id, resource_group, as_name):
'''Delete availability set.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
as_name (str): Name of ... | def function[delete_as, parameter[access_token, subscription_id, resource_group, as_name]]:
constant[Delete availability set.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
... | keyword[def] identifier[delete_as] ( identifier[access_token] , identifier[subscription_id] , identifier[resource_group] , identifier[as_name] ):
literal[string]
identifier[endpoint] = literal[string] . identifier[join] ([ identifier[get_rm_endpoint] (),
literal[string] , identifier[subscription_id] ,... | def delete_as(access_token, subscription_id, resource_group, as_name):
"""Delete availability set.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
as_name (str): Name of ... |
def calculate_sunrise_sunset_from_datetime(self, datetime, depression=0.833,
is_solar_time=False):
"""Calculate sunrise, sunset and noon for a day of year."""
# TODO(mostapha): This should be more generic and based on a method
if datetime.year != 20... | def function[calculate_sunrise_sunset_from_datetime, parameter[self, datetime, depression, is_solar_time]]:
constant[Calculate sunrise, sunset and noon for a day of year.]
if <ast.BoolOp object at 0x7da1b12b9f30> begin[:]
variable[datetime] assign[=] call[name[DateTime], parameter[name[d... | keyword[def] identifier[calculate_sunrise_sunset_from_datetime] ( identifier[self] , identifier[datetime] , identifier[depression] = literal[int] ,
identifier[is_solar_time] = keyword[False] ):
literal[string]
keyword[if] identifier[datetime] . identifier[year] != literal[int] keyword[a... | def calculate_sunrise_sunset_from_datetime(self, datetime, depression=0.833, is_solar_time=False):
"""Calculate sunrise, sunset and noon for a day of year."""
# TODO(mostapha): This should be more generic and based on a method
if datetime.year != 2016 and self.is_leap_year:
datetime = DateTime(datet... |
def init(i): # pragma: no cover
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
global cfg, work, initialized, paths_repos, type_lon... | def function[init, parameter[i]]:
constant[
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
]
<ast.Global object at 0x7da1b220f1c0>
... | keyword[def] identifier[init] ( identifier[i] ):
literal[string]
keyword[global] identifier[cfg] , identifier[work] , identifier[initialized] , identifier[paths_repos] , identifier[type_long] , identifier[string_io]
keyword[if] identifier[initialized] :
keyword[return] { literal[string] :... | def init(i): # pragma: no cover
'\n Input: {}\n\n Output: {\n return - return code = 0, if successful\n > 0, if error\n (error) - error text if return > 0\n }\n '
global cfg, work, initialized, paths_repos, type... |
def get_draft_version(self, expand=[]):
"""
Get the current draft version of this layer.
:raises NotFound: if there is no draft version.
"""
target_url = self._client.get_url('VERSION', 'GET', 'draft', {'layer_id': self.id})
return self._manager._get(target_url, expand=ex... | def function[get_draft_version, parameter[self, expand]]:
constant[
Get the current draft version of this layer.
:raises NotFound: if there is no draft version.
]
variable[target_url] assign[=] call[name[self]._client.get_url, parameter[constant[VERSION], constant[GET], constant[... | keyword[def] identifier[get_draft_version] ( identifier[self] , identifier[expand] =[]):
literal[string]
identifier[target_url] = identifier[self] . identifier[_client] . identifier[get_url] ( literal[string] , literal[string] , literal[string] ,{ literal[string] : identifier[self] . identifier[id]... | def get_draft_version(self, expand=[]):
"""
Get the current draft version of this layer.
:raises NotFound: if there is no draft version.
"""
target_url = self._client.get_url('VERSION', 'GET', 'draft', {'layer_id': self.id})
return self._manager._get(target_url, expand=expand) |
def _feature_most_population(self, results):
"""
Find the placename with the largest population and return its country.
More population is a rough measure of importance.
Paramaters
----------
results: dict
output of `query_geonames`
Returns
-... | def function[_feature_most_population, parameter[self, results]]:
constant[
Find the placename with the largest population and return its country.
More population is a rough measure of importance.
Paramaters
----------
results: dict
output of `query_geonames`... | keyword[def] identifier[_feature_most_population] ( identifier[self] , identifier[results] ):
literal[string]
keyword[try] :
identifier[populations] =[ identifier[i] [ literal[string] ] keyword[for] identifier[i] keyword[in] identifier[results] [ literal[string] ][ literal[string] ... | def _feature_most_population(self, results):
"""
Find the placename with the largest population and return its country.
More population is a rough measure of importance.
Paramaters
----------
results: dict
output of `query_geonames`
Returns
-----... |
def build_index_sortmerna(ref_fp, working_dir):
"""Build a SortMeRNA index for all reference databases.
Parameters
----------
ref_fp: tuple
filepaths to FASTA reference databases
working_dir: string
working directory path where to store the indexed database
Returns
-------
... | def function[build_index_sortmerna, parameter[ref_fp, working_dir]]:
constant[Build a SortMeRNA index for all reference databases.
Parameters
----------
ref_fp: tuple
filepaths to FASTA reference databases
working_dir: string
working directory path where to store the indexed dat... | keyword[def] identifier[build_index_sortmerna] ( identifier[ref_fp] , identifier[working_dir] ):
literal[string]
identifier[logger] = identifier[logging] . identifier[getLogger] ( identifier[__name__] )
identifier[logger] . identifier[info] ( literal[string]
literal[string] %( identifier[ref_fp]... | def build_index_sortmerna(ref_fp, working_dir):
"""Build a SortMeRNA index for all reference databases.
Parameters
----------
ref_fp: tuple
filepaths to FASTA reference databases
working_dir: string
working directory path where to store the indexed database
Returns
-------
... |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: UsageContext for this UsageInstance
:rtype: twilio.rest.preview.wireless.sim.usage.UsageContext
... | def function[_proxy, parameter[self]]:
constant[
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: UsageContext for this UsageInstance
:rtype: twilio.rest.preview.wirele... | keyword[def] identifier[_proxy] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_context] keyword[is] keyword[None] :
identifier[self] . identifier[_context] = identifier[UsageContext] ( identifier[self] . identifier[_version] , identifier[sim_sid] = ... | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: UsageContext for this UsageInstance
:rtype: twilio.rest.preview.wireless.sim.usage.UsageContext
... |
def create_connector_resource(name, server=None, **kwargs):
'''
Create a connection resource
'''
defaults = {
'description': '',
'enabled': True,
'id': name,
'poolName': '',
'objectType': 'user',
'target': 'server'
}
# Data = defaults + merge kwar... | def function[create_connector_resource, parameter[name, server]]:
constant[
Create a connection resource
]
variable[defaults] assign[=] dictionary[[<ast.Constant object at 0x7da1b1fa7850>, <ast.Constant object at 0x7da1b1fa6c80>, <ast.Constant object at 0x7da1b1fa6b00>, <ast.Constant object at 0... | keyword[def] identifier[create_connector_resource] ( identifier[name] , identifier[server] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[defaults] ={
literal[string] : literal[string] ,
literal[string] : keyword[True] ,
literal[string] : identifier[name] ,
literal... | def create_connector_resource(name, server=None, **kwargs):
"""
Create a connection resource
"""
defaults = {'description': '', 'enabled': True, 'id': name, 'poolName': '', 'objectType': 'user', 'target': 'server'}
# Data = defaults + merge kwargs + poolname
data = defaults
data.update(kwarg... |
def nlms(u, d, M, step, eps=0.001, leak=0, initCoeffs=None, N=None,
returnCoeffs=False):
"""
Perform normalized least-mean-squares (NLMS) adaptive filtering on u to
minimize error given by e=d-y, where y is the output of the adaptive
filter.
Parameters
----------
u : array-like
... | def function[nlms, parameter[u, d, M, step, eps, leak, initCoeffs, N, returnCoeffs]]:
constant[
Perform normalized least-mean-squares (NLMS) adaptive filtering on u to
minimize error given by e=d-y, where y is the output of the adaptive
filter.
Parameters
----------
u : array-like
... | keyword[def] identifier[nlms] ( identifier[u] , identifier[d] , identifier[M] , identifier[step] , identifier[eps] = literal[int] , identifier[leak] = literal[int] , identifier[initCoeffs] = keyword[None] , identifier[N] = keyword[None] ,
identifier[returnCoeffs] = keyword[False] ):
literal[string]
i... | def nlms(u, d, M, step, eps=0.001, leak=0, initCoeffs=None, N=None, returnCoeffs=False):
"""
Perform normalized least-mean-squares (NLMS) adaptive filtering on u to
minimize error given by e=d-y, where y is the output of the adaptive
filter.
Parameters
----------
u : array-like
One-... |
def revoke(self, cidr_ip=None, ec2_group=None):
"""
Revoke access to a CIDR range or EC2 SecurityGroup.
You need to pass in either a CIDR block or
an EC2 SecurityGroup from which to revoke access.
@type cidr_ip: string
@param cidr_ip: A valid CIDR IP range to revoke
... | def function[revoke, parameter[self, cidr_ip, ec2_group]]:
constant[
Revoke access to a CIDR range or EC2 SecurityGroup.
You need to pass in either a CIDR block or
an EC2 SecurityGroup from which to revoke access.
@type cidr_ip: string
@param cidr_ip: A valid CIDR IP ran... | keyword[def] identifier[revoke] ( identifier[self] , identifier[cidr_ip] = keyword[None] , identifier[ec2_group] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[ec2_group] , identifier[SecurityGroup] ):
identifier[group_name] = identifier[ec2_group] ... | def revoke(self, cidr_ip=None, ec2_group=None):
"""
Revoke access to a CIDR range or EC2 SecurityGroup.
You need to pass in either a CIDR block or
an EC2 SecurityGroup from which to revoke access.
@type cidr_ip: string
@param cidr_ip: A valid CIDR IP range to revoke
... |
def restartCheckpoint(self, jobStore):
"""Restart a checkpoint after the total failure of jobs in its subtree.
Writes the changes to the jobStore immediately. All the
checkpoint's successors will be deleted, but its retry count
will *not* be decreased.
Returns a list with the I... | def function[restartCheckpoint, parameter[self, jobStore]]:
constant[Restart a checkpoint after the total failure of jobs in its subtree.
Writes the changes to the jobStore immediately. All the
checkpoint's successors will be deleted, but its retry count
will *not* be decreased.
... | keyword[def] identifier[restartCheckpoint] ( identifier[self] , identifier[jobStore] ):
literal[string]
keyword[assert] identifier[self] . identifier[checkpoint] keyword[is] keyword[not] keyword[None]
identifier[successorsDeleted] =[]
keyword[if] identifier[self] . identifie... | def restartCheckpoint(self, jobStore):
"""Restart a checkpoint after the total failure of jobs in its subtree.
Writes the changes to the jobStore immediately. All the
checkpoint's successors will be deleted, but its retry count
will *not* be decreased.
Returns a list with the IDs o... |
def store(self, loc, df):
"""Store dataframe in the given location.
Store some arbitrary dataframe:
>>> data.store('my_data', df)
Now recover it from the global store.
>>> data.my_data
...
"""
path = "%s.%s" % (self._root / "processed" / loc, FILE_EXTE... | def function[store, parameter[self, loc, df]]:
constant[Store dataframe in the given location.
Store some arbitrary dataframe:
>>> data.store('my_data', df)
Now recover it from the global store.
>>> data.my_data
...
]
variable[path] assign[=] binary_ope... | keyword[def] identifier[store] ( identifier[self] , identifier[loc] , identifier[df] ):
literal[string]
identifier[path] = literal[string] %( identifier[self] . identifier[_root] / literal[string] / identifier[loc] , identifier[FILE_EXTENSION] )
identifier[WRITE_DF] ( identifier[df] , ide... | def store(self, loc, df):
"""Store dataframe in the given location.
Store some arbitrary dataframe:
>>> data.store('my_data', df)
Now recover it from the global store.
>>> data.my_data
...
"""
path = '%s.%s' % (self._root / 'processed' / loc, FILE_EXTENSION)
... |
def toints(self):
"""\
Returns an iterable of integers interpreting the content of `seq`
as sequence of binary numbers of length 8.
"""
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x')... | def function[toints, parameter[self]]:
constant[ Returns an iterable of integers interpreting the content of `seq`
as sequence of binary numbers of length 8.
]
def function[grouper, parameter[iterable, n, fillvalue]]:
constant[Collect data into fixed-length chunks ... | keyword[def] identifier[toints] ( identifier[self] ):
literal[string]
keyword[def] identifier[grouper] ( identifier[iterable] , identifier[n] , identifier[fillvalue] = keyword[None] ):
literal[string]
keyword[return] identifier[zip_longest] (*[ identifier[i... | def toints(self):
""" Returns an iterable of integers interpreting the content of `seq`
as sequence of binary numbers of length 8.
"""
def grouper(iterable, n, fillvalue=None):
"""Collect data into fixed-length chunks or blocks"""
# grouper('ABCDEFG', 3, 'x') --> ABC DEF ... |
def get_method_bridges(self, name, arg_types=()):
"""
generator of bridge methods found that adapt the return types of a
named method and having argument type descriptors matching
those in arg_types.
"""
for m in self.get_methods_by_name(name):
if ((m.is_brid... | def function[get_method_bridges, parameter[self, name, arg_types]]:
constant[
generator of bridge methods found that adapt the return types of a
named method and having argument type descriptors matching
those in arg_types.
]
for taget[name[m]] in starred[call[name[self].... | keyword[def] identifier[get_method_bridges] ( identifier[self] , identifier[name] , identifier[arg_types] =()):
literal[string]
keyword[for] identifier[m] keyword[in] identifier[self] . identifier[get_methods_by_name] ( identifier[name] ):
keyword[if] (( identifier[m] . identifier[... | def get_method_bridges(self, name, arg_types=()):
"""
generator of bridge methods found that adapt the return types of a
named method and having argument type descriptors matching
those in arg_types.
"""
for m in self.get_methods_by_name(name):
if m.is_bridge() and m.get_... |
def size(self):
"""The size of the schema. If the underlying data source changes, it may be outdated.
"""
if self._size is None:
self._size = 0
for csv_file in self.files:
self._size += sum(1 if line else 0 for line in _util.open_local_or_gcs(csv_file, 'r'))
return self._size | def function[size, parameter[self]]:
constant[The size of the schema. If the underlying data source changes, it may be outdated.
]
if compare[name[self]._size is constant[None]] begin[:]
name[self]._size assign[=] constant[0]
for taget[name[csv_file]] in starred[name[... | keyword[def] identifier[size] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_size] keyword[is] keyword[None] :
identifier[self] . identifier[_size] = literal[int]
keyword[for] identifier[csv_file] keyword[in] identifier[self] . identifier[files] :
... | def size(self):
"""The size of the schema. If the underlying data source changes, it may be outdated.
"""
if self._size is None:
self._size = 0
for csv_file in self.files:
self._size += sum((1 if line else 0 for line in _util.open_local_or_gcs(csv_file, 'r'))) # depends on [cont... |
def get_as_nullable_map(self, key):
"""
Converts map element into an AnyValueMap or returns None if conversion is not possible.
:param key: a key of element to get.
:return: AnyValueMap value of the element or None if conversion is not supported.
"""
value = self.get_as... | def function[get_as_nullable_map, parameter[self, key]]:
constant[
Converts map element into an AnyValueMap or returns None if conversion is not possible.
:param key: a key of element to get.
:return: AnyValueMap value of the element or None if conversion is not supported.
]
... | keyword[def] identifier[get_as_nullable_map] ( identifier[self] , identifier[key] ):
literal[string]
identifier[value] = identifier[self] . identifier[get_as_object] ( identifier[key] )
keyword[return] identifier[AnyValueMap] . identifier[from_value] ( identifier[value] ) | def get_as_nullable_map(self, key):
"""
Converts map element into an AnyValueMap or returns None if conversion is not possible.
:param key: a key of element to get.
:return: AnyValueMap value of the element or None if conversion is not supported.
"""
value = self.get_as_object(... |
def hide(cls):
"""
Hide the log interface.
"""
cls.el.style.display = "none"
cls.overlay.hide()
cls.bind() | def function[hide, parameter[cls]]:
constant[
Hide the log interface.
]
name[cls].el.style.display assign[=] constant[none]
call[name[cls].overlay.hide, parameter[]]
call[name[cls].bind, parameter[]] | keyword[def] identifier[hide] ( identifier[cls] ):
literal[string]
identifier[cls] . identifier[el] . identifier[style] . identifier[display] = literal[string]
identifier[cls] . identifier[overlay] . identifier[hide] ()
identifier[cls] . identifier[bind] () | def hide(cls):
"""
Hide the log interface.
"""
cls.el.style.display = 'none'
cls.overlay.hide()
cls.bind() |
def get_overlapping_ranges(self, collection_link, sorted_ranges):
'''
Given the sorted ranges and a collection,
Returns the list of overlapping partition key ranges
:param str collection_link:
The collection link.
:param (list of routing_range._Range) sorted_... | def function[get_overlapping_ranges, parameter[self, collection_link, sorted_ranges]]:
constant[
Given the sorted ranges and a collection,
Returns the list of overlapping partition key ranges
:param str collection_link:
The collection link.
:param (list of ro... | keyword[def] identifier[get_overlapping_ranges] ( identifier[self] , identifier[collection_link] , identifier[sorted_ranges] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_is_sorted_and_non_overlapping] ( identifier[sorted_ranges] ):
keyword[rais... | def get_overlapping_ranges(self, collection_link, sorted_ranges):
"""
Given the sorted ranges and a collection,
Returns the list of overlapping partition key ranges
:param str collection_link:
The collection link.
:param (list of routing_range._Range) sorted_rang... |
def from_dict(data, ctx):
"""
Instantiate a new DynamicOrderState from a dict (generally from loading
a JSON response). The data used to instantiate the DynamicOrderState is
a shallow copy of the dict passed in, with any complex child types
instantiated appropriately.
"""... | def function[from_dict, parameter[data, ctx]]:
constant[
Instantiate a new DynamicOrderState from a dict (generally from loading
a JSON response). The data used to instantiate the DynamicOrderState is
a shallow copy of the dict passed in, with any complex child types
instantiated... | keyword[def] identifier[from_dict] ( identifier[data] , identifier[ctx] ):
literal[string]
identifier[data] = identifier[data] . identifier[copy] ()
keyword[if] identifier[data] . identifier[get] ( literal[string] ) keyword[is] keyword[not] keyword[None] :
identifier[data... | def from_dict(data, ctx):
"""
Instantiate a new DynamicOrderState from a dict (generally from loading
a JSON response). The data used to instantiate the DynamicOrderState is
a shallow copy of the dict passed in, with any complex child types
instantiated appropriately.
"""
... |
def _init_zeo_root(self, attempts=3):
"""
Get and initialize the ZEO root object.
Args:
attempts (int, default 3): How many times to try, if the connection
was lost.
"""
try:
db_root = self._connection.root()
except ConnectionState... | def function[_init_zeo_root, parameter[self, attempts]]:
constant[
Get and initialize the ZEO root object.
Args:
attempts (int, default 3): How many times to try, if the connection
was lost.
]
<ast.Try object at 0x7da1b15ac820>
if <ast.BoolOp obje... | keyword[def] identifier[_init_zeo_root] ( identifier[self] , identifier[attempts] = literal[int] ):
literal[string]
keyword[try] :
identifier[db_root] = identifier[self] . identifier[_connection] . identifier[root] ()
keyword[except] identifier[ConnectionStateError] :
... | def _init_zeo_root(self, attempts=3):
"""
Get and initialize the ZEO root object.
Args:
attempts (int, default 3): How many times to try, if the connection
was lost.
"""
try:
db_root = self._connection.root() # depends on [control=['try'], data=[]]
... |
def create_tokenizer(self, name, config=dict()):
"""Create a pipeline component from a factory.
name (unicode): Factory name to look up in `Language.factories`.
config (dict): Configuration parameters to initialise component.
RETURNS (callable): Pipeline component.
"""
i... | def function[create_tokenizer, parameter[self, name, config]]:
constant[Create a pipeline component from a factory.
name (unicode): Factory name to look up in `Language.factories`.
config (dict): Configuration parameters to initialise component.
RETURNS (callable): Pipeline component.
... | keyword[def] identifier[create_tokenizer] ( identifier[self] , identifier[name] , identifier[config] = identifier[dict] ()):
literal[string]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[factories] :
keyword[raise] identifier[KeyError] ( ident... | def create_tokenizer(self, name, config=dict()):
"""Create a pipeline component from a factory.
name (unicode): Factory name to look up in `Language.factories`.
config (dict): Configuration parameters to initialise component.
RETURNS (callable): Pipeline component.
"""
if name n... |
def get_stats(self):
"""Get general stats for the cache."""
expired = sum([x['expired'] for _, x in
self._CACHE_STATS['access_stats'].items()])
miss = sum([x['miss'] for _, x in
self._CACHE_STATS['access_stats'].items()])
hit = sum([x['hit'] fo... | def function[get_stats, parameter[self]]:
constant[Get general stats for the cache.]
variable[expired] assign[=] call[name[sum], parameter[<ast.ListComp object at 0x7da1b016f940>]]
variable[miss] assign[=] call[name[sum], parameter[<ast.ListComp object at 0x7da1b01906a0>]]
variable[hit] ... | keyword[def] identifier[get_stats] ( identifier[self] ):
literal[string]
identifier[expired] = identifier[sum] ([ identifier[x] [ literal[string] ] keyword[for] identifier[_] , identifier[x] keyword[in]
identifier[self] . identifier[_CACHE_STATS] [ literal[string] ]. identifier[items] (... | def get_stats(self):
"""Get general stats for the cache."""
expired = sum([x['expired'] for (_, x) in self._CACHE_STATS['access_stats'].items()])
miss = sum([x['miss'] for (_, x) in self._CACHE_STATS['access_stats'].items()])
hit = sum([x['hit'] for (_, x) in self._CACHE_STATS['access_stats'].items()])
... |
def sync(self, vault_client, opt):
"""Synchronizes the context to the Vault server. This
has the effect of updating every resource which is
in the context and has changes pending."""
active_mounts = []
for audit_log in self.logs():
audit_log.sync(vault_client)
... | def function[sync, parameter[self, vault_client, opt]]:
constant[Synchronizes the context to the Vault server. This
has the effect of updating every resource which is
in the context and has changes pending.]
variable[active_mounts] assign[=] list[[]]
for taget[name[audit_log]] in... | keyword[def] identifier[sync] ( identifier[self] , identifier[vault_client] , identifier[opt] ):
literal[string]
identifier[active_mounts] =[]
keyword[for] identifier[audit_log] keyword[in] identifier[self] . identifier[logs] ():
identifier[audit_log] . identifier[sync] ( i... | def sync(self, vault_client, opt):
"""Synchronizes the context to the Vault server. This
has the effect of updating every resource which is
in the context and has changes pending."""
active_mounts = []
for audit_log in self.logs():
audit_log.sync(vault_client) # depends on [control=... |
def _extract_device_name_from_event(event):
"""Extract device name from a tf.Event proto carrying tensor value."""
plugin_data_content = json.loads(
tf.compat.as_str(event.summary.value[0].metadata.plugin_data.content))
return plugin_data_content['device'] | def function[_extract_device_name_from_event, parameter[event]]:
constant[Extract device name from a tf.Event proto carrying tensor value.]
variable[plugin_data_content] assign[=] call[name[json].loads, parameter[call[name[tf].compat.as_str, parameter[call[name[event].summary.value][constant[0]].metadat... | keyword[def] identifier[_extract_device_name_from_event] ( identifier[event] ):
literal[string]
identifier[plugin_data_content] = identifier[json] . identifier[loads] (
identifier[tf] . identifier[compat] . identifier[as_str] ( identifier[event] . identifier[summary] . identifier[value] [ literal[int] ]. id... | def _extract_device_name_from_event(event):
"""Extract device name from a tf.Event proto carrying tensor value."""
plugin_data_content = json.loads(tf.compat.as_str(event.summary.value[0].metadata.plugin_data.content))
return plugin_data_content['device'] |
def save(self, specfiles=None, rm=False, ci=False, smi=False, sai=False,
si=False, compress=True, path=None):
"""Writes the specified datatypes to ``mrc`` files on the hard disk.
.. note::
If ``.save()`` is called and no ``mrc`` files are present in the
specified pa... | def function[save, parameter[self, specfiles, rm, ci, smi, sai, si, compress, path]]:
constant[Writes the specified datatypes to ``mrc`` files on the hard disk.
.. note::
If ``.save()`` is called and no ``mrc`` files are present in the
specified path new files are generated, oth... | keyword[def] identifier[save] ( identifier[self] , identifier[specfiles] = keyword[None] , identifier[rm] = keyword[False] , identifier[ci] = keyword[False] , identifier[smi] = keyword[False] , identifier[sai] = keyword[False] ,
identifier[si] = keyword[False] , identifier[compress] = keyword[True] , identifier[path... | def save(self, specfiles=None, rm=False, ci=False, smi=False, sai=False, si=False, compress=True, path=None):
"""Writes the specified datatypes to ``mrc`` files on the hard disk.
.. note::
If ``.save()`` is called and no ``mrc`` files are present in the
specified path new files are ... |
def _get_balance(self, account_number):
"""Get current balance from Fido."""
# Prepare data
data = {"ctn": self.username,
"language": "en-US",
"accountNumber": account_number}
# Http request
try:
raw_res = yield from self._session.post(... | def function[_get_balance, parameter[self, account_number]]:
constant[Get current balance from Fido.]
variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da20e748580>, <ast.Constant object at 0x7da20e7485e0>, <ast.Constant object at 0x7da20e74b850>], [<ast.Attribute object at 0x7da20e748640>... | keyword[def] identifier[_get_balance] ( identifier[self] , identifier[account_number] ):
literal[string]
identifier[data] ={ literal[string] : identifier[self] . identifier[username] ,
literal[string] : literal[string] ,
literal[string] : identifier[account_number] }
... | def _get_balance(self, account_number):
"""Get current balance from Fido."""
# Prepare data
data = {'ctn': self.username, 'language': 'en-US', 'accountNumber': account_number}
# Http request
try:
raw_res = (yield from self._session.post(BALANCE_URL, data=data, headers=self._headers, timeout=... |
def get_object_example(self, def_name):
'''
Create example for response, from object structure
:param def_name: --deffinition name of structure
:type def_name: str, unicode
:return: example of object
:rtype: dict
'''
def_model = self.definitions[def_name]... | def function[get_object_example, parameter[self, def_name]]:
constant[
Create example for response, from object structure
:param def_name: --deffinition name of structure
:type def_name: str, unicode
:return: example of object
:rtype: dict
]
variable[def_... | keyword[def] identifier[get_object_example] ( identifier[self] , identifier[def_name] ):
literal[string]
identifier[def_model] = identifier[self] . identifier[definitions] [ identifier[def_name] ]
identifier[example] = identifier[dict] ()
keyword[for] identifier[opt_name] , ident... | def get_object_example(self, def_name):
"""
Create example for response, from object structure
:param def_name: --deffinition name of structure
:type def_name: str, unicode
:return: example of object
:rtype: dict
"""
def_model = self.definitions[def_name]
exa... |
def rwh_primes1(n):
# http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
''' Returns a list of primes < n '''
sieve = [True] * (n/2)
for i in _range(3,int(n**0.5)+1,2):
if sieve[i/2]:
sieve[i*i/2::i] = [False] * ((n-i*i-1)/(2*... | def function[rwh_primes1, parameter[n]]:
constant[ Returns a list of primes < n ]
variable[sieve] assign[=] binary_operation[list[[<ast.Constant object at 0x7da18f7218a0>]] * binary_operation[name[n] / constant[2]]]
for taget[name[i]] in starred[call[name[_range], parameter[constant[3], binary_... | keyword[def] identifier[rwh_primes1] ( identifier[n] ):
literal[string]
identifier[sieve] =[ keyword[True] ]*( identifier[n] / literal[int] )
keyword[for] identifier[i] keyword[in] identifier[_range] ( literal[int] , identifier[int] ( identifier[n] ** literal[int] )+ literal[int] , literal[int] ):... | def rwh_primes1(n):
# http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
' Returns a list of primes < n '
sieve = [True] * (n / 2)
for i in _range(3, int(n ** 0.5) + 1, 2):
if sieve[i / 2]:
sieve[i * i / 2::i] = [False] * ((n ... |
def stripQuotes(value):
"""Strip single or double quotes off string; remove embedded quote pairs"""
if value[:1] == '"':
value = value[1:]
if value[-1:] == '"':
value = value[:-1]
# replace "" with "
value = re.sub(_re_doubleq2, '"', value)
elif value[:1] == "'"... | def function[stripQuotes, parameter[value]]:
constant[Strip single or double quotes off string; remove embedded quote pairs]
if compare[call[name[value]][<ast.Slice object at 0x7da1b0f057e0>] equal[==] constant["]] begin[:]
variable[value] assign[=] call[name[value]][<ast.Slice object at... | keyword[def] identifier[stripQuotes] ( identifier[value] ):
literal[string]
keyword[if] identifier[value] [: literal[int] ]== literal[string] :
identifier[value] = identifier[value] [ literal[int] :]
keyword[if] identifier[value] [- literal[int] :]== literal[string] :
ide... | def stripQuotes(value):
"""Strip single or double quotes off string; remove embedded quote pairs"""
if value[:1] == '"':
value = value[1:]
if value[-1:] == '"':
value = value[:-1] # depends on [control=['if'], data=[]]
# replace "" with "
value = re.sub(_re_doubleq2,... |
def get_bars(self, assets, data_frequency, bar_count=500):
'''
Interface method.
Return: pd.Dataframe() with columns MultiIndex [asset -> OHLCV]
'''
assets_is_scalar = not isinstance(assets, (list, set, tuple))
is_daily = 'd' in data_frequency # 'daily' or '1d'
... | def function[get_bars, parameter[self, assets, data_frequency, bar_count]]:
constant[
Interface method.
Return: pd.Dataframe() with columns MultiIndex [asset -> OHLCV]
]
variable[assets_is_scalar] assign[=] <ast.UnaryOp object at 0x7da2054a6230>
variable[is_daily] assign... | keyword[def] identifier[get_bars] ( identifier[self] , identifier[assets] , identifier[data_frequency] , identifier[bar_count] = literal[int] ):
literal[string]
identifier[assets_is_scalar] = keyword[not] identifier[isinstance] ( identifier[assets] ,( identifier[list] , identifier[set] , identifie... | def get_bars(self, assets, data_frequency, bar_count=500):
"""
Interface method.
Return: pd.Dataframe() with columns MultiIndex [asset -> OHLCV]
"""
assets_is_scalar = not isinstance(assets, (list, set, tuple))
is_daily = 'd' in data_frequency # 'daily' or '1d'
if assets_is_sca... |
def unmount_medium(self, name, controller_port, device, force):
"""Unmounts any currently mounted medium (:py:class:`IMedium` ,
identified by the given UUID @a id) to the given storage controller
(:py:class:`IStorageController` , identified by @a name),
at the indicated port and device. ... | def function[unmount_medium, parameter[self, name, controller_port, device, force]]:
constant[Unmounts any currently mounted medium (:py:class:`IMedium` ,
identified by the given UUID @a id) to the given storage controller
(:py:class:`IStorageController` , identified by @a name),
at the ... | keyword[def] identifier[unmount_medium] ( identifier[self] , identifier[name] , identifier[controller_port] , identifier[device] , identifier[force] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[name] , identifier[basestring] ):
keyword[raise] ident... | def unmount_medium(self, name, controller_port, device, force):
"""Unmounts any currently mounted medium (:py:class:`IMedium` ,
identified by the given UUID @a id) to the given storage controller
(:py:class:`IStorageController` , identified by @a name),
at the indicated port and device. The ... |
def cli(env, identifier):
"""Cancel a subnet."""
mgr = SoftLayer.NetworkManager(env.client)
subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier,
name='subnet')
if not (env.skip_confirmations or formatting.no_going_back(subnet_id)):
raise excepti... | def function[cli, parameter[env, identifier]]:
constant[Cancel a subnet.]
variable[mgr] assign[=] call[name[SoftLayer].NetworkManager, parameter[name[env].client]]
variable[subnet_id] assign[=] call[name[helpers].resolve_id, parameter[name[mgr].resolve_subnet_ids, name[identifier]]]
if <... | keyword[def] identifier[cli] ( identifier[env] , identifier[identifier] ):
literal[string]
identifier[mgr] = identifier[SoftLayer] . identifier[NetworkManager] ( identifier[env] . identifier[client] )
identifier[subnet_id] = identifier[helpers] . identifier[resolve_id] ( identifier[mgr] . identifier[... | def cli(env, identifier):
"""Cancel a subnet."""
mgr = SoftLayer.NetworkManager(env.client)
subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier, name='subnet')
if not (env.skip_confirmations or formatting.no_going_back(subnet_id)):
raise exceptions.CLIAbort('Aborted') # depends on... |
def canonicalize(self, mol):
"""Return a canonical tautomer by enumerating and scoring all possible tautomers.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:return: The canonical tautomer.
:rtype: rdkit.Chem.rdchem.Mol
"""
# TODO: Overload the... | def function[canonicalize, parameter[self, mol]]:
constant[Return a canonical tautomer by enumerating and scoring all possible tautomers.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:return: The canonical tautomer.
:rtype: rdkit.Chem.rdchem.Mol
]
... | keyword[def] identifier[canonicalize] ( identifier[self] , identifier[mol] ):
literal[string]
identifier[tautomers] = identifier[self] . identifier[_enumerate_tautomers] ( identifier[mol] )
keyword[if] identifier[len] ( identifier[tautomers] )== literal[int] :
keywor... | def canonicalize(self, mol):
"""Return a canonical tautomer by enumerating and scoring all possible tautomers.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:return: The canonical tautomer.
:rtype: rdkit.Chem.rdchem.Mol
"""
# TODO: Overload the mol par... |
def get_tunnel(self, tunnel_id):
"""Get information for a tunnel given its ID."""
method = 'GET'
endpoint = '/rest/v1/{}/tunnels/{}'.format(
self.client.sauce_username, tunnel_id)
return self.client.request(method, endpoint) | def function[get_tunnel, parameter[self, tunnel_id]]:
constant[Get information for a tunnel given its ID.]
variable[method] assign[=] constant[GET]
variable[endpoint] assign[=] call[constant[/rest/v1/{}/tunnels/{}].format, parameter[name[self].client.sauce_username, name[tunnel_id]]]
return[... | keyword[def] identifier[get_tunnel] ( identifier[self] , identifier[tunnel_id] ):
literal[string]
identifier[method] = literal[string]
identifier[endpoint] = literal[string] . identifier[format] (
identifier[self] . identifier[client] . identifier[sauce_username] , identifier[tun... | def get_tunnel(self, tunnel_id):
"""Get information for a tunnel given its ID."""
method = 'GET'
endpoint = '/rest/v1/{}/tunnels/{}'.format(self.client.sauce_username, tunnel_id)
return self.client.request(method, endpoint) |
def enrollment_upload(
self,
enrollment_id,
audio_file,
):
"""
Upload Enrollment Data. Uses PUT to /enrollments/<enrollment_id> interface.
:Args:
* *enrollment_id*: (str) Enrollment's ID
* *audio_file*: (str) Path to the audio file of the rec... | def function[enrollment_upload, parameter[self, enrollment_id, audio_file]]:
constant[
Upload Enrollment Data. Uses PUT to /enrollments/<enrollment_id> interface.
:Args:
* *enrollment_id*: (str) Enrollment's ID
* *audio_file*: (str) Path to the audio file of the recorde... | keyword[def] identifier[enrollment_upload] (
identifier[self] ,
identifier[enrollment_id] ,
identifier[audio_file] ,
):
literal[string]
identifier[files] ={
literal[string] : identifier[os] . identifier[path] . identifier[basename] ( identifier[audio_file] ),
identifier[os] . i... | def enrollment_upload(self, enrollment_id, audio_file):
"""
Upload Enrollment Data. Uses PUT to /enrollments/<enrollment_id> interface.
:Args:
* *enrollment_id*: (str) Enrollment's ID
* *audio_file*: (str) Path to the audio file of the recorded words. Not required for phone... |
def create_file_vdev(size, *vdevs):
'''
Creates file based virtual devices for a zpool
CLI Example:
.. code-block:: bash
salt '*' zpool.create_file_vdev 7G /path/to/vdev1 [/path/to/vdev2] [...]
.. note::
Depending on file size, the above command may take a while to return.
... | def function[create_file_vdev, parameter[size]]:
constant[
Creates file based virtual devices for a zpool
CLI Example:
.. code-block:: bash
salt '*' zpool.create_file_vdev 7G /path/to/vdev1 [/path/to/vdev2] [...]
.. note::
Depending on file size, the above command may take a... | keyword[def] identifier[create_file_vdev] ( identifier[size] ,* identifier[vdevs] ):
literal[string]
identifier[ret] = identifier[OrderedDict] ()
identifier[err] = identifier[OrderedDict] ()
identifier[_mkfile_cmd] = identifier[salt] . identifier[utils] . identifier[path] . identifier[which] ( l... | def create_file_vdev(size, *vdevs):
"""
Creates file based virtual devices for a zpool
CLI Example:
.. code-block:: bash
salt '*' zpool.create_file_vdev 7G /path/to/vdev1 [/path/to/vdev2] [...]
.. note::
Depending on file size, the above command may take a while to return.
... |
def validate_term(self, term, latest_only=False):
""" Check that a term is present in the metadata dictionary.
raises :exc:`~billy.scrape.NoDataForPeriod` if term is invalid
:param term: string representing term to check
:param latest_only: if True, will raise exception if term ... | def function[validate_term, parameter[self, term, latest_only]]:
constant[ Check that a term is present in the metadata dictionary.
raises :exc:`~billy.scrape.NoDataForPeriod` if term is invalid
:param term: string representing term to check
:param latest_only: if True, will rai... | keyword[def] identifier[validate_term] ( identifier[self] , identifier[term] , identifier[latest_only] = keyword[False] ):
literal[string]
keyword[if] identifier[latest_only] :
keyword[if] identifier[term] == identifier[self] . identifier[metadata] [ literal[string] ][- literal[int]... | def validate_term(self, term, latest_only=False):
""" Check that a term is present in the metadata dictionary.
raises :exc:`~billy.scrape.NoDataForPeriod` if term is invalid
:param term: string representing term to check
:param latest_only: if True, will raise exception if term is n... |
def set_item_metadata(self, token, item_id, element, value,
qualifier=None):
"""
Set the metadata associated with an item.
:param token: A valid token for the user in question.
:type token: string
:param item_id: The id of the item for which metadata wi... | def function[set_item_metadata, parameter[self, token, item_id, element, value, qualifier]]:
constant[
Set the metadata associated with an item.
:param token: A valid token for the user in question.
:type token: string
:param item_id: The id of the item for which metadata will b... | keyword[def] identifier[set_item_metadata] ( identifier[self] , identifier[token] , identifier[item_id] , identifier[element] , identifier[value] ,
identifier[qualifier] = keyword[None] ):
literal[string]
identifier[parameters] = identifier[dict] ()
identifier[parameters] [ literal[string... | def set_item_metadata(self, token, item_id, element, value, qualifier=None):
"""
Set the metadata associated with an item.
:param token: A valid token for the user in question.
:type token: string
:param item_id: The id of the item for which metadata will be set.
:type item_... |
def get_t(self):
"""Returns the top border of the cell"""
cell_above = CellBorders(self.cell_attributes,
*self.cell.get_above_key_rect())
return cell_above.get_b() | def function[get_t, parameter[self]]:
constant[Returns the top border of the cell]
variable[cell_above] assign[=] call[name[CellBorders], parameter[name[self].cell_attributes, <ast.Starred object at 0x7da1b1600970>]]
return[call[name[cell_above].get_b, parameter[]]] | keyword[def] identifier[get_t] ( identifier[self] ):
literal[string]
identifier[cell_above] = identifier[CellBorders] ( identifier[self] . identifier[cell_attributes] ,
* identifier[self] . identifier[cell] . identifier[get_above_key_rect] ())
keyword[return] identifier[cell_abov... | def get_t(self):
"""Returns the top border of the cell"""
cell_above = CellBorders(self.cell_attributes, *self.cell.get_above_key_rect())
return cell_above.get_b() |
def add_aggregate(self, name, data_fac):
"""
Add an aggregate target to this nest.
Since nests added after the aggregate can access the construct returned
by the factory function value, it can be mutated to provide additional
values for use when the decorated function is called... | def function[add_aggregate, parameter[self, name, data_fac]]:
constant[
Add an aggregate target to this nest.
Since nests added after the aggregate can access the construct returned
by the factory function value, it can be mutated to provide additional
values for use when the d... | keyword[def] identifier[add_aggregate] ( identifier[self] , identifier[name] , identifier[data_fac] ):
literal[string]
@ identifier[self] . identifier[add_target] ( identifier[name] )
keyword[def] identifier[wrap] ( identifier[outdir] , identifier[c] ):
keyword[return] identi... | def add_aggregate(self, name, data_fac):
"""
Add an aggregate target to this nest.
Since nests added after the aggregate can access the construct returned
by the factory function value, it can be mutated to provide additional
values for use when the decorated function is called.
... |
def sel(self, indexers=None, method=None, tolerance=None, drop=False,
**indexers_kwargs):
"""Return a new DataArray whose dataset is given by selecting
index labels along the specified dimension(s).
.. warning::
Do not try to assign values when using any of the indexing m... | def function[sel, parameter[self, indexers, method, tolerance, drop]]:
constant[Return a new DataArray whose dataset is given by selecting
index labels along the specified dimension(s).
.. warning::
Do not try to assign values when using any of the indexing methods
``isel``... | keyword[def] identifier[sel] ( identifier[self] , identifier[indexers] = keyword[None] , identifier[method] = keyword[None] , identifier[tolerance] = keyword[None] , identifier[drop] = keyword[False] ,
** identifier[indexers_kwargs] ):
literal[string]
identifier[ds] = identifier[self] . identifier[... | def sel(self, indexers=None, method=None, tolerance=None, drop=False, **indexers_kwargs):
"""Return a new DataArray whose dataset is given by selecting
index labels along the specified dimension(s).
.. warning::
Do not try to assign values when using any of the indexing methods
... |
def gibbs_ask(X, e, bn, N):
"""[Fig. 14.16]
>>> seed(1017)
>>> gibbs_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary, 1000
... ).show_approx()
'False: 0.738, True: 0.262'
"""
assert X not in e, "Query variable must be distinct from evidence"
counts = dict((x, 0) for x in bn.var... | def function[gibbs_ask, parameter[X, e, bn, N]]:
constant[[Fig. 14.16]
>>> seed(1017)
>>> gibbs_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary, 1000
... ).show_approx()
'False: 0.738, True: 0.262'
]
assert[compare[name[X] <ast.NotIn object at 0x7da2590d7190> name[e]]]
... | keyword[def] identifier[gibbs_ask] ( identifier[X] , identifier[e] , identifier[bn] , identifier[N] ):
literal[string]
keyword[assert] identifier[X] keyword[not] keyword[in] identifier[e] , literal[string]
identifier[counts] = identifier[dict] (( identifier[x] , literal[int] ) keyword[for] ident... | def gibbs_ask(X, e, bn, N):
"""[Fig. 14.16]
>>> seed(1017)
>>> gibbs_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary, 1000
... ).show_approx()
'False: 0.738, True: 0.262'
"""
assert X not in e, 'Query variable must be distinct from evidence'
counts = dict(((x, 0) for x in bn.va... |
def fetch(self, category=CATEGORY_MESSAGE, from_date=DEFAULT_DATETIME):
"""Fetch the messages from the channel.
This method fetches the messages stored on the channel that were
sent since the given date.
:param category: the category of items to fetch
:param from_date: obtain m... | def function[fetch, parameter[self, category, from_date]]:
constant[Fetch the messages from the channel.
This method fetches the messages stored on the channel that were
sent since the given date.
:param category: the category of items to fetch
:param from_date: obtain messages... | keyword[def] identifier[fetch] ( identifier[self] , identifier[category] = identifier[CATEGORY_MESSAGE] , identifier[from_date] = identifier[DEFAULT_DATETIME] ):
literal[string]
keyword[if] keyword[not] identifier[from_date] :
identifier[from_date] = identifier[DEFAULT_DATETIME]
... | def fetch(self, category=CATEGORY_MESSAGE, from_date=DEFAULT_DATETIME):
"""Fetch the messages from the channel.
This method fetches the messages stored on the channel that were
sent since the given date.
:param category: the category of items to fetch
:param from_date: obtain messa... |
def split_recursive(
self,
depth: int,
min_width: int,
min_height: int,
max_horizontal_ratio: float,
max_vertical_ratio: float,
seed: Optional[tcod.random.Random] = None,
) -> None:
"""Divide this partition recursively.
Args:
depth... | def function[split_recursive, parameter[self, depth, min_width, min_height, max_horizontal_ratio, max_vertical_ratio, seed]]:
constant[Divide this partition recursively.
Args:
depth (int): The maximum depth to divide this object recursively.
min_width (int): The minimum width of... | keyword[def] identifier[split_recursive] (
identifier[self] ,
identifier[depth] : identifier[int] ,
identifier[min_width] : identifier[int] ,
identifier[min_height] : identifier[int] ,
identifier[max_horizontal_ratio] : identifier[float] ,
identifier[max_vertical_ratio] : identifier[float] ,
identifier[seed] :... | def split_recursive(self, depth: int, min_width: int, min_height: int, max_horizontal_ratio: float, max_vertical_ratio: float, seed: Optional[tcod.random.Random]=None) -> None:
"""Divide this partition recursively.
Args:
depth (int): The maximum depth to divide this object recursively.
... |
def send_identity(self):
"""
Send the identity of the service.
"""
service_name = {'service_name': self.messaging._service_name}
service_name = _json.dumps(service_name).encode('utf8')
identify_frame = (b'',
b'IDENT',
_... | def function[send_identity, parameter[self]]:
constant[
Send the identity of the service.
]
variable[service_name] assign[=] dictionary[[<ast.Constant object at 0x7da1b0e3af20>], [<ast.Attribute object at 0x7da1b0e3bca0>]]
variable[service_name] assign[=] call[call[name[_json].du... | keyword[def] identifier[send_identity] ( identifier[self] ):
literal[string]
identifier[service_name] ={ literal[string] : identifier[self] . identifier[messaging] . identifier[_service_name] }
identifier[service_name] = identifier[_json] . identifier[dumps] ( identifier[service_name] ). i... | def send_identity(self):
"""
Send the identity of the service.
"""
service_name = {'service_name': self.messaging._service_name}
service_name = _json.dumps(service_name).encode('utf8')
identify_frame = (b'', b'IDENT', _json.dumps([]).encode('utf8'), service_name)
# NOTE: Have to do t... |
def _connect(self):
"""Establish connection to MySQL Database."""
if self._connParams:
self._conn = MySQLdb.connect(**self._connParams)
else:
self._conn = MySQLdb.connect('') | def function[_connect, parameter[self]]:
constant[Establish connection to MySQL Database.]
if name[self]._connParams begin[:]
name[self]._conn assign[=] call[name[MySQLdb].connect, parameter[]] | keyword[def] identifier[_connect] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_connParams] :
identifier[self] . identifier[_conn] = identifier[MySQLdb] . identifier[connect] (** identifier[self] . identifier[_connParams] )
keyword[else] :
... | def _connect(self):
"""Establish connection to MySQL Database."""
if self._connParams:
self._conn = MySQLdb.connect(**self._connParams) # depends on [control=['if'], data=[]]
else:
self._conn = MySQLdb.connect('') |
def match_file(filename, exclude):
"""Return True if file is okay for modifying/recursing."""
base_name = os.path.basename(filename)
if base_name.startswith('.'):
return False
for pattern in exclude:
if fnmatch.fnmatch(base_name, pattern):
return False
if fnmatch.fn... | def function[match_file, parameter[filename, exclude]]:
constant[Return True if file is okay for modifying/recursing.]
variable[base_name] assign[=] call[name[os].path.basename, parameter[name[filename]]]
if call[name[base_name].startswith, parameter[constant[.]]] begin[:]
return[constan... | keyword[def] identifier[match_file] ( identifier[filename] , identifier[exclude] ):
literal[string]
identifier[base_name] = identifier[os] . identifier[path] . identifier[basename] ( identifier[filename] )
keyword[if] identifier[base_name] . identifier[startswith] ( literal[string] ):
keywo... | def match_file(filename, exclude):
"""Return True if file is okay for modifying/recursing."""
base_name = os.path.basename(filename)
if base_name.startswith('.'):
return False # depends on [control=['if'], data=[]]
for pattern in exclude:
if fnmatch.fnmatch(base_name, pattern):
... |
def set_poll_func(self, func, func_err_handler=None):
'''Can be used to integrate pulse client into existing eventloop.
Function will be passed a list of pollfd structs and timeout value (seconds, float),
which it is responsible to use and modify (set poll flags) accordingly,
returning int value >= 0 with ... | def function[set_poll_func, parameter[self, func, func_err_handler]]:
constant[Can be used to integrate pulse client into existing eventloop.
Function will be passed a list of pollfd structs and timeout value (seconds, float),
which it is responsible to use and modify (set poll flags) accordingly,
re... | keyword[def] identifier[set_poll_func] ( identifier[self] , identifier[func] , identifier[func_err_handler] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[func_err_handler] : identifier[func_err_handler] = identifier[traceback] . identifier[print_exception]
identifier[self] . iden... | def set_poll_func(self, func, func_err_handler=None):
"""Can be used to integrate pulse client into existing eventloop.
Function will be passed a list of pollfd structs and timeout value (seconds, float),
which it is responsible to use and modify (set poll flags) accordingly,
returning int value >= 0 wit... |
def projection_pp(site, normal, dist_to_plane, reference):
'''
This method finds the projection of the site onto the plane containing
the slipped area, defined as the Pp(i.e. 'perpendicular projection of
site location onto the fault plane' Spudich et al. (2013) - page 88)
given a site.
:param s... | def function[projection_pp, parameter[site, normal, dist_to_plane, reference]]:
constant[
This method finds the projection of the site onto the plane containing
the slipped area, defined as the Pp(i.e. 'perpendicular projection of
site location onto the fault plane' Spudich et al. (2013) - page 88)
... | keyword[def] identifier[projection_pp] ( identifier[site] , identifier[normal] , identifier[dist_to_plane] , identifier[reference] ):
literal[string]
[ identifier[site_x] , identifier[site_y] , identifier[site_z] ]= identifier[get_xyz_from_ll] ( identifier[site] , identifier[reference] )
identif... | def projection_pp(site, normal, dist_to_plane, reference):
"""
This method finds the projection of the site onto the plane containing
the slipped area, defined as the Pp(i.e. 'perpendicular projection of
site location onto the fault plane' Spudich et al. (2013) - page 88)
given a site.
:param s... |
def elem_add(self, idx=None, name=None, **kwargs):
"""overloading elem_add function of a JIT class"""
self.jit_load()
if self.loaded:
return self.system.__dict__[self.name].elem_add(
idx, name, **kwargs) | def function[elem_add, parameter[self, idx, name]]:
constant[overloading elem_add function of a JIT class]
call[name[self].jit_load, parameter[]]
if name[self].loaded begin[:]
return[call[call[name[self].system.__dict__][name[self].name].elem_add, parameter[name[idx], name[name]]]] | keyword[def] identifier[elem_add] ( identifier[self] , identifier[idx] = keyword[None] , identifier[name] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[jit_load] ()
keyword[if] identifier[self] . identifier[loaded] :
keyword[return] ... | def elem_add(self, idx=None, name=None, **kwargs):
"""overloading elem_add function of a JIT class"""
self.jit_load()
if self.loaded:
return self.system.__dict__[self.name].elem_add(idx, name, **kwargs) # depends on [control=['if'], data=[]] |
def fetch_fieldnames(self, sql: str, *args) -> List[str]:
"""Executes SQL; returns just the output fieldnames."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return [i[0] for i in cursor.description]
except... | def function[fetch_fieldnames, parameter[self, sql]]:
constant[Executes SQL; returns just the output fieldnames.]
call[name[self].ensure_db_open, parameter[]]
variable[cursor] assign[=] call[name[self].db.cursor, parameter[]]
call[name[self].db_exec_with_cursor, parameter[name[cursor], n... | keyword[def] identifier[fetch_fieldnames] ( identifier[self] , identifier[sql] : identifier[str] ,* identifier[args] )-> identifier[List] [ identifier[str] ]:
literal[string]
identifier[self] . identifier[ensure_db_open] ()
identifier[cursor] = identifier[self] . identifier[db] . identifie... | def fetch_fieldnames(self, sql: str, *args) -> List[str]:
"""Executes SQL; returns just the output fieldnames."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return [i[0] for i in cursor.description] # depends on [control=['try'], data=[... |
def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque):
'''
Domain block threshold events handler
'''
_salt_send_domain_event(opaque, conn, domain, opaque['event'], {
'dev': dev,
'path': path,
'threshold': threshold,
'excess': excess
... | def function[_domain_event_block_threshold_cb, parameter[conn, domain, dev, path, threshold, excess, opaque]]:
constant[
Domain block threshold events handler
]
call[name[_salt_send_domain_event], parameter[name[opaque], name[conn], name[domain], call[name[opaque]][constant[event]], dictionary[[... | keyword[def] identifier[_domain_event_block_threshold_cb] ( identifier[conn] , identifier[domain] , identifier[dev] , identifier[path] , identifier[threshold] , identifier[excess] , identifier[opaque] ):
literal[string]
identifier[_salt_send_domain_event] ( identifier[opaque] , identifier[conn] , identifie... | def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque):
"""
Domain block threshold events handler
"""
_salt_send_domain_event(opaque, conn, domain, opaque['event'], {'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess}) |
def mod_run_check_cmd(cmd, filename, **check_cmd_opts):
'''
Execute the check_cmd logic.
Return a result dict if ``check_cmd`` succeeds (check_cmd == 0)
otherwise return True
'''
log.debug('running our check_cmd')
_cmd = '{0} {1}'.format(cmd, filename)
cret = __salt__['cmd.run_all'](_c... | def function[mod_run_check_cmd, parameter[cmd, filename]]:
constant[
Execute the check_cmd logic.
Return a result dict if ``check_cmd`` succeeds (check_cmd == 0)
otherwise return True
]
call[name[log].debug, parameter[constant[running our check_cmd]]]
variable[_cmd] assign[=] ca... | keyword[def] identifier[mod_run_check_cmd] ( identifier[cmd] , identifier[filename] ,** identifier[check_cmd_opts] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] )
identifier[_cmd] = literal[string] . identifier[format] ( identifier[cmd] , identifier[filename] )
identif... | def mod_run_check_cmd(cmd, filename, **check_cmd_opts):
"""
Execute the check_cmd logic.
Return a result dict if ``check_cmd`` succeeds (check_cmd == 0)
otherwise return True
"""
log.debug('running our check_cmd')
_cmd = '{0} {1}'.format(cmd, filename)
cret = __salt__['cmd.run_all'](_cm... |
def read_plink(file_prefix, verbose=True):
r"""Read PLINK files into Pandas data frames.
Parameters
----------
file_prefix : str
Path prefix to the set of PLINK files. It supports loading many BED
files at once using globstrings wildcard.
verbose : bool
``True`` for progress... | def function[read_plink, parameter[file_prefix, verbose]]:
constant[Read PLINK files into Pandas data frames.
Parameters
----------
file_prefix : str
Path prefix to the set of PLINK files. It supports loading many BED
files at once using globstrings wildcard.
verbose : bool
... | keyword[def] identifier[read_plink] ( identifier[file_prefix] , identifier[verbose] = keyword[True] ):
literal[string]
keyword[from] identifier[dask] . identifier[array] keyword[import] identifier[concatenate]
identifier[file_prefixes] = identifier[sorted] ( identifier[glob] ( identifier[file_pre... | def read_plink(file_prefix, verbose=True):
"""Read PLINK files into Pandas data frames.
Parameters
----------
file_prefix : str
Path prefix to the set of PLINK files. It supports loading many BED
files at once using globstrings wildcard.
verbose : bool
``True`` for progress ... |
def scale(p, factor, o=(0, 0)):
""" scale vector
Args:
p: point (x, y)
factor: scaling factor
o: origin (x, y)
"""
v = vector(o, p)
sv = v[0] * factor, v[1] * factor
return translate(sv, o) | def function[scale, parameter[p, factor, o]]:
constant[ scale vector
Args:
p: point (x, y)
factor: scaling factor
o: origin (x, y)
]
variable[v] assign[=] call[name[vector], parameter[name[o], name[p]]]
variable[sv] assign[=] tuple[[<ast.BinOp object at 0x7da1b24efc40>,... | keyword[def] identifier[scale] ( identifier[p] , identifier[factor] , identifier[o] =( literal[int] , literal[int] )):
literal[string]
identifier[v] = identifier[vector] ( identifier[o] , identifier[p] )
identifier[sv] = identifier[v] [ literal[int] ]* identifier[factor] , identifier[v] [ literal[int]... | def scale(p, factor, o=(0, 0)):
""" scale vector
Args:
p: point (x, y)
factor: scaling factor
o: origin (x, y)
"""
v = vector(o, p)
sv = (v[0] * factor, v[1] * factor)
return translate(sv, o) |
def opening_hours(location=None, concise=False):
"""
Creates a rendered listing of hours.
"""
template_name = 'openinghours/opening_hours_list.html'
days = [] # [{'hours': '9:00am to 5:00pm', 'name': u'Monday'}, {'hours...
# Without `location`, choose the first company.
if location:
... | def function[opening_hours, parameter[location, concise]]:
constant[
Creates a rendered listing of hours.
]
variable[template_name] assign[=] constant[openinghours/opening_hours_list.html]
variable[days] assign[=] list[[]]
if name[location] begin[:]
variable[ohrs]... | keyword[def] identifier[opening_hours] ( identifier[location] = keyword[None] , identifier[concise] = keyword[False] ):
literal[string]
identifier[template_name] = literal[string]
identifier[days] =[]
keyword[if] identifier[location] :
identifier[ohrs] = identifier[OpeningHours] ... | def opening_hours(location=None, concise=False):
"""
Creates a rendered listing of hours.
"""
template_name = 'openinghours/opening_hours_list.html'
days = [] # [{'hours': '9:00am to 5:00pm', 'name': u'Monday'}, {'hours...
# Without `location`, choose the first company.
if location:
... |
def get_config_tuple_from_egrc(egrc_path):
"""
Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None.
"""
with open(egrc_path, 'r'... | def function[get_config_tuple_from_egrc, parameter[egrc_path]]:
constant[
Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None.
]... | keyword[def] identifier[get_config_tuple_from_egrc] ( identifier[egrc_path] ):
literal[string]
keyword[with] identifier[open] ( identifier[egrc_path] , literal[string] ) keyword[as] identifier[egrc] :
keyword[try] :
identifier[config] = identifier[ConfigParser] . identifier[RawConfi... | def get_config_tuple_from_egrc(egrc_path):
"""
Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None.
"""
with open(egrc_path, 'r'... |
def check(self, var):
"""Return True if the variable matches this type, and False otherwise."""
if self._class is None: self._init()
return self._class and self._checker(var, self._class) | def function[check, parameter[self, var]]:
constant[Return True if the variable matches this type, and False otherwise.]
if compare[name[self]._class is constant[None]] begin[:]
call[name[self]._init, parameter[]]
return[<ast.BoolOp object at 0x7da1b05be320>] | keyword[def] identifier[check] ( identifier[self] , identifier[var] ):
literal[string]
keyword[if] identifier[self] . identifier[_class] keyword[is] keyword[None] : identifier[self] . identifier[_init] ()
keyword[return] identifier[self] . identifier[_class] keyword[and] identifier[s... | def check(self, var):
"""Return True if the variable matches this type, and False otherwise."""
if self._class is None:
self._init() # depends on [control=['if'], data=[]]
return self._class and self._checker(var, self._class) |
def diff(self, mail_a, mail_b):
""" Return difference in bytes between two mails' normalized body.
TODO: rewrite the diff algorithm to not rely on naive unified diff
result parsing.
"""
return len(''.join(unified_diff(
mail_a.body_lines, mail_b.body_lines,
... | def function[diff, parameter[self, mail_a, mail_b]]:
constant[ Return difference in bytes between two mails' normalized body.
TODO: rewrite the diff algorithm to not rely on naive unified diff
result parsing.
]
return[call[name[len], parameter[call[constant[].join, parameter[call[na... | keyword[def] identifier[diff] ( identifier[self] , identifier[mail_a] , identifier[mail_b] ):
literal[string]
keyword[return] identifier[len] ( literal[string] . identifier[join] ( identifier[unified_diff] (
identifier[mail_a] . identifier[body_lines] , identifier[mail_b] . identifier[bod... | def diff(self, mail_a, mail_b):
""" Return difference in bytes between two mails' normalized body.
TODO: rewrite the diff algorithm to not rely on naive unified diff
result parsing.
"""
# Ignore difference in filename lenghts and timestamps.
return len(''.join(unified_diff(mail_a.bo... |
def _get_asset_load(self, asset_type):
"""
Helper function to dynamically create *_load_time properties. Return
value is in ms.
"""
if asset_type == 'initial':
return self.actual_page['time']
elif asset_type == 'content':
return self.pageTimings['o... | def function[_get_asset_load, parameter[self, asset_type]]:
constant[
Helper function to dynamically create *_load_time properties. Return
value is in ms.
]
if compare[name[asset_type] equal[==] constant[initial]] begin[:]
return[call[name[self].actual_page][constant[time... | keyword[def] identifier[_get_asset_load] ( identifier[self] , identifier[asset_type] ):
literal[string]
keyword[if] identifier[asset_type] == literal[string] :
keyword[return] identifier[self] . identifier[actual_page] [ literal[string] ]
keyword[elif] identifier[asset_type... | def _get_asset_load(self, asset_type):
"""
Helper function to dynamically create *_load_time properties. Return
value is in ms.
"""
if asset_type == 'initial':
return self.actual_page['time'] # depends on [control=['if'], data=[]]
elif asset_type == 'content':
return... |
def _quantile_function(self, alpha=0.5, smallest_count=None):
"""Return a function that returns the quantile values for this
histogram.
"""
total = float(self.total())
smallest_observed_count = min(itervalues(self))
if smallest_count is None:
smallest_count ... | def function[_quantile_function, parameter[self, alpha, smallest_count]]:
constant[Return a function that returns the quantile values for this
histogram.
]
variable[total] assign[=] call[name[float], parameter[call[name[self].total, parameter[]]]]
variable[smallest_observed_coun... | keyword[def] identifier[_quantile_function] ( identifier[self] , identifier[alpha] = literal[int] , identifier[smallest_count] = keyword[None] ):
literal[string]
identifier[total] = identifier[float] ( identifier[self] . identifier[total] ())
identifier[smallest_observed_count] = identifi... | def _quantile_function(self, alpha=0.5, smallest_count=None):
"""Return a function that returns the quantile values for this
histogram.
"""
total = float(self.total())
smallest_observed_count = min(itervalues(self))
if smallest_count is None:
smallest_count = smallest_observed_c... |
def init():
"""Initialize the communities file storage."""
try:
initialize_communities_bucket()
click.secho('Community init successful.', fg='green')
except FilesException as e:
click.secho(e.message, fg='red') | def function[init, parameter[]]:
constant[Initialize the communities file storage.]
<ast.Try object at 0x7da18ede5690> | keyword[def] identifier[init] ():
literal[string]
keyword[try] :
identifier[initialize_communities_bucket] ()
identifier[click] . identifier[secho] ( literal[string] , identifier[fg] = literal[string] )
keyword[except] identifier[FilesException] keyword[as] identifier[e] :
... | def init():
"""Initialize the communities file storage."""
try:
initialize_communities_bucket()
click.secho('Community init successful.', fg='green') # depends on [control=['try'], data=[]]
except FilesException as e:
click.secho(e.message, fg='red') # depends on [control=['except'... |
def count_unique_sequences(
allele_reads,
max_prefix_size=None,
max_suffix_size=None):
"""
Given a list of AlleleRead objects, extracts all unique
(prefix, allele, suffix) sequences and associate each with the number
of reads that contain that sequence.
"""
groups = group... | def function[count_unique_sequences, parameter[allele_reads, max_prefix_size, max_suffix_size]]:
constant[
Given a list of AlleleRead objects, extracts all unique
(prefix, allele, suffix) sequences and associate each with the number
of reads that contain that sequence.
]
variable[groups]... | keyword[def] identifier[count_unique_sequences] (
identifier[allele_reads] ,
identifier[max_prefix_size] = keyword[None] ,
identifier[max_suffix_size] = keyword[None] ):
literal[string]
identifier[groups] = identifier[group_unique_sequences] (
identifier[allele_reads] ,
identifier[max_prefix_s... | def count_unique_sequences(allele_reads, max_prefix_size=None, max_suffix_size=None):
"""
Given a list of AlleleRead objects, extracts all unique
(prefix, allele, suffix) sequences and associate each with the number
of reads that contain that sequence.
"""
groups = group_unique_sequences(allele_... |
def coin_toss(self):
"""Gets information relating to the opening coin toss.
Keys are:
* wonToss - contains the ID of the team that won the toss
* deferred - bool whether the team that won the toss deferred it
:returns: Dictionary of coin toss-related info.
"""
d... | def function[coin_toss, parameter[self]]:
constant[Gets information relating to the opening coin toss.
Keys are:
* wonToss - contains the ID of the team that won the toss
* deferred - bool whether the team that won the toss deferred it
:returns: Dictionary of coin toss-related ... | keyword[def] identifier[coin_toss] ( identifier[self] ):
literal[string]
identifier[doc] = identifier[self] . identifier[get_doc] ()
identifier[table] = identifier[doc] ( literal[string] )
identifier[giTable] = identifier[sportsref] . identifier[utils] . identifier[parse_info_tabl... | def coin_toss(self):
"""Gets information relating to the opening coin toss.
Keys are:
* wonToss - contains the ID of the team that won the toss
* deferred - bool whether the team that won the toss deferred it
:returns: Dictionary of coin toss-related info.
"""
doc = sel... |
def update_anomalous_score(self):
"""Update anomalous score.
New anomalous score is a weighted average of differences
between current summary and reviews. The weights come from credibilities.
Therefore, the new anomalous score of reviewer :math:`p` is as
.. math::
... | def function[update_anomalous_score, parameter[self]]:
constant[Update anomalous score.
New anomalous score is a weighted average of differences
between current summary and reviews. The weights come from credibilities.
Therefore, the new anomalous score of reviewer :math:`p` is as
... | keyword[def] identifier[update_anomalous_score] ( identifier[self] ):
literal[string]
identifier[products] = identifier[self] . identifier[_graph] . identifier[retrieve_products] ( identifier[self] )
identifier[diffs] =[
identifier[p] . identifier[summary] . identifier[difference]... | def update_anomalous_score(self):
"""Update anomalous score.
New anomalous score is a weighted average of differences
between current summary and reviews. The weights come from credibilities.
Therefore, the new anomalous score of reviewer :math:`p` is as
.. math::
{\\r... |
def read_namespaced_pod_preset(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod_preset # noqa: E501
read the specified PodPreset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True... | def function[read_namespaced_pod_preset, parameter[self, name, namespace]]:
constant[read_namespaced_pod_preset # noqa: E501
read the specified PodPreset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=T... | keyword[def] identifier[read_namespaced_pod_preset] ( identifier[self] , identifier[name] , identifier[namespace] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
... | def read_namespaced_pod_preset(self, name, namespace, **kwargs): # noqa: E501
"read_namespaced_pod_preset # noqa: E501\n\n read the specified PodPreset # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n... |
def patch_namespaced_role_binding(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_role_binding # noqa: E501
partially update the specified RoleBinding # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, ... | def function[patch_namespaced_role_binding, parameter[self, name, namespace, body]]:
constant[patch_namespaced_role_binding # noqa: E501
partially update the specified RoleBinding # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP reques... | keyword[def] identifier[patch_namespaced_role_binding] ( identifier[self] , identifier[name] , identifier[namespace] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( liter... | def patch_namespaced_role_binding(self, name, namespace, body, **kwargs): # noqa: E501
"patch_namespaced_role_binding # noqa: E501\n\n partially update the specified RoleBinding # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, pl... |
def migrate(pool, from_connection, to_connection):
"""
Migrate tool for pyspider
"""
f = connect_database(from_connection)
t = connect_database(to_connection)
if isinstance(f, ProjectDB):
for each in f.get_all():
each = unicode_obj(each)
logging.info("projectdb: ... | def function[migrate, parameter[pool, from_connection, to_connection]]:
constant[
Migrate tool for pyspider
]
variable[f] assign[=] call[name[connect_database], parameter[name[from_connection]]]
variable[t] assign[=] call[name[connect_database], parameter[name[to_connection]]]
if... | keyword[def] identifier[migrate] ( identifier[pool] , identifier[from_connection] , identifier[to_connection] ):
literal[string]
identifier[f] = identifier[connect_database] ( identifier[from_connection] )
identifier[t] = identifier[connect_database] ( identifier[to_connection] )
keyword[if] id... | def migrate(pool, from_connection, to_connection):
"""
Migrate tool for pyspider
"""
f = connect_database(from_connection)
t = connect_database(to_connection)
if isinstance(f, ProjectDB):
for each in f.get_all():
each = unicode_obj(each)
logging.info('projectdb: %... |
def load(path=None, **kwargs):
'''
Loads the configuration from the file provided onto the device.
path (required)
Path where the configuration/template file is present. If the file has
a ``.conf`` extension, the content is treated as text format. If the
file has a ``.xml`` extensio... | def function[load, parameter[path]]:
constant[
Loads the configuration from the file provided onto the device.
path (required)
Path where the configuration/template file is present. If the file has
a ``.conf`` extension, the content is treated as text format. If the
file has a `... | keyword[def] identifier[load] ( identifier[path] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[conn] = identifier[__proxy__] [ literal[string] ]()
identifier[ret] ={}
identifier[ret] [ literal[string] ]= keyword[True]
keyword[if] identifier[path] keyword[is] keywo... | def load(path=None, **kwargs):
"""
Loads the configuration from the file provided onto the device.
path (required)
Path where the configuration/template file is present. If the file has
a ``.conf`` extension, the content is treated as text format. If the
file has a ``.xml`` extensio... |
def get_member_groups(
self, object_id, security_enabled_only, additional_properties=None, custom_headers=None, raw=False, **operation_config):
"""Gets a collection that contains the object IDs of the groups of which
the user is a member.
:param object_id: The object ID of the user ... | def function[get_member_groups, parameter[self, object_id, security_enabled_only, additional_properties, custom_headers, raw]]:
constant[Gets a collection that contains the object IDs of the groups of which
the user is a member.
:param object_id: The object ID of the user for which to get group... | keyword[def] identifier[get_member_groups] (
identifier[self] , identifier[object_id] , identifier[security_enabled_only] , identifier[additional_properties] = keyword[None] , identifier[custom_headers] = keyword[None] , identifier[raw] = keyword[False] ,** identifier[operation_config] ):
literal[string]
... | def get_member_groups(self, object_id, security_enabled_only, additional_properties=None, custom_headers=None, raw=False, **operation_config):
"""Gets a collection that contains the object IDs of the groups of which
the user is a member.
:param object_id: The object ID of the user for which to get ... |
def create_connection(self, session=None):
"""
Create connection in the Connection table, according to whether it uses
proxy, TCP, UNIX sockets, SSL. Connection ID will be randomly generated.
:param session: Session of the SQL Alchemy ORM (automatically generated with
... | def function[create_connection, parameter[self, session]]:
constant[
Create connection in the Connection table, according to whether it uses
proxy, TCP, UNIX sockets, SSL. Connection ID will be randomly generated.
:param session: Session of the SQL Alchemy ORM (automatically generated w... | keyword[def] identifier[create_connection] ( identifier[self] , identifier[session] = keyword[None] ):
literal[string]
identifier[connection] = identifier[Connection] ( identifier[conn_id] = identifier[self] . identifier[db_conn_id] )
identifier[uri] = identifier[self] . identifier[_genera... | def create_connection(self, session=None):
"""
Create connection in the Connection table, according to whether it uses
proxy, TCP, UNIX sockets, SSL. Connection ID will be randomly generated.
:param session: Session of the SQL Alchemy ORM (automatically generated with
... |
def Audio(self, run, tag):
"""Retrieve the audio events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not available ... | def function[Audio, parameter[self, run, tag]]:
constant[Retrieve the audio events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not foun... | keyword[def] identifier[Audio] ( identifier[self] , identifier[run] , identifier[tag] ):
literal[string]
identifier[accumulator] = identifier[self] . identifier[GetAccumulator] ( identifier[run] )
keyword[return] identifier[accumulator] . identifier[Audio] ( identifier[tag] ) | def Audio(self, run, tag):
"""Retrieve the audio events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not available ... |
def process_ip_frame(self,
id=None,
msg=None):
"""process_ip_frame
Convert a complex nested json dictionary
to a flattened dictionary and capture
all unique keys for table construction
:param id: key for this msg
:param ... | def function[process_ip_frame, parameter[self, id, msg]]:
constant[process_ip_frame
Convert a complex nested json dictionary
to a flattened dictionary and capture
all unique keys for table construction
:param id: key for this msg
:param msg: ip frame for packet
... | keyword[def] identifier[process_ip_frame] ( identifier[self] ,
identifier[id] = keyword[None] ,
identifier[msg] = keyword[None] ):
literal[string]
identifier[df] = identifier[json_normalize] ( identifier[msg] )
identifier[dt] = identifier[json] . identifier[loads] ( id... | def process_ip_frame(self, id=None, msg=None):
"""process_ip_frame
Convert a complex nested json dictionary
to a flattened dictionary and capture
all unique keys for table construction
:param id: key for this msg
:param msg: ip frame for packet
"""
# normalize i... |
def sample_train_batch(self):
"""Sample a training batch (data and label)."""
batch = []
labels = []
num_groups = self.batch_size // self.batch_k
# For CUB200, we use the first 100 classes for training.
sampled_classes = np.random.choice(100, num_groups, replace=False)
... | def function[sample_train_batch, parameter[self]]:
constant[Sample a training batch (data and label).]
variable[batch] assign[=] list[[]]
variable[labels] assign[=] list[[]]
variable[num_groups] assign[=] binary_operation[name[self].batch_size <ast.FloorDiv object at 0x7da2590d6bc0> name... | keyword[def] identifier[sample_train_batch] ( identifier[self] ):
literal[string]
identifier[batch] =[]
identifier[labels] =[]
identifier[num_groups] = identifier[self] . identifier[batch_size] // identifier[self] . identifier[batch_k]
identifier[sampled_classe... | def sample_train_batch(self):
"""Sample a training batch (data and label)."""
batch = []
labels = []
num_groups = self.batch_size // self.batch_k
# For CUB200, we use the first 100 classes for training.
sampled_classes = np.random.choice(100, num_groups, replace=False)
for i in range(num_gro... |
def set_preshared_key(self, new_key):
"""
Set the preshared key for this VPN. A pre-shared key is only
present when the tunnel type is 'VPN' or the encryption mode
is 'transport'.
:return: None
"""
if self.data.get('preshared_key'):
self.updat... | def function[set_preshared_key, parameter[self, new_key]]:
constant[
Set the preshared key for this VPN. A pre-shared key is only
present when the tunnel type is 'VPN' or the encryption mode
is 'transport'.
:return: None
]
if call[name[self].data.get, par... | keyword[def] identifier[set_preshared_key] ( identifier[self] , identifier[new_key] ):
literal[string]
keyword[if] identifier[self] . identifier[data] . identifier[get] ( literal[string] ):
identifier[self] . identifier[update] ( identifier[preshared_key] = identifier[new_key] ) | def set_preshared_key(self, new_key):
"""
Set the preshared key for this VPN. A pre-shared key is only
present when the tunnel type is 'VPN' or the encryption mode
is 'transport'.
:return: None
"""
if self.data.get('preshared_key'):
self.update(preshared_... |
def identify(self, text, **kwargs):
"""
Identify language.
Identifies the language of the input text.
:param str text: Input text in UTF-8 format.
:param dict headers: A `dict` containing the request headers
:return: A `DetailedResponse` containing the result, headers a... | def function[identify, parameter[self, text]]:
constant[
Identify language.
Identifies the language of the input text.
:param str text: Input text in UTF-8 format.
:param dict headers: A `dict` containing the request headers
:return: A `DetailedResponse` containing the ... | keyword[def] identifier[identify] ( identifier[self] , identifier[text] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[text] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[headers] ={}
keyword[i... | def identify(self, text, **kwargs):
"""
Identify language.
Identifies the language of the input text.
:param str text: Input text in UTF-8 format.
:param dict headers: A `dict` containing the request headers
:return: A `DetailedResponse` containing the result, headers and H... |
def view_plugins(category=None):
""" return a view of the loaded plugin names and descriptions
Parameters
----------
category : None or str
if str, apply for single plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, ... | def function[view_plugins, parameter[category]]:
constant[ return a view of the loaded plugin names and descriptions
Parameters
----------
category : None or str
if str, apply for single plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugin... | keyword[def] identifier[view_plugins] ( identifier[category] = keyword[None] ):
literal[string]
keyword[if] identifier[category] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[category] == literal[string] :
keyword[return] {
identifier[name] :{ liter... | def view_plugins(category=None):
""" return a view of the loaded plugin names and descriptions
Parameters
----------
category : None or str
if str, apply for single plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, ... |
def problem(problem_name, **kwargs):
"""Get possibly copied/reversed problem in `base_registry` or `env_registry`.
Args:
problem_name: string problem name. See `parse_problem_name`.
**kwargs: forwarded to env problem's initialize method.
Returns:
possibly reversed/copied version of base problem regi... | def function[problem, parameter[problem_name]]:
constant[Get possibly copied/reversed problem in `base_registry` or `env_registry`.
Args:
problem_name: string problem name. See `parse_problem_name`.
**kwargs: forwarded to env problem's initialize method.
Returns:
possibly reversed/copied versi... | keyword[def] identifier[problem] ( identifier[problem_name] ,** identifier[kwargs] ):
literal[string]
identifier[spec] = identifier[parse_problem_name] ( identifier[problem_name] )
keyword[try] :
keyword[return] identifier[Registries] . identifier[problems] [ identifier[spec] . identifier[base_name] ]... | def problem(problem_name, **kwargs):
"""Get possibly copied/reversed problem in `base_registry` or `env_registry`.
Args:
problem_name: string problem name. See `parse_problem_name`.
**kwargs: forwarded to env problem's initialize method.
Returns:
possibly reversed/copied version of base problem re... |
def decode_transformer(encoder_output, encoder_decoder_attention_bias, targets,
hparams, name):
"""Original Transformer decoder."""
with tf.variable_scope(name):
targets = common_layers.flatten4d3d(targets)
decoder_input, decoder_self_bias = (
transformer.transformer_prepare_... | def function[decode_transformer, parameter[encoder_output, encoder_decoder_attention_bias, targets, hparams, name]]:
constant[Original Transformer decoder.]
with call[name[tf].variable_scope, parameter[name[name]]] begin[:]
variable[targets] assign[=] call[name[common_layers].flatten4d3d... | keyword[def] identifier[decode_transformer] ( identifier[encoder_output] , identifier[encoder_decoder_attention_bias] , identifier[targets] ,
identifier[hparams] , identifier[name] ):
literal[string]
keyword[with] identifier[tf] . identifier[variable_scope] ( identifier[name] ):
identifier[targets] = id... | def decode_transformer(encoder_output, encoder_decoder_attention_bias, targets, hparams, name):
"""Original Transformer decoder."""
with tf.variable_scope(name):
targets = common_layers.flatten4d3d(targets)
(decoder_input, decoder_self_bias) = transformer.transformer_prepare_decoder(targets, hpa... |
def _to_api_value(self, attribute_type, value):
"""Return a parsed value for the API."""
if not value:
return None
if isinstance(attribute_type, properties.Instance):
return value.to_api()
if isinstance(attribute_type, properties.List):
return self.... | def function[_to_api_value, parameter[self, attribute_type, value]]:
constant[Return a parsed value for the API.]
if <ast.UnaryOp object at 0x7da204623730> begin[:]
return[constant[None]]
if call[name[isinstance], parameter[name[attribute_type], name[properties].Instance]] begin[:]
... | keyword[def] identifier[_to_api_value] ( identifier[self] , identifier[attribute_type] , identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[value] :
keyword[return] keyword[None]
keyword[if] identifier[isinstance] ( identifier[attribute_type] , ide... | def _to_api_value(self, attribute_type, value):
"""Return a parsed value for the API."""
if not value:
return None # depends on [control=['if'], data=[]]
if isinstance(attribute_type, properties.Instance):
return value.to_api() # depends on [control=['if'], data=[]]
if isinstance(attri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.