code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def makeResetPacket(ID, param):
"""
Resets a servo to one of 3 reset states:
XL320_RESET_ALL = 0xFF
XL320_RESET_ALL_BUT_ID = 0x01
XL320_RESET_ALL_BUT_ID_BAUD_RATE = 0x02
"""
if param not in [0x01, 0x02, 0xff]:
raise Exception('Packet.makeResetPacket invalide parameter {}'.format(par... | def function[makeResetPacket, parameter[ID, param]]:
constant[
Resets a servo to one of 3 reset states:
XL320_RESET_ALL = 0xFF
XL320_RESET_ALL_BUT_ID = 0x01
XL320_RESET_ALL_BUT_ID_BAUD_RATE = 0x02
]
if compare[name[param] <ast.NotIn object at 0x7da2590d7190> list[[<ast.C... | keyword[def] identifier[makeResetPacket] ( identifier[ID] , identifier[param] ):
literal[string]
keyword[if] identifier[param] keyword[not] keyword[in] [ literal[int] , literal[int] , literal[int] ]:
keyword[raise] identifier[Exception] ( literal[string] . identifier[format] ( identifier[param] ))
id... | def makeResetPacket(ID, param):
"""
Resets a servo to one of 3 reset states:
XL320_RESET_ALL = 0xFF
XL320_RESET_ALL_BUT_ID = 0x01
XL320_RESET_ALL_BUT_ID_BAUD_RATE = 0x02
"""
if param not in [1, 2, 255]:
raise Exception('Packet.makeResetPacket invalide parameter {}'.forma... |
def token(self):
""" returns the token for the site """
if self._token is None or \
datetime.datetime.now() >= self._token_expires_on:
result = self._getTokenArcMap()
if 'error' in result:
self._valid = False
self._message = result
... | def function[token, parameter[self]]:
constant[ returns the token for the site ]
if <ast.BoolOp object at 0x7da1b12903d0> begin[:]
variable[result] assign[=] call[name[self]._getTokenArcMap, parameter[]]
if compare[constant[error] in name[result]] begin[:]
... | keyword[def] identifier[token] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_token] keyword[is] keyword[None] keyword[or] identifier[datetime] . identifier[datetime] . identifier[now] ()>= identifier[self] . identifier[_token_expires_on] :
identi... | def token(self):
""" returns the token for the site """
if self._token is None or datetime.datetime.now() >= self._token_expires_on:
result = self._getTokenArcMap()
if 'error' in result:
self._valid = False
self._message = result # depends on [control=['if'], data=['resu... |
def list_directories_and_files(self, share_name, directory_name=None,
num_results=None, marker=None, timeout=None):
'''
Returns a generator to list the directories and files under the specified share.
The generator will lazily follow the continuation tokens re... | def function[list_directories_and_files, parameter[self, share_name, directory_name, num_results, marker, timeout]]:
constant[
Returns a generator to list the directories and files under the specified share.
The generator will lazily follow the continuation tokens returned by
the service... | keyword[def] identifier[list_directories_and_files] ( identifier[self] , identifier[share_name] , identifier[directory_name] = keyword[None] ,
identifier[num_results] = keyword[None] , identifier[marker] = keyword[None] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[args] =( i... | def list_directories_and_files(self, share_name, directory_name=None, num_results=None, marker=None, timeout=None):
"""
Returns a generator to list the directories and files under the specified share.
The generator will lazily follow the continuation tokens returned by
the service and stop w... |
def all(self, endpoint, *args, **kwargs):
"""Retrieve all the data of a paginated endpoint, using GET.
:returns: The endpoint unpaginated data
:rtype: dict
"""
# 1. Initialize the pagination parameters.
kwargs.setdefault('params', {})['offset'] = 0
kwargs.setdefau... | def function[all, parameter[self, endpoint]]:
constant[Retrieve all the data of a paginated endpoint, using GET.
:returns: The endpoint unpaginated data
:rtype: dict
]
call[call[name[kwargs].setdefault, parameter[constant[params], dictionary[[], []]]]][constant[offset]] assign[=]... | keyword[def] identifier[all] ( identifier[self] , identifier[endpoint] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] . identifier[setdefault] ( literal[string] ,{})[ literal[string] ]= literal[int]
identifier[kwargs] . identifier[setdefault] ( l... | def all(self, endpoint, *args, **kwargs):
"""Retrieve all the data of a paginated endpoint, using GET.
:returns: The endpoint unpaginated data
:rtype: dict
"""
# 1. Initialize the pagination parameters.
kwargs.setdefault('params', {})['offset'] = 0
kwargs.setdefault('params', {})... |
def get_all_conversion_chains(self, from_type: Type[Any] = JOKER, to_type: Type[Any] = JOKER)\
-> Tuple[List[Converter], List[Converter], List[Converter]]:
"""
Utility method to find all converters or conversion chains matching the provided query.
:param from_type: a required type o... | def function[get_all_conversion_chains, parameter[self, from_type, to_type]]:
constant[
Utility method to find all converters or conversion chains matching the provided query.
:param from_type: a required type of input object, or JOKER for 'wildcard'(*) .
WARNING: "from_type=AnyObject/o... | keyword[def] identifier[get_all_conversion_chains] ( identifier[self] , identifier[from_type] : identifier[Type] [ identifier[Any] ]= identifier[JOKER] , identifier[to_type] : identifier[Type] [ identifier[Any] ]= identifier[JOKER] )-> identifier[Tuple] [ identifier[List] [ identifier[Converter] ], identifier[List] [... | def get_all_conversion_chains(self, from_type: Type[Any]=JOKER, to_type: Type[Any]=JOKER) -> Tuple[List[Converter], List[Converter], List[Converter]]:
"""
Utility method to find all converters or conversion chains matching the provided query.
:param from_type: a required type of input object, or JO... |
def get_comments_are_moderated(instance):
"""
Check if comments are moderated for the instance
"""
if not IS_INSTALLED:
return False
try:
# Get the moderator which is installed for this model.
mod = moderator._registry[instance.__class__]
except KeyError:
# No mo... | def function[get_comments_are_moderated, parameter[instance]]:
constant[
Check if comments are moderated for the instance
]
if <ast.UnaryOp object at 0x7da1b27e1960> begin[:]
return[constant[False]]
<ast.Try object at 0x7da1b27e3430>
return[call[name[CommentModerator].moderate, p... | keyword[def] identifier[get_comments_are_moderated] ( identifier[instance] ):
literal[string]
keyword[if] keyword[not] identifier[IS_INSTALLED] :
keyword[return] keyword[False]
keyword[try] :
identifier[mod] = identifier[moderator] . identifier[_registry] [ identifier[insta... | def get_comments_are_moderated(instance):
"""
Check if comments are moderated for the instance
"""
if not IS_INSTALLED:
return False # depends on [control=['if'], data=[]]
try:
# Get the moderator which is installed for this model.
mod = moderator._registry[instance.__class_... |
def _probe_characteristics(self, conn, services, timeout=5.0):
"""Probe gatt services for all associated characteristics in a BLE device
Args:
conn (int): the connection handle to probe
services (dict): a dictionary of services produced by probe_services()
timeout (f... | def function[_probe_characteristics, parameter[self, conn, services, timeout]]:
constant[Probe gatt services for all associated characteristics in a BLE device
Args:
conn (int): the connection handle to probe
services (dict): a dictionary of services produced by probe_services()... | keyword[def] identifier[_probe_characteristics] ( identifier[self] , identifier[conn] , identifier[services] , identifier[timeout] = literal[int] ):
literal[string]
keyword[for] identifier[service] keyword[in] identifier[services] . identifier[values] ():
identifier[success] , iden... | def _probe_characteristics(self, conn, services, timeout=5.0):
"""Probe gatt services for all associated characteristics in a BLE device
Args:
conn (int): the connection handle to probe
services (dict): a dictionary of services produced by probe_services()
timeout (float... |
def __params_descriptor(self, message_type, request_kind, path, method_id,
request_params_class):
"""Describe the parameters of a method.
If the message_type is not a ResourceContainer, will fall back to
__params_descriptor_without_container (which will eventually be deprecated).
... | def function[__params_descriptor, parameter[self, message_type, request_kind, path, method_id, request_params_class]]:
constant[Describe the parameters of a method.
If the message_type is not a ResourceContainer, will fall back to
__params_descriptor_without_container (which will eventually be deprecat... | keyword[def] identifier[__params_descriptor] ( identifier[self] , identifier[message_type] , identifier[request_kind] , identifier[path] , identifier[method_id] ,
identifier[request_params_class] ):
literal[string]
identifier[path_parameter_dict] = identifier[self] . identifier[__get_path_parameters] ( id... | def __params_descriptor(self, message_type, request_kind, path, method_id, request_params_class):
"""Describe the parameters of a method.
If the message_type is not a ResourceContainer, will fall back to
__params_descriptor_without_container (which will eventually be deprecated).
If the message type i... |
def __respond_with_list(self, data):
"""
Builds a python list from a json object
:param data: the json object
:returns: a nested list
"""
response = []
if isinstance(data, dict):
data.pop('seq', None)
data = list(data.values())
fo... | def function[__respond_with_list, parameter[self, data]]:
constant[
Builds a python list from a json object
:param data: the json object
:returns: a nested list
]
variable[response] assign[=] list[[]]
if call[name[isinstance], parameter[name[data], name[dict]]] b... | keyword[def] identifier[__respond_with_list] ( identifier[self] , identifier[data] ):
literal[string]
identifier[response] =[]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[dict] ):
identifier[data] . identifier[pop] ( literal[string] , keyword[None] )
... | def __respond_with_list(self, data):
"""
Builds a python list from a json object
:param data: the json object
:returns: a nested list
"""
response = []
if isinstance(data, dict):
data.pop('seq', None)
data = list(data.values()) # depends on [control=['if'], ... |
def to_dict(self, converter=None):
"""Returns a copy dict of the current object
If a converter function is given, pass each value to it.
Per default the values are converted by `self.stringify`.
"""
if converter is None:
converter = self.stringify
out = dict(... | def function[to_dict, parameter[self, converter]]:
constant[Returns a copy dict of the current object
If a converter function is given, pass each value to it.
Per default the values are converted by `self.stringify`.
]
if compare[name[converter] is constant[None]] begin[:]
... | keyword[def] identifier[to_dict] ( identifier[self] , identifier[converter] = keyword[None] ):
literal[string]
keyword[if] identifier[converter] keyword[is] keyword[None] :
identifier[converter] = identifier[self] . identifier[stringify]
identifier[out] = identifier[dict] ... | def to_dict(self, converter=None):
"""Returns a copy dict of the current object
If a converter function is given, pass each value to it.
Per default the values are converted by `self.stringify`.
"""
if converter is None:
converter = self.stringify # depends on [control=['if'], ... |
def get_object(self, name):
"""Retrieve an object by a dotted name relative to the space."""
parts = name.split(".")
child = parts.pop(0)
if parts:
return self.spaces[child].get_object(".".join(parts))
else:
return self._namespace_impl[child] | def function[get_object, parameter[self, name]]:
constant[Retrieve an object by a dotted name relative to the space.]
variable[parts] assign[=] call[name[name].split, parameter[constant[.]]]
variable[child] assign[=] call[name[parts].pop, parameter[constant[0]]]
if name[parts] begin[:]
... | keyword[def] identifier[get_object] ( identifier[self] , identifier[name] ):
literal[string]
identifier[parts] = identifier[name] . identifier[split] ( literal[string] )
identifier[child] = identifier[parts] . identifier[pop] ( literal[int] )
keyword[if] identifier[parts] :
... | def get_object(self, name):
"""Retrieve an object by a dotted name relative to the space."""
parts = name.split('.')
child = parts.pop(0)
if parts:
return self.spaces[child].get_object('.'.join(parts)) # depends on [control=['if'], data=[]]
else:
return self._namespace_impl[child] |
def get_single_external_tool_accounts(self, account_id, external_tool_id):
"""
Get a single external tool.
Returns the specified external tool.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["... | def function[get_single_external_tool_accounts, parameter[self, account_id, external_tool_id]]:
constant[
Get a single external tool.
Returns the specified external tool.
]
variable[path] assign[=] dictionary[[], []]
variable[data] assign[=] dictionary[[], []]
va... | keyword[def] identifier[get_single_external_tool_accounts] ( identifier[self] , identifier[account_id] , identifier[external_tool_id] ):
literal[string]
identifier[path] ={}
identifier[data] ={}
identifier[params] ={}
literal[string]
identifier... | def get_single_external_tool_accounts(self, account_id, external_tool_id):
"""
Get a single external tool.
Returns the specified external tool.
"""
path = {}
data = {}
params = {} # REQUIRED - PATH - account_id
'ID'
path['account_id'] = account_id # REQUIRED - PATH - e... |
def join(self, timeout=None):
"""Overwrites `threading.Thread.join`, to allow handling of exceptions thrown by threads
from within the main app."""
Thread.join(self, timeout=timeout)
if self.exc:
msg = "Thread '%s' threw an exception `%s`: %s" \
% (self.getN... | def function[join, parameter[self, timeout]]:
constant[Overwrites `threading.Thread.join`, to allow handling of exceptions thrown by threads
from within the main app.]
call[name[Thread].join, parameter[name[self]]]
if name[self].exc begin[:]
variable[msg] assign[=] binary... | keyword[def] identifier[join] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[Thread] . identifier[join] ( identifier[self] , identifier[timeout] = identifier[timeout] )
keyword[if] identifier[self] . identifier[exc] :
identifier[msg] = ... | def join(self, timeout=None):
"""Overwrites `threading.Thread.join`, to allow handling of exceptions thrown by threads
from within the main app."""
Thread.join(self, timeout=timeout)
if self.exc:
msg = "Thread '%s' threw an exception `%s`: %s" % (self.getName(), self.exc[0].__name__, self.ex... |
def handle(self, request, buffer_size):
"""
Handle a message
:param request: the request socket.
:param buffer_size: the buffer size.
:return: True if success, False otherwise
"""
logger = self.logger
data = self.__receive(request, buffer_size)
if... | def function[handle, parameter[self, request, buffer_size]]:
constant[
Handle a message
:param request: the request socket.
:param buffer_size: the buffer size.
:return: True if success, False otherwise
]
variable[logger] assign[=] name[self].logger
variab... | keyword[def] identifier[handle] ( identifier[self] , identifier[request] , identifier[buffer_size] ):
literal[string]
identifier[logger] = identifier[self] . identifier[logger]
identifier[data] = identifier[self] . identifier[__receive] ( identifier[request] , identifier[buffer_size] )
... | def handle(self, request, buffer_size):
"""
Handle a message
:param request: the request socket.
:param buffer_size: the buffer size.
:return: True if success, False otherwise
"""
logger = self.logger
data = self.__receive(request, buffer_size)
if data is None:
... |
def facets_on_hull(self):
"""
Find which facets of the mesh are on the convex hull.
Returns
---------
on_hull : (len(mesh.facets),) bool
is A facet on the meshes convex hull or not
"""
# facets plane, origin and normal
normals = self.facets_norm... | def function[facets_on_hull, parameter[self]]:
constant[
Find which facets of the mesh are on the convex hull.
Returns
---------
on_hull : (len(mesh.facets),) bool
is A facet on the meshes convex hull or not
]
variable[normals] assign[=] name[self].face... | keyword[def] identifier[facets_on_hull] ( identifier[self] ):
literal[string]
identifier[normals] = identifier[self] . identifier[facets_normal]
identifier[origins] = identifier[self] . identifier[facets_origin]
identifier[convex] = identifier[self] . identifi... | def facets_on_hull(self):
"""
Find which facets of the mesh are on the convex hull.
Returns
---------
on_hull : (len(mesh.facets),) bool
is A facet on the meshes convex hull or not
"""
# facets plane, origin and normal
normals = self.facets_normal
origi... |
def vis_detection(im_orig, detections, class_names, thresh=0.7):
"""visualize [cls, conf, x1, y1, x2, y2]"""
import matplotlib.pyplot as plt
import random
plt.imshow(im_orig)
colors = [(random.random(), random.random(), random.random()) for _ in class_names]
for [cls, conf, x1, y1, x2, y2] in de... | def function[vis_detection, parameter[im_orig, detections, class_names, thresh]]:
constant[visualize [cls, conf, x1, y1, x2, y2]]
import module[matplotlib.pyplot] as alias[plt]
import module[random]
call[name[plt].imshow, parameter[name[im_orig]]]
variable[colors] assign[=] <ast.ListComp... | keyword[def] identifier[vis_detection] ( identifier[im_orig] , identifier[detections] , identifier[class_names] , identifier[thresh] = literal[int] ):
literal[string]
keyword[import] identifier[matplotlib] . identifier[pyplot] keyword[as] identifier[plt]
keyword[import] identifier[random]
i... | def vis_detection(im_orig, detections, class_names, thresh=0.7):
"""visualize [cls, conf, x1, y1, x2, y2]"""
import matplotlib.pyplot as plt
import random
plt.imshow(im_orig)
colors = [(random.random(), random.random(), random.random()) for _ in class_names]
for [cls, conf, x1, y1, x2, y2] in de... |
def getElementsByName(self, name):
""" get element with given name,
return list of element objects regarding to 'name'
:param name: element name, case sensitive, if elements are
auto-generated from LteParser, the name should be lower cased.
"""
try:
... | def function[getElementsByName, parameter[self, name]]:
constant[ get element with given name,
return list of element objects regarding to 'name'
:param name: element name, case sensitive, if elements are
auto-generated from LteParser, the name should be lower cased.
... | keyword[def] identifier[getElementsByName] ( identifier[self] , identifier[name] ):
literal[string]
keyword[try] :
keyword[return] identifier[filter] ( keyword[lambda] identifier[x] : identifier[x] . identifier[name] == identifier[name] , identifier[self] . identifier[_lattice_eleobj... | def getElementsByName(self, name):
""" get element with given name,
return list of element objects regarding to 'name'
:param name: element name, case sensitive, if elements are
auto-generated from LteParser, the name should be lower cased.
"""
try:
retur... |
def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None):
"""
Check if database contains any tables.
:param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument
is a boolean flag specifying if t... | def function[_checkIfDatabaseIsEmpty, parameter[self, successHandler, failHandler]]:
constant[
Check if database contains any tables.
:param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument
is a boolean fla... | keyword[def] identifier[_checkIfDatabaseIsEmpty] ( identifier[self] , identifier[successHandler] = keyword[None] , identifier[failHandler] = keyword[None] ):
literal[string]
keyword[def] identifier[failCallback] ( identifier[error] ):
identifier[errorMessage] = identifier[str] ( ident... | def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None):
"""
Check if database contains any tables.
:param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument
is a boolean flag specifying if the d... |
def createSomeItems(store, itemType, values, counter):
"""
Create some instances of a particular type in a store.
"""
for i in counter:
itemType(store=store, **values) | def function[createSomeItems, parameter[store, itemType, values, counter]]:
constant[
Create some instances of a particular type in a store.
]
for taget[name[i]] in starred[name[counter]] begin[:]
call[name[itemType], parameter[]] | keyword[def] identifier[createSomeItems] ( identifier[store] , identifier[itemType] , identifier[values] , identifier[counter] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[counter] :
identifier[itemType] ( identifier[store] = identifier[store] ,** identifier[values] ) | def createSomeItems(store, itemType, values, counter):
"""
Create some instances of a particular type in a store.
"""
for i in counter:
itemType(store=store, **values) # depends on [control=['for'], data=[]] |
def send_confirm_email_email(self, user, user_email):
"""Send the 'email confirmation' email."""
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL: return
if not self.user_manager.USER_ENABLE_CONFIRM_EMAIL: return
# The confirm_email email is sent to a... | def function[send_confirm_email_email, parameter[self, user, user_email]]:
constant[Send the 'email confirmation' email.]
if <ast.UnaryOp object at 0x7da18bc70850> begin[:]
return[None]
if <ast.UnaryOp object at 0x7da18bc70bb0> begin[:]
return[None]
variable[email] assign... | keyword[def] identifier[send_confirm_email_email] ( identifier[self] , identifier[user] , identifier[user_email] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[user_manager] . identifier[USER_ENABLE_EMAIL] : keyword[return]
keyword[if] keyword[not] ... | def send_confirm_email_email(self, user, user_email):
"""Send the 'email confirmation' email."""
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL:
return # depends on [control=['if'], data=[]]
if not self.user_manager.USER_ENABLE_CONFIRM_EMAIL:
return # depends on [c... |
def formula_1980(household, period, parameters):
'''
To compute this allowance, the 'rent' value must be provided for the same month, but 'housing_occupancy_status' is not necessary.
'''
return household('rent', period) * parameters(period).benefits.housing_allowance | def function[formula_1980, parameter[household, period, parameters]]:
constant[
To compute this allowance, the 'rent' value must be provided for the same month, but 'housing_occupancy_status' is not necessary.
]
return[binary_operation[call[name[household], parameter[constant[rent], name[per... | keyword[def] identifier[formula_1980] ( identifier[household] , identifier[period] , identifier[parameters] ):
literal[string]
keyword[return] identifier[household] ( literal[string] , identifier[period] )* identifier[parameters] ( identifier[period] ). identifier[benefits] . identifier[housing_al... | def formula_1980(household, period, parameters):
"""
To compute this allowance, the 'rent' value must be provided for the same month, but 'housing_occupancy_status' is not necessary.
"""
return household('rent', period) * parameters(period).benefits.housing_allowance |
def create_payload(self):
"""Remove ``smart_class_parameter_id`` or ``smart_variable_id``"""
payload = super(OverrideValue, self).create_payload()
if hasattr(self, 'smart_class_parameter'):
del payload['smart_class_parameter_id']
if hasattr(self, 'smart_variable'):
... | def function[create_payload, parameter[self]]:
constant[Remove ``smart_class_parameter_id`` or ``smart_variable_id``]
variable[payload] assign[=] call[call[name[super], parameter[name[OverrideValue], name[self]]].create_payload, parameter[]]
if call[name[hasattr], parameter[name[self], constant[... | keyword[def] identifier[create_payload] ( identifier[self] ):
literal[string]
identifier[payload] = identifier[super] ( identifier[OverrideValue] , identifier[self] ). identifier[create_payload] ()
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
keywor... | def create_payload(self):
"""Remove ``smart_class_parameter_id`` or ``smart_variable_id``"""
payload = super(OverrideValue, self).create_payload()
if hasattr(self, 'smart_class_parameter'):
del payload['smart_class_parameter_id'] # depends on [control=['if'], data=[]]
if hasattr(self, 'smart_va... |
def polygonize(self, width, cap_style_line=CAP_STYLE.flat, cap_style_point=CAP_STYLE.round):
"""Turns line or point into a buffered polygon."""
shape = self._shape
if isinstance(shape, (LineString, MultiLineString)):
return self.__class__(
shape.buffer(width / 2, cap_... | def function[polygonize, parameter[self, width, cap_style_line, cap_style_point]]:
constant[Turns line or point into a buffered polygon.]
variable[shape] assign[=] name[self]._shape
if call[name[isinstance], parameter[name[shape], tuple[[<ast.Name object at 0x7da2054a4e80>, <ast.Name object at 0... | keyword[def] identifier[polygonize] ( identifier[self] , identifier[width] , identifier[cap_style_line] = identifier[CAP_STYLE] . identifier[flat] , identifier[cap_style_point] = identifier[CAP_STYLE] . identifier[round] ):
literal[string]
identifier[shape] = identifier[self] . identifier[_shape]
... | def polygonize(self, width, cap_style_line=CAP_STYLE.flat, cap_style_point=CAP_STYLE.round):
"""Turns line or point into a buffered polygon."""
shape = self._shape
if isinstance(shape, (LineString, MultiLineString)):
return self.__class__(shape.buffer(width / 2, cap_style=cap_style_line), self.crs) ... |
def signed_session(self, session=None):
"""
Sign requests session with the token. This method is called every time a request is going on the wire.
The user is responsible for updating the token with the preferred tool/SDK.
In general there are two options:
- override this met... | def function[signed_session, parameter[self, session]]:
constant[
Sign requests session with the token. This method is called every time a request is going on the wire.
The user is responsible for updating the token with the preferred tool/SDK.
In general there are two options:
... | keyword[def] identifier[signed_session] ( identifier[self] , identifier[session] = keyword[None] ):
literal[string]
identifier[session] = identifier[session] keyword[or] identifier[requests] . identifier[Session] ()
identifier[session] . identifier[headers] [ literal[string] ]= literal[s... | def signed_session(self, session=None):
"""
Sign requests session with the token. This method is called every time a request is going on the wire.
The user is responsible for updating the token with the preferred tool/SDK.
In general there are two options:
- override this method ... |
def new_fully_connected(self, name: str, output_count: int, relu=True, input_layer_name: str=None):
"""
Creates a new fully connected layer.
:param name: name for the layer.
:param output_count: number of outputs of the fully connected layer.
:param relu: boolean flag to set if ... | def function[new_fully_connected, parameter[self, name, output_count, relu, input_layer_name]]:
constant[
Creates a new fully connected layer.
:param name: name for the layer.
:param output_count: number of outputs of the fully connected layer.
:param relu: boolean flag to set i... | keyword[def] identifier[new_fully_connected] ( identifier[self] , identifier[name] : identifier[str] , identifier[output_count] : identifier[int] , identifier[relu] = keyword[True] , identifier[input_layer_name] : identifier[str] = keyword[None] ):
literal[string]
keyword[with] identifier[tf] . i... | def new_fully_connected(self, name: str, output_count: int, relu=True, input_layer_name: str=None):
"""
Creates a new fully connected layer.
:param name: name for the layer.
:param output_count: number of outputs of the fully connected layer.
:param relu: boolean flag to set if ReLu... |
def inet_pton(af, addr):
"""Convert an IP address from text representation into binary form."""
# Will replace Net/Net6 objects
addr = plain_str(addr)
# Use inet_pton if available
try:
return socket.inet_pton(af, addr)
except AttributeError:
try:
return _INET_PTON[af]... | def function[inet_pton, parameter[af, addr]]:
constant[Convert an IP address from text representation into binary form.]
variable[addr] assign[=] call[name[plain_str], parameter[name[addr]]]
<ast.Try object at 0x7da1b1c19ea0> | keyword[def] identifier[inet_pton] ( identifier[af] , identifier[addr] ):
literal[string]
identifier[addr] = identifier[plain_str] ( identifier[addr] )
keyword[try] :
keyword[return] identifier[socket] . identifier[inet_pton] ( identifier[af] , identifier[addr] )
keyword[excep... | def inet_pton(af, addr):
"""Convert an IP address from text representation into binary form."""
# Will replace Net/Net6 objects
addr = plain_str(addr)
# Use inet_pton if available
try:
return socket.inet_pton(af, addr) # depends on [control=['try'], data=[]]
except AttributeError:
... |
def get_encoded_text(container, xpath):
"""Return text for element at xpath in the container xml if it is there.
Parameters
----------
container : xml.etree.ElementTree.Element
The element to be searched in.
xpath : str
The path to be looked for.
Returns
-------
result... | def function[get_encoded_text, parameter[container, xpath]]:
constant[Return text for element at xpath in the container xml if it is there.
Parameters
----------
container : xml.etree.ElementTree.Element
The element to be searched in.
xpath : str
The path to be looked for.
... | keyword[def] identifier[get_encoded_text] ( identifier[container] , identifier[xpath] ):
literal[string]
keyword[try] :
keyword[return] literal[string] . identifier[join] ( identifier[container] . identifier[find] ( identifier[xpath] , identifier[ns] ). identifier[itertext] ())
keyword[excep... | def get_encoded_text(container, xpath):
"""Return text for element at xpath in the container xml if it is there.
Parameters
----------
container : xml.etree.ElementTree.Element
The element to be searched in.
xpath : str
The path to be looked for.
Returns
-------
result... |
def waitForAllConnectionsToClose(self):
"""
Wait for all currently-open connections to enter the 'CLOSED' state.
Currently this is only usable from test fixtures.
"""
if not self._connections:
return self._stop()
return self._allConnectionsClosed.deferred().ad... | def function[waitForAllConnectionsToClose, parameter[self]]:
constant[
Wait for all currently-open connections to enter the 'CLOSED' state.
Currently this is only usable from test fixtures.
]
if <ast.UnaryOp object at 0x7da2047e8cd0> begin[:]
return[call[name[self]._stop,... | keyword[def] identifier[waitForAllConnectionsToClose] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_connections] :
keyword[return] identifier[self] . identifier[_stop] ()
keyword[return] identifier[self] . identifier[_allConn... | def waitForAllConnectionsToClose(self):
"""
Wait for all currently-open connections to enter the 'CLOSED' state.
Currently this is only usable from test fixtures.
"""
if not self._connections:
return self._stop() # depends on [control=['if'], data=[]]
return self._allConnect... |
def acl_middleware(callback):
"""Returns a aiohttp_auth.acl middleware factory for use by the aiohttp
application object.
Args:
callback: This is a callable which takes a user_id (as returned from
the auth.get_auth function), and expects a sequence of permitted ACL
groups to... | def function[acl_middleware, parameter[callback]]:
constant[Returns a aiohttp_auth.acl middleware factory for use by the aiohttp
application object.
Args:
callback: This is a callable which takes a user_id (as returned from
the auth.get_auth function), and expects a sequence of perm... | keyword[def] identifier[acl_middleware] ( identifier[callback] ):
literal[string]
keyword[async] keyword[def] identifier[_acl_middleware_factory] ( identifier[app] , identifier[handler] ):
keyword[async] keyword[def] identifier[_middleware_handler] ( identifier[request] ):
... | def acl_middleware(callback):
"""Returns a aiohttp_auth.acl middleware factory for use by the aiohttp
application object.
Args:
callback: This is a callable which takes a user_id (as returned from
the auth.get_auth function), and expects a sequence of permitted ACL
groups to... |
def ExpandRecursiveGlobs(cls, path, path_separator):
"""Expands recursive like globs present in an artifact path.
If a path ends in '**', with up to two optional digits such as '**10',
the '**' will recursively match all files and zero or more directories
from the specified path. The optional digits in... | def function[ExpandRecursiveGlobs, parameter[cls, path, path_separator]]:
constant[Expands recursive like globs present in an artifact path.
If a path ends in '**', with up to two optional digits such as '**10',
the '**' will recursively match all files and zero or more directories
from the specifi... | keyword[def] identifier[ExpandRecursiveGlobs] ( identifier[cls] , identifier[path] , identifier[path_separator] ):
literal[string]
identifier[glob_regex] = literal[string] . identifier[format] (
identifier[re] . identifier[escape] ( identifier[path_separator] ))
identifier[match] = identifier[re... | def ExpandRecursiveGlobs(cls, path, path_separator):
"""Expands recursive like globs present in an artifact path.
If a path ends in '**', with up to two optional digits such as '**10',
the '**' will recursively match all files and zero or more directories
from the specified path. The optional digits in... |
def removeNotification(self, notificationId):
"""Destroy a notification, hiding it first if it currently shown to the user."""
fn = self.function_table.removeNotification
result = fn(notificationId)
return result | def function[removeNotification, parameter[self, notificationId]]:
constant[Destroy a notification, hiding it first if it currently shown to the user.]
variable[fn] assign[=] name[self].function_table.removeNotification
variable[result] assign[=] call[name[fn], parameter[name[notificationId]]]
... | keyword[def] identifier[removeNotification] ( identifier[self] , identifier[notificationId] ):
literal[string]
identifier[fn] = identifier[self] . identifier[function_table] . identifier[removeNotification]
identifier[result] = identifier[fn] ( identifier[notificationId] )
keywo... | def removeNotification(self, notificationId):
"""Destroy a notification, hiding it first if it currently shown to the user."""
fn = self.function_table.removeNotification
result = fn(notificationId)
return result |
def pcre(tgt, minion_id=None):
'''
Return True if the minion ID matches the given pcre target
minion_id
Specify the minion ID to match against the target expression
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.pcre '.*'
'''
if minio... | def function[pcre, parameter[tgt, minion_id]]:
constant[
Return True if the minion ID matches the given pcre target
minion_id
Specify the minion ID to match against the target expression
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.pcre... | keyword[def] identifier[pcre] ( identifier[tgt] , identifier[minion_id] = keyword[None] ):
literal[string]
keyword[if] identifier[minion_id] keyword[is] keyword[not] keyword[None] :
identifier[opts] = identifier[copy] . identifier[copy] ( identifier[__opts__] )
keyword[if] keyword[no... | def pcre(tgt, minion_id=None):
"""
Return True if the minion ID matches the given pcre target
minion_id
Specify the minion ID to match against the target expression
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.pcre '.*'
"""
if minio... |
def delete(name, timeout=90):
'''
Delete the named service
Args:
name (str): The name of the service to delete
timeout (int):
The time in seconds to wait for the service to be deleted before
returning. This is necessary because a service must be stopped
... | def function[delete, parameter[name, timeout]]:
constant[
Delete the named service
Args:
name (str): The name of the service to delete
timeout (int):
The time in seconds to wait for the service to be deleted before
returning. This is necessary because a service... | keyword[def] identifier[delete] ( identifier[name] , identifier[timeout] = literal[int] ):
literal[string]
identifier[handle_scm] = identifier[win32service] . identifier[OpenSCManager] (
keyword[None] , keyword[None] , identifier[win32service] . identifier[SC_MANAGER_CONNECT] )
keyword[try] :
... | def delete(name, timeout=90):
"""
Delete the named service
Args:
name (str): The name of the service to delete
timeout (int):
The time in seconds to wait for the service to be deleted before
returning. This is necessary because a service must be stopped
... |
def get_training_status(self, model_id, token=None, url=API_TRAIN_MODEL):
""" Gets status on the training process once you create a model
:param model_id: string, id of the model to check
returns: requests object
"""
auth = 'Bearer ' + self.check_for_token(token)
... | def function[get_training_status, parameter[self, model_id, token, url]]:
constant[ Gets status on the training process once you create a model
:param model_id: string, id of the model to check
returns: requests object
]
variable[auth] assign[=] binary_operation[constant[... | keyword[def] identifier[get_training_status] ( identifier[self] , identifier[model_id] , identifier[token] = keyword[None] , identifier[url] = identifier[API_TRAIN_MODEL] ):
literal[string]
identifier[auth] = literal[string] + identifier[self] . identifier[check_for_token] ( identifier[token] )
... | def get_training_status(self, model_id, token=None, url=API_TRAIN_MODEL):
""" Gets status on the training process once you create a model
:param model_id: string, id of the model to check
returns: requests object
"""
auth = 'Bearer ' + self.check_for_token(token)
h = {'Author... |
def consume(self, queue, consumer, consumer_tag='', no_local=False,
no_ack=True, exclusive=False, nowait=True, ticket=None,
cb=None):
'''
Start a queue consumer. If `cb` is supplied, will be called when
broker confirms that consumer is registered.
'''
... | def function[consume, parameter[self, queue, consumer, consumer_tag, no_local, no_ack, exclusive, nowait, ticket, cb]]:
constant[
Start a queue consumer. If `cb` is supplied, will be called when
broker confirms that consumer is registered.
]
variable[nowait] assign[=] <ast.BoolOp... | keyword[def] identifier[consume] ( identifier[self] , identifier[queue] , identifier[consumer] , identifier[consumer_tag] = literal[string] , identifier[no_local] = keyword[False] ,
identifier[no_ack] = keyword[True] , identifier[exclusive] = keyword[False] , identifier[nowait] = keyword[True] , identifier[ticket] =... | def consume(self, queue, consumer, consumer_tag='', no_local=False, no_ack=True, exclusive=False, nowait=True, ticket=None, cb=None):
"""
Start a queue consumer. If `cb` is supplied, will be called when
broker confirms that consumer is registered.
"""
nowait = nowait and self.allow_nowai... |
def _representable(value: Any) -> bool:
"""
Check whether we want to represent the value in the error message on contract breach.
We do not want to represent classes, methods, modules and functions.
:param value: value related to an AST node
:return: True if we want to represent it in the violatio... | def function[_representable, parameter[value]]:
constant[
Check whether we want to represent the value in the error message on contract breach.
We do not want to represent classes, methods, modules and functions.
:param value: value related to an AST node
:return: True if we want to represent ... | keyword[def] identifier[_representable] ( identifier[value] : identifier[Any] )-> identifier[bool] :
literal[string]
keyword[return] keyword[not] identifier[inspect] . identifier[isclass] ( identifier[value] ) keyword[and] keyword[not] identifier[inspect] . identifier[isfunction] ( identifier[value] ) ... | def _representable(value: Any) -> bool:
"""
Check whether we want to represent the value in the error message on contract breach.
We do not want to represent classes, methods, modules and functions.
:param value: value related to an AST node
:return: True if we want to represent it in the violatio... |
def to_definition(self):
"""
Converts the name instance to a pyqode.core.share.Definition
"""
icon = {
Name.Type.Root: icons.ICON_MIMETYPE,
Name.Type.Division: icons.ICON_DIVISION,
Name.Type.Section: icons.ICON_SECTION,
Name.Type.Variable: ... | def function[to_definition, parameter[self]]:
constant[
Converts the name instance to a pyqode.core.share.Definition
]
variable[icon] assign[=] call[dictionary[[<ast.Attribute object at 0x7da18dc06680>, <ast.Attribute object at 0x7da18dc078b0>, <ast.Attribute object at 0x7da18dc07f40>, <... | keyword[def] identifier[to_definition] ( identifier[self] ):
literal[string]
identifier[icon] ={
identifier[Name] . identifier[Type] . identifier[Root] : identifier[icons] . identifier[ICON_MIMETYPE] ,
identifier[Name] . identifier[Type] . identifier[Division] : identifier[icons] ... | def to_definition(self):
"""
Converts the name instance to a pyqode.core.share.Definition
"""
icon = {Name.Type.Root: icons.ICON_MIMETYPE, Name.Type.Division: icons.ICON_DIVISION, Name.Type.Section: icons.ICON_SECTION, Name.Type.Variable: icons.ICON_VAR, Name.Type.Paragraph: icons.ICON_FUNC}[sel... |
def save_element_as_image_file(self, selector, file_name, folder=None):
""" Take a screenshot of an element and save it as an image file.
If no folder is specified, will save it to the current folder. """
element = self.find_element(selector)
element_png = element.screenshot_as_png
... | def function[save_element_as_image_file, parameter[self, selector, file_name, folder]]:
constant[ Take a screenshot of an element and save it as an image file.
If no folder is specified, will save it to the current folder. ]
variable[element] assign[=] call[name[self].find_element, parameter... | keyword[def] identifier[save_element_as_image_file] ( identifier[self] , identifier[selector] , identifier[file_name] , identifier[folder] = keyword[None] ):
literal[string]
identifier[element] = identifier[self] . identifier[find_element] ( identifier[selector] )
identifier[element_png] =... | def save_element_as_image_file(self, selector, file_name, folder=None):
""" Take a screenshot of an element and save it as an image file.
If no folder is specified, will save it to the current folder. """
element = self.find_element(selector)
element_png = element.screenshot_as_png
if len(fi... |
def validate_int(value):
""" Integer validator """
if value and not isinstance(value, int):
try:
int(str(value))
except (TypeError, ValueError):
raise ValidationError('not a valid number')
return value | def function[validate_int, parameter[value]]:
constant[ Integer validator ]
if <ast.BoolOp object at 0x7da20c76eda0> begin[:]
<ast.Try object at 0x7da20c76d9f0>
return[name[value]] | keyword[def] identifier[validate_int] ( identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[and] keyword[not] identifier[isinstance] ( identifier[value] , identifier[int] ):
keyword[try] :
identifier[int] ( identifier[str] ( identifier[value] ))
ke... | def validate_int(value):
""" Integer validator """
if value and (not isinstance(value, int)):
try:
int(str(value)) # depends on [control=['try'], data=[]]
except (TypeError, ValueError):
raise ValidationError('not a valid number') # depends on [control=['except'], data=... |
def get_paragraph(self):
"""
Write a paragraph
of 5 sentences.
"""
self.text = ''
for x in range(randint(5, 12)):
sentence = self._write_sentence()
self.text = self.text + sentence
return self.text | def function[get_paragraph, parameter[self]]:
constant[
Write a paragraph
of 5 sentences.
]
name[self].text assign[=] constant[]
for taget[name[x]] in starred[call[name[range], parameter[call[name[randint], parameter[constant[5], constant[12]]]]]] begin[:]
... | keyword[def] identifier[get_paragraph] ( identifier[self] ):
literal[string]
identifier[self] . identifier[text] = literal[string]
keyword[for] identifier[x] keyword[in] identifier[range] ( identifier[randint] ( literal[int] , literal[int] )):
identifier[sentence] = identi... | def get_paragraph(self):
"""
Write a paragraph
of 5 sentences.
"""
self.text = ''
for x in range(randint(5, 12)):
sentence = self._write_sentence()
self.text = self.text + sentence # depends on [control=['for'], data=[]]
return self.text |
def set_bucket_type_props(self, transport, bucket_type, props):
"""
set_bucket_type_props(bucket_type, props)
Sets properties for the given bucket-type.
.. note:: This request is automatically retried :attr:`retries`
times if it fails due to network error.
:param bu... | def function[set_bucket_type_props, parameter[self, transport, bucket_type, props]]:
constant[
set_bucket_type_props(bucket_type, props)
Sets properties for the given bucket-type.
.. note:: This request is automatically retried :attr:`retries`
times if it fails due to networ... | keyword[def] identifier[set_bucket_type_props] ( identifier[self] , identifier[transport] , identifier[bucket_type] , identifier[props] ):
literal[string]
identifier[_validate_bucket_props] ( identifier[props] )
keyword[return] identifier[transport] . identifier[set_bucket_type_props] ( i... | def set_bucket_type_props(self, transport, bucket_type, props):
"""
set_bucket_type_props(bucket_type, props)
Sets properties for the given bucket-type.
.. note:: This request is automatically retried :attr:`retries`
times if it fails due to network error.
:param bucket... |
def legend_scaler(legend_values, max_labels=10.0):
"""
Downsamples the number of legend values so that there isn't a collision
of text on the legend colorbar (within reason). The colorbar seems to
support ~10 entries as a maximum.
"""
if len(legend_values) < max_labels:
legend_ticks = l... | def function[legend_scaler, parameter[legend_values, max_labels]]:
constant[
Downsamples the number of legend values so that there isn't a collision
of text on the legend colorbar (within reason). The colorbar seems to
support ~10 entries as a maximum.
]
if compare[call[name[len], param... | keyword[def] identifier[legend_scaler] ( identifier[legend_values] , identifier[max_labels] = literal[int] ):
literal[string]
keyword[if] identifier[len] ( identifier[legend_values] )< identifier[max_labels] :
identifier[legend_ticks] = identifier[legend_values]
keyword[else] :
ide... | def legend_scaler(legend_values, max_labels=10.0):
"""
Downsamples the number of legend values so that there isn't a collision
of text on the legend colorbar (within reason). The colorbar seems to
support ~10 entries as a maximum.
"""
if len(legend_values) < max_labels:
legend_ticks = l... |
def register_on_snapshot_deleted(self, callback):
"""Set the callback function to consume on snapshot deleted events.
Callback receives a ISnapshotDeletedEvent object.
Returns the callback_id
"""
event_type = library.VBoxEventType.on_snapshot_deleted
return self.event_s... | def function[register_on_snapshot_deleted, parameter[self, callback]]:
constant[Set the callback function to consume on snapshot deleted events.
Callback receives a ISnapshotDeletedEvent object.
Returns the callback_id
]
variable[event_type] assign[=] name[library].VBoxEventTyp... | keyword[def] identifier[register_on_snapshot_deleted] ( identifier[self] , identifier[callback] ):
literal[string]
identifier[event_type] = identifier[library] . identifier[VBoxEventType] . identifier[on_snapshot_deleted]
keyword[return] identifier[self] . identifier[event_source] . iden... | def register_on_snapshot_deleted(self, callback):
"""Set the callback function to consume on snapshot deleted events.
Callback receives a ISnapshotDeletedEvent object.
Returns the callback_id
"""
event_type = library.VBoxEventType.on_snapshot_deleted
return self.event_source.regist... |
def get_field_description(f):
"""Get the type description of a GRPC Message field."""
type_name = get_field_type(f)
if type_name == 'MESSAGE' and \
{sf.name for sf in f.message_type.fields} == {'key', 'value'}:
return 'map<string, string>'
elif type_name == 'MESSAGE':
return ... | def function[get_field_description, parameter[f]]:
constant[Get the type description of a GRPC Message field.]
variable[type_name] assign[=] call[name[get_field_type], parameter[name[f]]]
if <ast.BoolOp object at 0x7da1b191e1a0> begin[:]
return[constant[map<string, string>]] | keyword[def] identifier[get_field_description] ( identifier[f] ):
literal[string]
identifier[type_name] = identifier[get_field_type] ( identifier[f] )
keyword[if] identifier[type_name] == literal[string] keyword[and] { identifier[sf] . identifier[name] keyword[for] identifier[sf] keyword[in] ide... | def get_field_description(f):
"""Get the type description of a GRPC Message field."""
type_name = get_field_type(f)
if type_name == 'MESSAGE' and {sf.name for sf in f.message_type.fields} == {'key', 'value'}:
return 'map<string, string>' # depends on [control=['if'], data=[]]
elif type_name == ... |
def _run_parallel_multiprocess(self):
"""Run processes from queue
"""
_log.debug("run.parallel.multiprocess.start")
processes = []
ProcRunner.instance = self
for i in range(self._ncores):
self._status.running(i)
proc = multiprocessing.Process(targe... | def function[_run_parallel_multiprocess, parameter[self]]:
constant[Run processes from queue
]
call[name[_log].debug, parameter[constant[run.parallel.multiprocess.start]]]
variable[processes] assign[=] list[[]]
name[ProcRunner].instance assign[=] name[self]
for taget[name... | keyword[def] identifier[_run_parallel_multiprocess] ( identifier[self] ):
literal[string]
identifier[_log] . identifier[debug] ( literal[string] )
identifier[processes] =[]
identifier[ProcRunner] . identifier[instance] = identifier[self]
keyword[for] identifier[i] keyw... | def _run_parallel_multiprocess(self):
"""Run processes from queue
"""
_log.debug('run.parallel.multiprocess.start')
processes = []
ProcRunner.instance = self
for i in range(self._ncores):
self._status.running(i)
proc = multiprocessing.Process(target=ProcRunner.run, args=(i,))... |
def describe_formatted(self, name, database=None):
"""
Retrieve results of DESCRIBE FORMATTED command. See Impala
documentation for more.
Parameters
----------
name : string
Table name. Can be fully qualified (with database)
database : string, optional
... | def function[describe_formatted, parameter[self, name, database]]:
constant[
Retrieve results of DESCRIBE FORMATTED command. See Impala
documentation for more.
Parameters
----------
name : string
Table name. Can be fully qualified (with database)
databa... | keyword[def] identifier[describe_formatted] ( identifier[self] , identifier[name] , identifier[database] = keyword[None] ):
literal[string]
keyword[from] identifier[ibis] . identifier[impala] . identifier[metadata] keyword[import] identifier[parse_metadata]
identifier[stmt] = identifi... | def describe_formatted(self, name, database=None):
"""
Retrieve results of DESCRIBE FORMATTED command. See Impala
documentation for more.
Parameters
----------
name : string
Table name. Can be fully qualified (with database)
database : string, optional
... |
def contourf_to_geojson_overlap(contourf, geojson_filepath=None, min_angle_deg=None,
ndigits=5, unit='', stroke_width=1, fill_opacity=.9,
geojson_properties=None, strdump=False, serialize=True):
"""Transform matplotlib.contourf to geojson with overlapp... | def function[contourf_to_geojson_overlap, parameter[contourf, geojson_filepath, min_angle_deg, ndigits, unit, stroke_width, fill_opacity, geojson_properties, strdump, serialize]]:
constant[Transform matplotlib.contourf to geojson with overlapping filled contours.]
variable[polygon_features] assign[=] li... | keyword[def] identifier[contourf_to_geojson_overlap] ( identifier[contourf] , identifier[geojson_filepath] = keyword[None] , identifier[min_angle_deg] = keyword[None] ,
identifier[ndigits] = literal[int] , identifier[unit] = literal[string] , identifier[stroke_width] = literal[int] , identifier[fill_opacity] = liter... | def contourf_to_geojson_overlap(contourf, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit='', stroke_width=1, fill_opacity=0.9, geojson_properties=None, strdump=False, serialize=True):
"""Transform matplotlib.contourf to geojson with overlapping filled contours."""
polygon_features = []
contourf_... |
def get_all():
'''
Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' s6.get_all
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
service_list = [dirname for dirname
in os.l... | def function[get_all, parameter[]]:
constant[
Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' s6.get_all
]
if <ast.UnaryOp object at 0x7da20c6c5ea0> begin[:]
<ast.Raise object at 0x7da20c6c4e80>
variable[service_list] assign[=... | keyword[def] identifier[get_all] ():
literal[string]
keyword[if] keyword[not] identifier[SERVICE_DIR] :
keyword[raise] identifier[CommandExecutionError] ( literal[string] )
identifier[service_list] =[ identifier[dirname] keyword[for] identifier[dirname]
keyword[in] identifier[os] ... | def get_all():
"""
Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' s6.get_all
"""
if not SERVICE_DIR:
raise CommandExecutionError('Could not find service directory.') # depends on [control=['if'], data=[]]
service_list = [dirname for dir... |
def read(self, subpath=None):
"""
Returns the UTF-8 content of the specified subpath.
subpath is expected to already have been normalized.
Raises ReadmeNotFoundError if a README for the specified subpath
does not exist.
Raises werkzeug.exceptions.NotFound if the result... | def function[read, parameter[self, subpath]]:
constant[
Returns the UTF-8 content of the specified subpath.
subpath is expected to already have been normalized.
Raises ReadmeNotFoundError if a README for the specified subpath
does not exist.
Raises werkzeug.exceptions.... | keyword[def] identifier[read] ( identifier[self] , identifier[subpath] = keyword[None] ):
literal[string]
identifier[is_binary] = identifier[self] . identifier[is_binary] ( identifier[subpath] )
identifier[filename] = identifier[self] . identifier[readme_for] ( identifier[subpath] )
... | def read(self, subpath=None):
"""
Returns the UTF-8 content of the specified subpath.
subpath is expected to already have been normalized.
Raises ReadmeNotFoundError if a README for the specified subpath
does not exist.
Raises werkzeug.exceptions.NotFound if the resulting ... |
def absent(name, persist=False, comment=True, mods=None):
'''
Verify that the named kernel module is not loaded
name
The name of the kernel module to verify is not loaded
persist
Remove module from ``/etc/modules``
comment
Comment out module in ``/etc/modules`` rather than... | def function[absent, parameter[name, persist, comment, mods]]:
constant[
Verify that the named kernel module is not loaded
name
The name of the kernel module to verify is not loaded
persist
Remove module from ``/etc/modules``
comment
Comment out module in ``/etc/module... | keyword[def] identifier[absent] ( identifier[name] , identifier[persist] = keyword[False] , identifier[comment] = keyword[True] , identifier[mods] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[mods] ,( identifier[list] , identifier[tuple] )):
ide... | def absent(name, persist=False, comment=True, mods=None):
"""
Verify that the named kernel module is not loaded
name
The name of the kernel module to verify is not loaded
persist
Remove module from ``/etc/modules``
comment
Comment out module in ``/etc/modules`` rather than... |
def query(self, **kwargs):
"""
Query the data source, subselecting data. Available keyword arguments
include
- model
- scenario
- region
- variable
Example
-------
```
Connection.query(model='MESSAGE', scenario='SSP2*',
... | def function[query, parameter[self]]:
constant[
Query the data source, subselecting data. Available keyword arguments
include
- model
- scenario
- region
- variable
Example
-------
```
Connection.query(model='MESSAGE', scenario='... | keyword[def] identifier[query] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[headers] ={
literal[string] : literal[string] . identifier[format] ( identifier[self] . identifier[auth] ()),
literal[string] : literal[string] ,
}
identifier[da... | def query(self, **kwargs):
"""
Query the data source, subselecting data. Available keyword arguments
include
- model
- scenario
- region
- variable
Example
-------
```
Connection.query(model='MESSAGE', scenario='SSP2*',
... |
def extract_common_fields(self, data):
"""Extract fields from a basic user query."""
email = None
for curr_email in data.get("emails", []):
email = email or curr_email.get("email")
if curr_email.get("verified", False) and \
curr_email.get("primary", Fa... | def function[extract_common_fields, parameter[self, data]]:
constant[Extract fields from a basic user query.]
variable[email] assign[=] constant[None]
for taget[name[curr_email]] in starred[call[name[data].get, parameter[constant[emails], list[[]]]]] begin[:]
variable[email] assi... | keyword[def] identifier[extract_common_fields] ( identifier[self] , identifier[data] ):
literal[string]
identifier[email] = keyword[None]
keyword[for] identifier[curr_email] keyword[in] identifier[data] . identifier[get] ( literal[string] ,[]):
identifier[email] = identifi... | def extract_common_fields(self, data):
"""Extract fields from a basic user query."""
email = None
for curr_email in data.get('emails', []):
email = email or curr_email.get('email')
if curr_email.get('verified', False) and curr_email.get('primary', False):
email = curr_email.get('... |
def cmd_string(name, cmd):
# type: (AName, ACmd) -> ADefine
"""Define a string parameter coming from a shell command to be used within
this YAML file. Trailing newlines will be stripped."""
value = subprocess.check_output(cmd, shell=True).rstrip("\n")
return Define(name, value) | def function[cmd_string, parameter[name, cmd]]:
constant[Define a string parameter coming from a shell command to be used within
this YAML file. Trailing newlines will be stripped.]
variable[value] assign[=] call[call[name[subprocess].check_output, parameter[name[cmd]]].rstrip, parameter[constant[
]... | keyword[def] identifier[cmd_string] ( identifier[name] , identifier[cmd] ):
literal[string]
identifier[value] = identifier[subprocess] . identifier[check_output] ( identifier[cmd] , identifier[shell] = keyword[True] ). identifier[rstrip] ( literal[string] )
keyword[return] identifier[Define] ( ident... | def cmd_string(name, cmd):
# type: (AName, ACmd) -> ADefine
'Define a string parameter coming from a shell command to be used within\n this YAML file. Trailing newlines will be stripped.'
value = subprocess.check_output(cmd, shell=True).rstrip('\n')
return Define(name, value) |
def py2round(value):
"""Round values as in Python 2, for Python 3 compatibility.
All x.5 values are rounded away from zero.
In Python 3, this has changed to avoid bias: when x is even,
rounding is towards zero, when x is odd, rounding is away
from zero. Thus, in Python 3, round(2.5) results in 2,
... | def function[py2round, parameter[value]]:
constant[Round values as in Python 2, for Python 3 compatibility.
All x.5 values are rounded away from zero.
In Python 3, this has changed to avoid bias: when x is even,
rounding is towards zero, when x is odd, rounding is away
from zero. Thus, in Pyth... | keyword[def] identifier[py2round] ( identifier[value] ):
literal[string]
keyword[if] identifier[value] > literal[int] :
keyword[return] identifier[float] ( identifier[floor] ( identifier[float] ( identifier[value] )+ literal[int] ))
keyword[else] :
keyword[return] identifier[float... | def py2round(value):
"""Round values as in Python 2, for Python 3 compatibility.
All x.5 values are rounded away from zero.
In Python 3, this has changed to avoid bias: when x is even,
rounding is towards zero, when x is odd, rounding is away
from zero. Thus, in Python 3, round(2.5) results in 2,
... |
def refresh(self):
"""!
\~english
Update current view content to display
Supported: JMRPiDisplay_SSD1306 and Adafruit SSD1306 driver
\~chinese
更新当前视图内容到显示屏
支持: JMRPiDisplay_SSD1306 和 Adafruit SSD1306 driver
"""
try:
# suport for RPiDis... | def function[refresh, parameter[self]]:
constant[!
\~english
Update current view content to display
Supported: JMRPiDisplay_SSD1306 and Adafruit SSD1306 driver
\~chinese
更新当前视图内容到显示屏
支持: JMRPiDisplay_SSD1306 和 Adafruit SSD1306 driver
]
<ast.Try object... | keyword[def] identifier[refresh] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[self] . identifier[Display] . identifier[setImage] ( identifier[self] . identifier[_catchCurrentViewContent] ())
keyword[except] :
keyword[try] :
... | def refresh(self):
"""!
\\~english
Update current view content to display
Supported: JMRPiDisplay_SSD1306 and Adafruit SSD1306 driver
\\~chinese
更新当前视图内容到显示屏
支持: JMRPiDisplay_SSD1306 和 Adafruit SSD1306 driver
"""
try:
# suport for RPiDisplay SSD13... |
def get_positions(self):
"""
Returns a list of positions.
http://dev.wheniwork.com/#listing-positions
"""
url = "/2/positions"
data = self._get_resource(url)
positions = []
for entry in data['positions']:
positions.append(self.position_from_j... | def function[get_positions, parameter[self]]:
constant[
Returns a list of positions.
http://dev.wheniwork.com/#listing-positions
]
variable[url] assign[=] constant[/2/positions]
variable[data] assign[=] call[name[self]._get_resource, parameter[name[url]]]
variabl... | keyword[def] identifier[get_positions] ( identifier[self] ):
literal[string]
identifier[url] = literal[string]
identifier[data] = identifier[self] . identifier[_get_resource] ( identifier[url] )
identifier[positions] =[]
keyword[for] identifier[entry] keyword[in] ide... | def get_positions(self):
"""
Returns a list of positions.
http://dev.wheniwork.com/#listing-positions
"""
url = '/2/positions'
data = self._get_resource(url)
positions = []
for entry in data['positions']:
positions.append(self.position_from_json(entry)) # depends on... |
def lifetimes(self, dates, include_start_date, country_codes):
"""
Compute a DataFrame representing asset lifetimes for the specified date
range.
Parameters
----------
dates : pd.DatetimeIndex
The dates for which to compute lifetimes.
include_start_da... | def function[lifetimes, parameter[self, dates, include_start_date, country_codes]]:
constant[
Compute a DataFrame representing asset lifetimes for the specified date
range.
Parameters
----------
dates : pd.DatetimeIndex
The dates for which to compute lifetime... | keyword[def] identifier[lifetimes] ( identifier[self] , identifier[dates] , identifier[include_start_date] , identifier[country_codes] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[country_codes] , identifier[string_types] ):
keyword[raise] identifier[TypeError] ... | def lifetimes(self, dates, include_start_date, country_codes):
"""
Compute a DataFrame representing asset lifetimes for the specified date
range.
Parameters
----------
dates : pd.DatetimeIndex
The dates for which to compute lifetimes.
include_start_date :... |
def get_after(self, timestamp, s=None):
"""
Find all the (available) logs that are after the given time stamp.
If `s` is not supplied, then all lines are used. Otherwise, only the
lines contain the `s` are used. `s` can be either a single string or a
string list. For list, all... | def function[get_after, parameter[self, timestamp, s]]:
constant[
Find all the (available) logs that are after the given time stamp.
If `s` is not supplied, then all lines are used. Otherwise, only the
lines contain the `s` are used. `s` can be either a single string or a
stri... | keyword[def] identifier[get_after] ( identifier[self] , identifier[timestamp] , identifier[s] = keyword[None] ):
literal[string]
identifier[time_format] = identifier[self] . identifier[time_format]
identifie... | def get_after(self, timestamp, s=None):
"""
Find all the (available) logs that are after the given time stamp.
If `s` is not supplied, then all lines are used. Otherwise, only the
lines contain the `s` are used. `s` can be either a single string or a
string list. For list, all key... |
def timeit(method):
"""Compute the download time."""
def wrapper(*args, **kwargs):
start = time.time()
result = method(*args, **kwargs)
end = time.time()
click.echo('Cost {}s'.format(int(end-start)))
return result
return wrapper | def function[timeit, parameter[method]]:
constant[Compute the download time.]
def function[wrapper, parameter[]]:
variable[start] assign[=] call[name[time].time, parameter[]]
variable[result] assign[=] call[name[method], parameter[<ast.Starred object at 0x7da1b07b9ed0>]]
... | keyword[def] identifier[timeit] ( identifier[method] ):
literal[string]
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
identifier[start] = identifier[time] . identifier[time] ()
identifier[result] = identifier[method] (* identifier[args] ,** identifier[kw... | def timeit(method):
"""Compute the download time."""
def wrapper(*args, **kwargs):
start = time.time()
result = method(*args, **kwargs)
end = time.time()
click.echo('Cost {}s'.format(int(end - start)))
return result
return wrapper |
def alias_book(self, book_id, alias_id):
"""Adds an ``Id`` to a ``Book`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Book`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to another book, it ... | def function[alias_book, parameter[self, book_id, alias_id]]:
constant[Adds an ``Id`` to a ``Book`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Book`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a p... | keyword[def] identifier[alias_book] ( identifier[self] , identifier[book_id] , identifier[alias_id] ):
literal[string]
keyword[if] identifier[self] . identifier[_catalog_session] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifi... | def alias_book(self, book_id, alias_id):
"""Adds an ``Id`` to a ``Book`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Book`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to another book, it is
... |
def nan_maximum_filter(arr, ksize):
'''
same as scipy.filters.maximum_filter
but working excluding nans
'''
out = np.empty_like(arr)
_calc(arr, out, ksize//2)
return out | def function[nan_maximum_filter, parameter[arr, ksize]]:
constant[
same as scipy.filters.maximum_filter
but working excluding nans
]
variable[out] assign[=] call[name[np].empty_like, parameter[name[arr]]]
call[name[_calc], parameter[name[arr], name[out], binary_operation[name[ksize] ... | keyword[def] identifier[nan_maximum_filter] ( identifier[arr] , identifier[ksize] ):
literal[string]
identifier[out] = identifier[np] . identifier[empty_like] ( identifier[arr] )
identifier[_calc] ( identifier[arr] , identifier[out] , identifier[ksize] // literal[int] )
keyword[return] ident... | def nan_maximum_filter(arr, ksize):
"""
same as scipy.filters.maximum_filter
but working excluding nans
"""
out = np.empty_like(arr)
_calc(arr, out, ksize // 2)
return out |
def count(self, index=None, doc_type=None, body=None, **query_params):
"""
Execute a query and get the number of matches for that query.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html>`_
:param index: A comma-separated list of indices to restrict the r... | def function[count, parameter[self, index, doc_type, body]]:
constant[
Execute a query and get the number of matches for that query.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html>`_
:param index: A comma-separated list of indices to restrict the resul... | keyword[def] identifier[count] ( identifier[self] , identifier[index] = keyword[None] , identifier[doc_type] = keyword[None] , identifier[body] = keyword[None] ,** identifier[query_params] ):
literal[string]
keyword[if] identifier[doc_type] keyword[and] keyword[not] identifier[index] :
... | def count(self, index=None, doc_type=None, body=None, **query_params):
"""
Execute a query and get the number of matches for that query.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html>`_
:param index: A comma-separated list of indices to restrict the resul... |
def put(self, lo, hi):
"""Copy 16-bit value to result."""
self.buf.append(lo)
self.buf.append(hi)
self.pos += 1 | def function[put, parameter[self, lo, hi]]:
constant[Copy 16-bit value to result.]
call[name[self].buf.append, parameter[name[lo]]]
call[name[self].buf.append, parameter[name[hi]]]
<ast.AugAssign object at 0x7da20e957100> | keyword[def] identifier[put] ( identifier[self] , identifier[lo] , identifier[hi] ):
literal[string]
identifier[self] . identifier[buf] . identifier[append] ( identifier[lo] )
identifier[self] . identifier[buf] . identifier[append] ( identifier[hi] )
identifier[self] . identifier[... | def put(self, lo, hi):
"""Copy 16-bit value to result."""
self.buf.append(lo)
self.buf.append(hi)
self.pos += 1 |
def element_abund_marco(i_decay, stable_isotope_list,
stable_isotope_identifier,
mass_fractions_array_not_decayed,
mass_fractions_array_decayed):
'''
Given an array of isotopic abundances not decayed and a similar
array of isotopic abun... | def function[element_abund_marco, parameter[i_decay, stable_isotope_list, stable_isotope_identifier, mass_fractions_array_not_decayed, mass_fractions_array_decayed]]:
constant[
Given an array of isotopic abundances not decayed and a similar
array of isotopic abundances not decayed, here elements abundan... | keyword[def] identifier[element_abund_marco] ( identifier[i_decay] , identifier[stable_isotope_list] ,
identifier[stable_isotope_identifier] ,
identifier[mass_fractions_array_not_decayed] ,
identifier[mass_fractions_array_decayed] ):
literal[string]
keyword[global] identifier[el... | def element_abund_marco(i_decay, stable_isotope_list, stable_isotope_identifier, mass_fractions_array_not_decayed, mass_fractions_array_decayed):
"""
Given an array of isotopic abundances not decayed and a similar
array of isotopic abundances not decayed, here elements abundances,
and production factors... |
def get_oqparam(job_ini, pkg=None, calculators=None, hc_id=None, validate=1,
**kw):
"""
Parse a dictionary of parameters from an INI-style config file.
:param job_ini:
Path to configuration file/archive or dictionary of parameters
:param pkg:
Python package where to find... | def function[get_oqparam, parameter[job_ini, pkg, calculators, hc_id, validate]]:
constant[
Parse a dictionary of parameters from an INI-style config file.
:param job_ini:
Path to configuration file/archive or dictionary of parameters
:param pkg:
Python package where to find the con... | keyword[def] identifier[get_oqparam] ( identifier[job_ini] , identifier[pkg] = keyword[None] , identifier[calculators] = keyword[None] , identifier[hc_id] = keyword[None] , identifier[validate] = literal[int] ,
** identifier[kw] ):
literal[string]
keyword[from] identifier[openquake] . identifier[calc... | def get_oqparam(job_ini, pkg=None, calculators=None, hc_id=None, validate=1, **kw):
"""
Parse a dictionary of parameters from an INI-style config file.
:param job_ini:
Path to configuration file/archive or dictionary of parameters
:param pkg:
Python package where to find the configurati... |
def ticket_field_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/ticket_fields#show-ticket-field"
api_path = "/api/v2/ticket_fields/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | def function[ticket_field_show, parameter[self, id]]:
constant[https://developer.zendesk.com/rest_api/docs/core/ticket_fields#show-ticket-field]
variable[api_path] assign[=] constant[/api/v2/ticket_fields/{id}.json]
variable[api_path] assign[=] call[name[api_path].format, parameter[]]
return... | keyword[def] identifier[ticket_field_show] ( identifier[self] , identifier[id] ,** identifier[kwargs] ):
literal[string]
identifier[api_path] = literal[string]
identifier[api_path] = identifier[api_path] . identifier[format] ( identifier[id] = identifier[id] )
keyword[return] id... | def ticket_field_show(self, id, **kwargs):
"""https://developer.zendesk.com/rest_api/docs/core/ticket_fields#show-ticket-field"""
api_path = '/api/v2/ticket_fields/{id}.json'
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) |
def circular_gaussian_kernel(sd,radius):
"""Create a 2-d Gaussian convolution kernel
sd - standard deviation of the gaussian in pixels
radius - build a circular kernel that convolves all points in the circle
bounded by this radius
"""
i,j = np.mgrid[-radius:radius+1,-radius:ra... | def function[circular_gaussian_kernel, parameter[sd, radius]]:
constant[Create a 2-d Gaussian convolution kernel
sd - standard deviation of the gaussian in pixels
radius - build a circular kernel that convolves all points in the circle
bounded by this radius
]
<ast.Tup... | keyword[def] identifier[circular_gaussian_kernel] ( identifier[sd] , identifier[radius] ):
literal[string]
identifier[i] , identifier[j] = identifier[np] . identifier[mgrid] [- identifier[radius] : identifier[radius] + literal[int] ,- identifier[radius] : identifier[radius] + literal[int] ]. identifier[ast... | def circular_gaussian_kernel(sd, radius):
"""Create a 2-d Gaussian convolution kernel
sd - standard deviation of the gaussian in pixels
radius - build a circular kernel that convolves all points in the circle
bounded by this radius
"""
(i, j) = np.mgrid[-radius:radius + 1, -ra... |
def raw_to_bv(self):
"""
A counterpart to FP.raw_to_bv - does nothing and returns itself.
"""
if self.symbolic:
return BVS(next(iter(self.variables)).replace(self.STRING_TYPE_IDENTIFIER, self.GENERATED_BVS_IDENTIFIER), self.length)
else:
return BVV(ord(sel... | def function[raw_to_bv, parameter[self]]:
constant[
A counterpart to FP.raw_to_bv - does nothing and returns itself.
]
if name[self].symbolic begin[:]
return[call[name[BVS], parameter[call[call[name[next], parameter[call[name[iter], parameter[name[self].variables]]]].replace, par... | keyword[def] identifier[raw_to_bv] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[symbolic] :
keyword[return] identifier[BVS] ( identifier[next] ( identifier[iter] ( identifier[self] . identifier[variables] )). identifier[replace] ( identifier[self] .... | def raw_to_bv(self):
"""
A counterpart to FP.raw_to_bv - does nothing and returns itself.
"""
if self.symbolic:
return BVS(next(iter(self.variables)).replace(self.STRING_TYPE_IDENTIFIER, self.GENERATED_BVS_IDENTIFIER), self.length) # depends on [control=['if'], data=[]]
else:
... |
def get_vnet(access_token, subscription_id, resource_group, vnet_name):
'''Get details about the named virtual network.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
vn... | def function[get_vnet, parameter[access_token, subscription_id, resource_group, vnet_name]]:
constant[Get details about the named virtual network.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure ... | keyword[def] identifier[get_vnet] ( identifier[access_token] , identifier[subscription_id] , identifier[resource_group] , identifier[vnet_name] ):
literal[string]
identifier[endpoint] = literal[string] . identifier[join] ([ identifier[get_rm_endpoint] (),
literal[string] , identifier[subscription_id] ... | def get_vnet(access_token, subscription_id, resource_group, vnet_name):
"""Get details about the named virtual network.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
vn... |
def recode_curesim_reads(
curesim_fastq_fo,
rnf_fastq_fo,
fai_fo,
genome_id,
number_of_read_tuples=10**9,
recode_random=False,
):
"""Recode CuReSim output FASTQ file to the RNF-compatible output FASTQ file.
Args:
curesim_fastq_fo (file object): File obje... | def function[recode_curesim_reads, parameter[curesim_fastq_fo, rnf_fastq_fo, fai_fo, genome_id, number_of_read_tuples, recode_random]]:
constant[Recode CuReSim output FASTQ file to the RNF-compatible output FASTQ file.
Args:
curesim_fastq_fo (file object): File object of CuReSim FASTQ file.
fastq_rnf_f... | keyword[def] identifier[recode_curesim_reads] (
identifier[curesim_fastq_fo] ,
identifier[rnf_fastq_fo] ,
identifier[fai_fo] ,
identifier[genome_id] ,
identifier[number_of_read_tuples] = literal[int] ** literal[int] ,
identifier[recode_random] = keyword[False] ,
):
literal[string]
identifier... | def recode_curesim_reads(curesim_fastq_fo, rnf_fastq_fo, fai_fo, genome_id, number_of_read_tuples=10 ** 9, recode_random=False):
"""Recode CuReSim output FASTQ file to the RNF-compatible output FASTQ file.
Args:
curesim_fastq_fo (file object): File object of CuReSim FASTQ file.
fastq_rnf_fo (file object): ... |
def clean(self):
""" Remove intermediate files created
"""
if not util.is_blank(self.catalog.catname) and os.path.exists(self.catalog.catname):
os.remove(self.catalog.catname) | def function[clean, parameter[self]]:
constant[ Remove intermediate files created
]
if <ast.BoolOp object at 0x7da1b1badb70> begin[:]
call[name[os].remove, parameter[name[self].catalog.catname]] | keyword[def] identifier[clean] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[util] . identifier[is_blank] ( identifier[self] . identifier[catalog] . identifier[catname] ) keyword[and] identifier[os] . identifier[path] . identifier[exists] ( identifier[self] . identifi... | def clean(self):
""" Remove intermediate files created
"""
if not util.is_blank(self.catalog.catname) and os.path.exists(self.catalog.catname):
os.remove(self.catalog.catname) # depends on [control=['if'], data=[]] |
def ParseJavaFlags(self, start_line=0):
"""Parse Java style flags (com.google.common.flags)."""
# The java flags prints starts with a "Standard flags" "module"
# that doesn't follow the standard module syntax.
modname = 'Standard flags' # name of current module
self.module_list.append(modna... | def function[ParseJavaFlags, parameter[self, start_line]]:
constant[Parse Java style flags (com.google.common.flags).]
variable[modname] assign[=] constant[Standard flags]
call[name[self].module_list.append, parameter[name[modname]]]
call[name[self].modules.setdefault, parameter[name[mod... | keyword[def] identifier[ParseJavaFlags] ( identifier[self] , identifier[start_line] = literal[int] ):
literal[string]
identifier[modname] = literal[string]
identifier[self] . identifier[module_list] . identifier[append] ( identifier[modname] )
identifier[self] . identifier[modules] . i... | def ParseJavaFlags(self, start_line=0):
"""Parse Java style flags (com.google.common.flags)."""
# The java flags prints starts with a "Standard flags" "module"
# that doesn't follow the standard module syntax.
modname = 'Standard flags' # name of current module
self.module_list.append(modname)
... |
def invoke(ctx, data_file):
"""Invoke the command synchronously"""
click.echo('invoking')
response = ctx.invoke(data_file.read())
log_data = base64.b64decode(response['LogResult'])
click.echo(log_data)
click.echo('Response:')
click.echo(response['Payload'].read())
click.echo('done') | def function[invoke, parameter[ctx, data_file]]:
constant[Invoke the command synchronously]
call[name[click].echo, parameter[constant[invoking]]]
variable[response] assign[=] call[name[ctx].invoke, parameter[call[name[data_file].read, parameter[]]]]
variable[log_data] assign[=] call[name... | keyword[def] identifier[invoke] ( identifier[ctx] , identifier[data_file] ):
literal[string]
identifier[click] . identifier[echo] ( literal[string] )
identifier[response] = identifier[ctx] . identifier[invoke] ( identifier[data_file] . identifier[read] ())
identifier[log_data] = identifier[base64... | def invoke(ctx, data_file):
"""Invoke the command synchronously"""
click.echo('invoking')
response = ctx.invoke(data_file.read())
log_data = base64.b64decode(response['LogResult'])
click.echo(log_data)
click.echo('Response:')
click.echo(response['Payload'].read())
click.echo('done') |
def _format_arg(arg):
"""Validate one exception specification contract tuple/list."""
# Check that the argument conforms to one of the acceptable types, a string
# (when the default exception type is used), an exception type (when the
# default exception message is used) or a list/tuple to specify both
... | def function[_format_arg, parameter[arg]]:
constant[Validate one exception specification contract tuple/list.]
if <ast.UnaryOp object at 0x7da20c6e7850> begin[:]
<ast.Raise object at 0x7da20c6e5d20>
if <ast.BoolOp object at 0x7da20c6e4c10> begin[:]
<ast.Raise object at 0x7da20c6e... | keyword[def] identifier[_format_arg] ( identifier[arg] ):
literal[string]
keyword[if] keyword[not] ( identifier[_isexception] ( identifier[arg] ) keyword[or] identifier[isinstance] ( identifier[arg] ,( identifier[str] , identifier[tuple] , identifier[list] ))):
keyword[raise]... | def _format_arg(arg):
"""Validate one exception specification contract tuple/list."""
# Check that the argument conforms to one of the acceptable types, a string
# (when the default exception type is used), an exception type (when the
# default exception message is used) or a list/tuple to specify both
... |
def compare(self, path, prefixed_path, source_storage):
"""
Returns True if the file should be copied.
"""
# First try a method on the command named compare_<comparison_method>
# If that doesn't exist, create a comparitor that calls methods on the
# storage with the name ... | def function[compare, parameter[self, path, prefixed_path, source_storage]]:
constant[
Returns True if the file should be copied.
]
variable[comparitor] assign[=] call[name[getattr], parameter[name[self], binary_operation[constant[compare_%s] <ast.Mod object at 0x7da2590d6920> name[self]... | keyword[def] identifier[compare] ( identifier[self] , identifier[path] , identifier[prefixed_path] , identifier[source_storage] ):
literal[string]
identifier[comparitor] = identifier[getattr] ( identifier[self] , literal[string] % identifier[self] . identifier[comparison_... | def compare(self, path, prefixed_path, source_storage):
"""
Returns True if the file should be copied.
"""
# First try a method on the command named compare_<comparison_method>
# If that doesn't exist, create a comparitor that calls methods on the
# storage with the name <comparison_meth... |
def load_yaml_file(filename):
""" Load a YAML file from disk, throw a ParserError on failure."""
try:
with open(filename, 'r') as f:
return yaml.safe_load(f)
except IOError as e:
raise ParserError('Error opening ' + filename + ': ' + e.message)
except ValueError as e:
... | def function[load_yaml_file, parameter[filename]]:
constant[ Load a YAML file from disk, throw a ParserError on failure.]
<ast.Try object at 0x7da1b0334940> | keyword[def] identifier[load_yaml_file] ( identifier[filename] ):
literal[string]
keyword[try] :
keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[f] :
keyword[return] identifier[yaml] . identifier[safe_load] ( identifier[f] )
key... | def load_yaml_file(filename):
""" Load a YAML file from disk, throw a ParserError on failure."""
try:
with open(filename, 'r') as f:
return yaml.safe_load(f) # depends on [control=['with'], data=['f']] # depends on [control=['try'], data=[]]
except IOError as e:
raise ParserErr... |
def _check_index(self):
"""Check that the index is without the bounds of _history."""
assert 0 <= self._index <= len(self._history) - 1
# There should always be the base item at least.
assert len(self._history) >= 1 | def function[_check_index, parameter[self]]:
constant[Check that the index is without the bounds of _history.]
assert[compare[constant[0] less_or_equal[<=] name[self]._index]]
assert[compare[call[name[len], parameter[name[self]._history]] greater_or_equal[>=] constant[1]]] | keyword[def] identifier[_check_index] ( identifier[self] ):
literal[string]
keyword[assert] literal[int] <= identifier[self] . identifier[_index] <= identifier[len] ( identifier[self] . identifier[_history] )- literal[int]
keyword[assert] identifier[len] ( identifier[self] . id... | def _check_index(self):
"""Check that the index is without the bounds of _history."""
assert 0 <= self._index <= len(self._history) - 1
# There should always be the base item at least.
assert len(self._history) >= 1 |
def export_as_file(self, filepath, hyperparameters):
"""Generates a Python file with the importable base learner set to ``hyperparameters``
This function generates a Python file in the specified file path that contains
the base learner as an importable variable stored in ``base_learner``. The... | def function[export_as_file, parameter[self, filepath, hyperparameters]]:
constant[Generates a Python file with the importable base learner set to ``hyperparameters``
This function generates a Python file in the specified file path that contains
the base learner as an importable variable stor... | keyword[def] identifier[export_as_file] ( identifier[self] , identifier[filepath] , identifier[hyperparameters] ):
literal[string]
keyword[if] keyword[not] identifier[filepath] . identifier[endswith] ( literal[string] ):
identifier[filepath] += literal[string]
identifier[f... | def export_as_file(self, filepath, hyperparameters):
"""Generates a Python file with the importable base learner set to ``hyperparameters``
This function generates a Python file in the specified file path that contains
the base learner as an importable variable stored in ``base_learner``. The bas... |
def mixer(servo1, servo2, mixtype=1, gain=0.5):
'''mix two servos'''
s1 = servo1 - 1500
s2 = servo2 - 1500
v1 = (s1-s2)*gain
v2 = (s1+s2)*gain
if mixtype == 2:
v2 = -v2
elif mixtype == 3:
v1 = -v1
elif mixtype == 4:
v1 = -v1
v2 = -v2
if v1 > 600:
... | def function[mixer, parameter[servo1, servo2, mixtype, gain]]:
constant[mix two servos]
variable[s1] assign[=] binary_operation[name[servo1] - constant[1500]]
variable[s2] assign[=] binary_operation[name[servo2] - constant[1500]]
variable[v1] assign[=] binary_operation[binary_operation[n... | keyword[def] identifier[mixer] ( identifier[servo1] , identifier[servo2] , identifier[mixtype] = literal[int] , identifier[gain] = literal[int] ):
literal[string]
identifier[s1] = identifier[servo1] - literal[int]
identifier[s2] = identifier[servo2] - literal[int]
identifier[v1] =( identifier[s... | def mixer(servo1, servo2, mixtype=1, gain=0.5):
"""mix two servos"""
s1 = servo1 - 1500
s2 = servo2 - 1500
v1 = (s1 - s2) * gain
v2 = (s1 + s2) * gain
if mixtype == 2:
v2 = -v2 # depends on [control=['if'], data=[]]
elif mixtype == 3:
v1 = -v1 # depends on [control=['if'], ... |
def threshold(self, value):
"""Threshold used to determine if your content qualifies as spam.
On a scale from 1 to 10, with 10 being most strict, or most likely to
be considered as spam.
:param value: Threshold used to determine if your content qualifies as
spam.
... | def function[threshold, parameter[self, value]]:
constant[Threshold used to determine if your content qualifies as spam.
On a scale from 1 to 10, with 10 being most strict, or most likely to
be considered as spam.
:param value: Threshold used to determine if your content qualifies as
... | keyword[def] identifier[threshold] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[SpamThreshold] ):
identifier[self] . identifier[_threshold] = identifier[value]
keyword[else] :
ident... | def threshold(self, value):
"""Threshold used to determine if your content qualifies as spam.
On a scale from 1 to 10, with 10 being most strict, or most likely to
be considered as spam.
:param value: Threshold used to determine if your content qualifies as
spam.
... |
def fsplit(pred, objs):
"""Split a list into two classes according to the predicate."""
t = []
f = []
for obj in objs:
if pred(obj):
t.append(obj)
else:
f.append(obj)
return (t, f) | def function[fsplit, parameter[pred, objs]]:
constant[Split a list into two classes according to the predicate.]
variable[t] assign[=] list[[]]
variable[f] assign[=] list[[]]
for taget[name[obj]] in starred[name[objs]] begin[:]
if call[name[pred], parameter[name[obj]]] be... | keyword[def] identifier[fsplit] ( identifier[pred] , identifier[objs] ):
literal[string]
identifier[t] =[]
identifier[f] =[]
keyword[for] identifier[obj] keyword[in] identifier[objs] :
keyword[if] identifier[pred] ( identifier[obj] ):
identifier[t] . identifier[append] (... | def fsplit(pred, objs):
"""Split a list into two classes according to the predicate."""
t = []
f = []
for obj in objs:
if pred(obj):
t.append(obj) # depends on [control=['if'], data=[]]
else:
f.append(obj) # depends on [control=['for'], data=['obj']]
return ... |
def encode(self):
"""Base64-encode the data contained in the reply when appropriate.
:return: encoded data.
:returntype: `unicode`
"""
if self.data is None:
return ""
elif not self.data:
return "="
else:
ret = standard_b64encod... | def function[encode, parameter[self]]:
constant[Base64-encode the data contained in the reply when appropriate.
:return: encoded data.
:returntype: `unicode`
]
if compare[name[self].data is constant[None]] begin[:]
return[constant[]] | keyword[def] identifier[encode] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[data] keyword[is] keyword[None] :
keyword[return] literal[string]
keyword[elif] keyword[not] identifier[self] . identifier[data] :
keyword[return... | def encode(self):
"""Base64-encode the data contained in the reply when appropriate.
:return: encoded data.
:returntype: `unicode`
"""
if self.data is None:
return '' # depends on [control=['if'], data=[]]
elif not self.data:
return '=' # depends on [control=['if']... |
def get_user_roles(self, user):
"""Get roles associated with the given user.
Args:
user (string): User name.
Returns:
(list): List of roles that user has.
Raises:
requests.HTTPError on failure.
"""
return self.service.get_user_roles(... | def function[get_user_roles, parameter[self, user]]:
constant[Get roles associated with the given user.
Args:
user (string): User name.
Returns:
(list): List of roles that user has.
Raises:
requests.HTTPError on failure.
]
return[call[na... | keyword[def] identifier[get_user_roles] ( identifier[self] , identifier[user] ):
literal[string]
keyword[return] identifier[self] . identifier[service] . identifier[get_user_roles] (
identifier[user] , identifier[self] . identifier[url_prefix] , identifier[self] . identifier[auth] , ident... | def get_user_roles(self, user):
"""Get roles associated with the given user.
Args:
user (string): User name.
Returns:
(list): List of roles that user has.
Raises:
requests.HTTPError on failure.
"""
return self.service.get_user_roles(user, se... |
def _to_dict(objects):
'''
Potentially interprets a string as JSON for usage with mongo
'''
try:
if isinstance(objects, six.string_types):
objects = salt.utils.json.loads(objects)
except ValueError as err:
log.error("Could not parse objects: %s", err)
raise err
... | def function[_to_dict, parameter[objects]]:
constant[
Potentially interprets a string as JSON for usage with mongo
]
<ast.Try object at 0x7da18bc73820>
return[name[objects]] | keyword[def] identifier[_to_dict] ( identifier[objects] ):
literal[string]
keyword[try] :
keyword[if] identifier[isinstance] ( identifier[objects] , identifier[six] . identifier[string_types] ):
identifier[objects] = identifier[salt] . identifier[utils] . identifier[json] . identifie... | def _to_dict(objects):
"""
Potentially interprets a string as JSON for usage with mongo
"""
try:
if isinstance(objects, six.string_types):
objects = salt.utils.json.loads(objects) # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]]
except ValueError a... |
def _proc_loop(proc_id, alive, queue, fn):
"""Thread loop for generating data
Parameters
----------
proc_id: int
Process id
alive: multiprocessing.Value
variable for signaling whether process should continue or not
queue: multiprocessing.Queue
... | def function[_proc_loop, parameter[proc_id, alive, queue, fn]]:
constant[Thread loop for generating data
Parameters
----------
proc_id: int
Process id
alive: multiprocessing.Value
variable for signaling whether process should continue or not
queue... | keyword[def] identifier[_proc_loop] ( identifier[proc_id] , identifier[alive] , identifier[queue] , identifier[fn] ):
literal[string]
identifier[print] ( literal[string] . identifier[format] ( identifier[proc_id] ))
keyword[try] :
keyword[while] identifier[alive] . identifier... | def _proc_loop(proc_id, alive, queue, fn):
"""Thread loop for generating data
Parameters
----------
proc_id: int
Process id
alive: multiprocessing.Value
variable for signaling whether process should continue or not
queue: multiprocessing.Queue
... |
def _wrapper(func, *args, **kwargs):
'Decorator for the methods that follow'
try:
if func.__name__ == "init":
# init may not fail, as its return code is just stored as
# private_data field of struct fuse_context
return func(*args, **kwargs) or... | def function[_wrapper, parameter[func]]:
constant[Decorator for the methods that follow]
<ast.Try object at 0x7da2047eaad0> | keyword[def] identifier[_wrapper] ( identifier[func] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
keyword[if] identifier[func] . identifier[__name__] == literal[string] :
keyword[return] identifier[func] (* i... | def _wrapper(func, *args, **kwargs):
"""Decorator for the methods that follow"""
try:
if func.__name__ == 'init':
# init may not fail, as its return code is just stored as
# private_data field of struct fuse_context
return func(*args, **kwargs) or 0 # depends on [con... |
def get_asset_content_form_for_create(self, asset_id, asset_content_record_types):
"""Gets an asset content form for creating new assets.
arg: asset_id (osid.id.Id): the ``Id`` of an ``Asset``
arg: asset_content_record_types (osid.type.Type[]): array of
asset content recor... | def function[get_asset_content_form_for_create, parameter[self, asset_id, asset_content_record_types]]:
constant[Gets an asset content form for creating new assets.
arg: asset_id (osid.id.Id): the ``Id`` of an ``Asset``
arg: asset_content_record_types (osid.type.Type[]): array of
... | keyword[def] identifier[get_asset_content_form_for_create] ( identifier[self] , identifier[asset_id] , identifier[asset_content_record_types] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[asset_id] , identifier[ABCId] ):
keyword[ra... | def get_asset_content_form_for_create(self, asset_id, asset_content_record_types):
"""Gets an asset content form for creating new assets.
arg: asset_id (osid.id.Id): the ``Id`` of an ``Asset``
arg: asset_content_record_types (osid.type.Type[]): array of
asset content record ty... |
def drawSquiggle(self, p1, p2, breadth = 2):
"""Draw a squiggly line from p1 to p2.
"""
p1 = Point(p1)
p2 = Point(p2)
S = p2 - p1 # vector start - end
rad = abs(S) # distance of points
cnt = 4 * int(round(rad ... | def function[drawSquiggle, parameter[self, p1, p2, breadth]]:
constant[Draw a squiggly line from p1 to p2.
]
variable[p1] assign[=] call[name[Point], parameter[name[p1]]]
variable[p2] assign[=] call[name[Point], parameter[name[p2]]]
variable[S] assign[=] binary_operation[name[p2]... | keyword[def] identifier[drawSquiggle] ( identifier[self] , identifier[p1] , identifier[p2] , identifier[breadth] = literal[int] ):
literal[string]
identifier[p1] = identifier[Point] ( identifier[p1] )
identifier[p2] = identifier[Point] ( identifier[p2] )
identifier[S] = identifier... | def drawSquiggle(self, p1, p2, breadth=2):
"""Draw a squiggly line from p1 to p2.
"""
p1 = Point(p1)
p2 = Point(p2)
S = p2 - p1 # vector start - end
rad = abs(S) # distance of points
cnt = 4 * int(round(rad / (4 * breadth), 0)) # always take full phases
if cnt < 4:
raise V... |
def symbols_expanding_pre_event_input_accelerators(editor, event):
"""
Implements symbols expanding pre event input accelerators.
:param editor: Document editor.
:type editor: QWidget
:param event: Event being handled.
:type event: QEvent
:return: Process event.
:rtype: bool
"""
... | def function[symbols_expanding_pre_event_input_accelerators, parameter[editor, event]]:
constant[
Implements symbols expanding pre event input accelerators.
:param editor: Document editor.
:type editor: QWidget
:param event: Event being handled.
:type event: QEvent
:return: Process even... | keyword[def] identifier[symbols_expanding_pre_event_input_accelerators] ( identifier[editor] , identifier[event] ):
literal[string]
identifier[process_event] = keyword[True]
identifier[symbols_pairs] = identifier[get_editor_capability] ( identifier[editor] , literal[string] )
keyword[if] keyw... | def symbols_expanding_pre_event_input_accelerators(editor, event):
"""
Implements symbols expanding pre event input accelerators.
:param editor: Document editor.
:type editor: QWidget
:param event: Event being handled.
:type event: QEvent
:return: Process event.
:rtype: bool
"""
... |
def concatenate(*args, **kwargs):
"""
Concatenates the given strings.
Usage::
{% load libs_tags %}
{% concatenate "foo" "bar" as new_string %}
{% concatenate "foo" "bar" divider="_" as another_string %}
The above would result in the strings "foobar" and "foo_bar".
"""
... | def function[concatenate, parameter[]]:
constant[
Concatenates the given strings.
Usage::
{% load libs_tags %}
{% concatenate "foo" "bar" as new_string %}
{% concatenate "foo" "bar" divider="_" as another_string %}
The above would result in the strings "foobar" and "foo_ba... | keyword[def] identifier[concatenate] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[divider] = identifier[kwargs] . identifier[get] ( literal[string] , literal[string] )
identifier[result] = literal[string]
keyword[for] identifier[arg] keyword[in] identifier[args] :
... | def concatenate(*args, **kwargs):
"""
Concatenates the given strings.
Usage::
{% load libs_tags %}
{% concatenate "foo" "bar" as new_string %}
{% concatenate "foo" "bar" divider="_" as another_string %}
The above would result in the strings "foobar" and "foo_bar".
"""
... |
def orientality(self):
""" Returns the orientality of the object. """
sun = self.chart.getObject(const.SUN)
return orientality(self.obj, sun) | def function[orientality, parameter[self]]:
constant[ Returns the orientality of the object. ]
variable[sun] assign[=] call[name[self].chart.getObject, parameter[name[const].SUN]]
return[call[name[orientality], parameter[name[self].obj, name[sun]]]] | keyword[def] identifier[orientality] ( identifier[self] ):
literal[string]
identifier[sun] = identifier[self] . identifier[chart] . identifier[getObject] ( identifier[const] . identifier[SUN] )
keyword[return] identifier[orientality] ( identifier[self] . identifier[obj] , identifier[sun] ... | def orientality(self):
""" Returns the orientality of the object. """
sun = self.chart.getObject(const.SUN)
return orientality(self.obj, sun) |
def fillTriangle(self, x0, y0, x1, y1, x2, y2, color=None, aa=False):
"""
Draw filled triangle with points x0,y0 - x1,y1 - x2,y2
:param aa: if True, use Bresenham's algorithm for line drawing;
otherwise use Xiaolin Wu's algorithm
"""
md.fill_triangle(self.set, x0, y0... | def function[fillTriangle, parameter[self, x0, y0, x1, y1, x2, y2, color, aa]]:
constant[
Draw filled triangle with points x0,y0 - x1,y1 - x2,y2
:param aa: if True, use Bresenham's algorithm for line drawing;
otherwise use Xiaolin Wu's algorithm
]
call[name[md].fill_... | keyword[def] identifier[fillTriangle] ( identifier[self] , identifier[x0] , identifier[y0] , identifier[x1] , identifier[y1] , identifier[x2] , identifier[y2] , identifier[color] = keyword[None] , identifier[aa] = keyword[False] ):
literal[string]
identifier[md] . identifier[fill_triangle] ( identi... | def fillTriangle(self, x0, y0, x1, y1, x2, y2, color=None, aa=False):
"""
Draw filled triangle with points x0,y0 - x1,y1 - x2,y2
:param aa: if True, use Bresenham's algorithm for line drawing;
otherwise use Xiaolin Wu's algorithm
"""
md.fill_triangle(self.set, x0, y0, x1, y1... |
async def get_session_data(self):
"""Get Tautulli sessions."""
cmd = 'get_activity'
url = self.base_url + cmd
try:
async with async_timeout.timeout(8, loop=self._loop):
response = await self._session.get(url)
logger("Status from Tautulli: " + str(... | <ast.AsyncFunctionDef object at 0x7da18f811450> | keyword[async] keyword[def] identifier[get_session_data] ( identifier[self] ):
literal[string]
identifier[cmd] = literal[string]
identifier[url] = identifier[self] . identifier[base_url] + identifier[cmd]
keyword[try] :
keyword[async] keyword[with] identifier[asy... | async def get_session_data(self):
"""Get Tautulli sessions."""
cmd = 'get_activity'
url = self.base_url + cmd
try:
async with async_timeout.timeout(8, loop=self._loop):
response = await self._session.get(url)
logger('Status from Tautulli: ' + str(response.status))
sel... |
def run(self):
"""Loop forever, pushing out stats."""
self.graphite.start()
while True:
log.debug('Graphite pusher is sleeping for %d seconds', self.period)
time.sleep(self.period)
log.debug('Pushing stats to Graphite')
try:
self.push()
log.debug('Done pushing stats t... | def function[run, parameter[self]]:
constant[Loop forever, pushing out stats.]
call[name[self].graphite.start, parameter[]]
while constant[True] begin[:]
call[name[log].debug, parameter[constant[Graphite pusher is sleeping for %d seconds], name[self].period]]
call... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[self] . identifier[graphite] . identifier[start] ()
keyword[while] keyword[True] :
identifier[log] . identifier[debug] ( literal[string] , identifier[self] . identifier[period] )
identifier[time] . identifier[... | def run(self):
"""Loop forever, pushing out stats."""
self.graphite.start()
while True:
log.debug('Graphite pusher is sleeping for %d seconds', self.period)
time.sleep(self.period)
log.debug('Pushing stats to Graphite')
try:
self.push()
log.debug('Done... |
def json_schema_type(schema_file: str, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.JsonSchema` type.
This function will automatically load the schema and set it as an attribute
of the class along with the description and example.
:param schema_file: The full path to the json schema fil... | def function[json_schema_type, parameter[schema_file]]:
constant[Create a :class:`~doctor.types.JsonSchema` type.
This function will automatically load the schema and set it as an attribute
of the class along with the description and example.
:param schema_file: The full path to the json schema fi... | keyword[def] identifier[json_schema_type] ( identifier[schema_file] : identifier[str] ,** identifier[kwargs] )-> identifier[typing] . identifier[Type] :
literal[string]
keyword[from] identifier[doctor] . identifier[resource] keyword[import] identifier[ResourceSchema]
identifier[schema] = iden... | def json_schema_type(schema_file: str, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.JsonSchema` type.
This function will automatically load the schema and set it as an attribute
of the class along with the description and example.
:param schema_file: The full path to the json schema fil... |
def _layout_for_domfuzz(self, path):
"""
Update directory to work with DOMFuzz
@type path: str
@param path: A string representation of the fuzzmanager config path
"""
old_dir = os.getcwd()
os.chdir(os.path.join(path))
try:
os.mkdir('dist')
... | def function[_layout_for_domfuzz, parameter[self, path]]:
constant[
Update directory to work with DOMFuzz
@type path: str
@param path: A string representation of the fuzzmanager config path
]
variable[old_dir] assign[=] call[name[os].getcwd, parameter[]]
call[nam... | keyword[def] identifier[_layout_for_domfuzz] ( identifier[self] , identifier[path] ):
literal[string]
identifier[old_dir] = identifier[os] . identifier[getcwd] ()
identifier[os] . identifier[chdir] ( identifier[os] . identifier[path] . identifier[join] ( identifier[path] ))
keywor... | def _layout_for_domfuzz(self, path):
"""
Update directory to work with DOMFuzz
@type path: str
@param path: A string representation of the fuzzmanager config path
"""
old_dir = os.getcwd()
os.chdir(os.path.join(path))
try:
os.mkdir('dist')
link_name = os.... |
def _ParseCommentRecord(self, structure):
"""Parse a comment and store appropriate attributes.
Args:
structure (pyparsing.ParseResults): parsed log line.
"""
comment = structure[1]
if comment.startswith('Version'):
_, _, self._version = comment.partition(':')
elif comment.startswith... | def function[_ParseCommentRecord, parameter[self, structure]]:
constant[Parse a comment and store appropriate attributes.
Args:
structure (pyparsing.ParseResults): parsed log line.
]
variable[comment] assign[=] call[name[structure]][constant[1]]
if call[name[comment].startswith, p... | keyword[def] identifier[_ParseCommentRecord] ( identifier[self] , identifier[structure] ):
literal[string]
identifier[comment] = identifier[structure] [ literal[int] ]
keyword[if] identifier[comment] . identifier[startswith] ( literal[string] ):
identifier[_] , identifier[_] , identifier[self]... | def _ParseCommentRecord(self, structure):
"""Parse a comment and store appropriate attributes.
Args:
structure (pyparsing.ParseResults): parsed log line.
"""
comment = structure[1]
if comment.startswith('Version'):
(_, _, self._version) = comment.partition(':') # depends on [control=... |
def publish(self, events):
"""Publish events."""
assert len(events) > 0
with self.create_producer() as producer:
for event in events:
producer.publish(event) | def function[publish, parameter[self, events]]:
constant[Publish events.]
assert[compare[call[name[len], parameter[name[events]]] greater[>] constant[0]]]
with call[name[self].create_producer, parameter[]] begin[:]
for taget[name[event]] in starred[name[events]] begin[:]
... | keyword[def] identifier[publish] ( identifier[self] , identifier[events] ):
literal[string]
keyword[assert] identifier[len] ( identifier[events] )> literal[int]
keyword[with] identifier[self] . identifier[create_producer] () keyword[as] identifier[producer] :
keyword[for] ... | def publish(self, events):
"""Publish events."""
assert len(events) > 0
with self.create_producer() as producer:
for event in events:
producer.publish(event) # depends on [control=['for'], data=['event']] # depends on [control=['with'], data=['producer']] |
def find_id_in_folder(self, name, parent_folder_id=0):
"""Find a folder or a file ID from its name, inside a given folder.
Args:
name (str): Name of the folder or the file to find.
parent_folder_id (int): ID of the folder where to search.
Returns:
int. ID o... | def function[find_id_in_folder, parameter[self, name, parent_folder_id]]:
constant[Find a folder or a file ID from its name, inside a given folder.
Args:
name (str): Name of the folder or the file to find.
parent_folder_id (int): ID of the folder where to search.
Retur... | keyword[def] identifier[find_id_in_folder] ( identifier[self] , identifier[name] , identifier[parent_folder_id] = literal[int] ):
literal[string]
keyword[if] identifier[name] keyword[is] keyword[None] keyword[or] identifier[len] ( identifier[name] )== literal[int] :
keyword[return... | def find_id_in_folder(self, name, parent_folder_id=0):
"""Find a folder or a file ID from its name, inside a given folder.
Args:
name (str): Name of the folder or the file to find.
parent_folder_id (int): ID of the folder where to search.
Returns:
int. ID of th... |
def define_symbol(name, open_brace, comma, i, j,
close_brace, variables, **kwds):
r"""Define a nice symbol with matrix indices.
>>> name = "rho"
>>> from sympy import symbols
>>> t, x, y, z = symbols("t, x, y, z", positive=True)
>>> variables = [t, x, y, z]
>>> open_brace = ""... | def function[define_symbol, parameter[name, open_brace, comma, i, j, close_brace, variables]]:
constant[Define a nice symbol with matrix indices.
>>> name = "rho"
>>> from sympy import symbols
>>> t, x, y, z = symbols("t, x, y, z", positive=True)
>>> variables = [t, x, y, z]
>>> open_brace ... | keyword[def] identifier[define_symbol] ( identifier[name] , identifier[open_brace] , identifier[comma] , identifier[i] , identifier[j] ,
identifier[close_brace] , identifier[variables] ,** identifier[kwds] ):
literal[string]
keyword[if] identifier[variables] keyword[is] keyword[None] :
keyword... | def define_symbol(name, open_brace, comma, i, j, close_brace, variables, **kwds):
"""Define a nice symbol with matrix indices.
>>> name = "rho"
>>> from sympy import symbols
>>> t, x, y, z = symbols("t, x, y, z", positive=True)
>>> variables = [t, x, y, z]
>>> open_brace = ""
>>> comma = ""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.