code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def append_dynamic(self, t, dynamic, canvas=0, color='blue'):
"""!
@brief Append single dynamic to specified canvas (by default to the first with index '0').
@param[in] t (list): Time points that corresponds to dynamic values and considered on a X axis.
@param[in] dynamic (list): V... | def function[append_dynamic, parameter[self, t, dynamic, canvas, color]]:
constant[!
@brief Append single dynamic to specified canvas (by default to the first with index '0').
@param[in] t (list): Time points that corresponds to dynamic values and considered on a X axis.
@param[in] dyna... | keyword[def] identifier[append_dynamic] ( identifier[self] , identifier[t] , identifier[dynamic] , identifier[canvas] = literal[int] , identifier[color] = literal[string] ):
literal[string]
identifier[description] = identifier[dynamic_descr] ( identifier[canvas] , identifier[t] , identifier[dynam... | def append_dynamic(self, t, dynamic, canvas=0, color='blue'):
"""!
@brief Append single dynamic to specified canvas (by default to the first with index '0').
@param[in] t (list): Time points that corresponds to dynamic values and considered on a X axis.
@param[in] dynamic (list): Value poin... |
def pretty_print(node):
"""漂亮地打印一个节点
Args:
node (TYPE): Description
"""
for pre, _, node in RenderTree(node):
print('{}{}'.format(pre, node.name)) | def function[pretty_print, parameter[node]]:
constant[漂亮地打印一个节点
Args:
node (TYPE): Description
]
for taget[tuple[[<ast.Name object at 0x7da204622080>, <ast.Name object at 0x7da204620b20>, <ast.Name object at 0x7da204622b30>]]] in starred[call[name[RenderTree], parameter[name... | keyword[def] identifier[pretty_print] ( identifier[node] ):
literal[string]
keyword[for] identifier[pre] , identifier[_] , identifier[node] keyword[in] identifier[RenderTree] ( identifier[node] ):
identifier[print] ( literal[string] . identifier[format] ( identifier[pre] , identifie... | def pretty_print(node):
"""漂亮地打印一个节点
Args:
node (TYPE): Description
"""
for (pre, _, node) in RenderTree(node):
print('{}{}'.format(pre, node.name)) # depends on [control=['for'], data=[]] |
def set_state(self, entity_id, new_state, **kwargs):
"Updates or creates the current state of an entity."
return remote.set_state(self.api, new_state, **kwargs) | def function[set_state, parameter[self, entity_id, new_state]]:
constant[Updates or creates the current state of an entity.]
return[call[name[remote].set_state, parameter[name[self].api, name[new_state]]]] | keyword[def] identifier[set_state] ( identifier[self] , identifier[entity_id] , identifier[new_state] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[remote] . identifier[set_state] ( identifier[self] . identifier[api] , identifier[new_state] ,** identifier[kwargs] ) | def set_state(self, entity_id, new_state, **kwargs):
"""Updates or creates the current state of an entity."""
return remote.set_state(self.api, new_state, **kwargs) |
def gateway_by_type(self, type=None, on_network=None): # @ReservedAssignment
"""
Return gateways for the specified node. You can also
specify type to find only gateways of a specific type.
Valid types are: bgp_peering, netlink, ospfv2_area.
:param RoutingNode self: the routing node to check
... | def function[gateway_by_type, parameter[self, type, on_network]]:
constant[
Return gateways for the specified node. You can also
specify type to find only gateways of a specific type.
Valid types are: bgp_peering, netlink, ospfv2_area.
:param RoutingNode self: the routing node to check
... | keyword[def] identifier[gateway_by_type] ( identifier[self] , identifier[type] = keyword[None] , identifier[on_network] = keyword[None] ):
literal[string]
identifier[gateways] = identifier[route_level] ( identifier[self] , literal[string] )
keyword[if] keyword[not] identifier[type] :
keywor... | def gateway_by_type(self, type=None, on_network=None): # @ReservedAssignment
'\n Return gateways for the specified node. You can also\n specify type to find only gateways of a specific type.\n Valid types are: bgp_peering, netlink, ospfv2_area.\n \n :param RoutingNode self: the routing node to check... |
def attributes(self):
"""
A dictionary mapping names of attributes to BiomartAttribute instances.
This causes overwriting errors if there are diffferent pages which use
the same attribute names, but is kept for backward compatibility.
"""
if not self._attribute_pages:
... | def function[attributes, parameter[self]]:
constant[
A dictionary mapping names of attributes to BiomartAttribute instances.
This causes overwriting errors if there are diffferent pages which use
the same attribute names, but is kept for backward compatibility.
]
if <ast... | keyword[def] identifier[attributes] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_attribute_pages] :
identifier[self] . identifier[fetch_attributes] ()
identifier[result] ={}
keyword[for] identifier[page] keyword[in]... | def attributes(self):
"""
A dictionary mapping names of attributes to BiomartAttribute instances.
This causes overwriting errors if there are diffferent pages which use
the same attribute names, but is kept for backward compatibility.
"""
if not self._attribute_pages:
se... |
def present(name, deployment_id, metric_name, alert_config, api_key=None, profile='telemetry'):
'''
Ensure the telemetry alert exists.
name
An optional description of the alarm (not currently supported by telemetry API)
deployment_id
Specifies the ID of the root deployment resource
... | def function[present, parameter[name, deployment_id, metric_name, alert_config, api_key, profile]]:
constant[
Ensure the telemetry alert exists.
name
An optional description of the alarm (not currently supported by telemetry API)
deployment_id
Specifies the ID of the root deploymen... | keyword[def] identifier[present] ( identifier[name] , identifier[deployment_id] , identifier[metric_name] , identifier[alert_config] , identifier[api_key] = keyword[None] , identifier[profile] = literal[string] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[metric_name] , literal[strin... | def present(name, deployment_id, metric_name, alert_config, api_key=None, profile='telemetry'):
"""
Ensure the telemetry alert exists.
name
An optional description of the alarm (not currently supported by telemetry API)
deployment_id
Specifies the ID of the root deployment resource
... |
def pos(self):
"""
Lazy-loads the part of speech tag for this word
:getter: Returns the plain string value of the POS tag for the word
:type: str
"""
if self._pos is None:
poses = self._element.xpath('POS/text()')
if len(poses) > 0:
... | def function[pos, parameter[self]]:
constant[
Lazy-loads the part of speech tag for this word
:getter: Returns the plain string value of the POS tag for the word
:type: str
]
if compare[name[self]._pos is constant[None]] begin[:]
variable[poses] assign[=... | keyword[def] identifier[pos] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_pos] keyword[is] keyword[None] :
identifier[poses] = identifier[self] . identifier[_element] . identifier[xpath] ( literal[string] )
keyword[if] identifier[len... | def pos(self):
"""
Lazy-loads the part of speech tag for this word
:getter: Returns the plain string value of the POS tag for the word
:type: str
"""
if self._pos is None:
poses = self._element.xpath('POS/text()')
if len(poses) > 0:
self._pos = poses... |
async def handle_client_request(self, req, res):
"""
Entry point for the request + response middleware chain.
This is called by growler.HTTPResponder (the default responder)
after the headers have been processed in the begin_application
method.
This iterates over all mid... | <ast.AsyncFunctionDef object at 0x7da18bcc8070> | keyword[async] keyword[def] identifier[handle_client_request] ( identifier[self] , identifier[req] , identifier[res] ):
literal[string]
identifier[mw_generator] = identifier[self] . identifier[middleware] ( identifier[req] . identifier[method] , identifier[req] . identifier[path] )
... | async def handle_client_request(self, req, res):
"""
Entry point for the request + response middleware chain.
This is called by growler.HTTPResponder (the default responder)
after the headers have been processed in the begin_application
method.
This iterates over all middlew... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'key') and self.key is not None:
_dict['key'] = self.key
if hasattr(self,
'matching_results') and self.matching_results is not None:
_dict['m... | def function[_to_dict, parameter[self]]:
constant[Return a json dictionary representing this model.]
variable[_dict] assign[=] dictionary[[], []]
if <ast.BoolOp object at 0x7da2044c2920> begin[:]
call[name[_dict]][constant[key]] assign[=] name[self].key
if <ast.BoolOp obj... | keyword[def] identifier[_to_dict] ( identifier[self] ):
literal[string]
identifier[_dict] ={}
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and] identifier[self] . identifier[key] keyword[is] keyword[not] keyword[None] :
identifier[_dict] ... | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'key') and self.key is not None:
_dict['key'] = self.key # depends on [control=['if'], data=[]]
if hasattr(self, 'matching_results') and self.matching_results is not None:
_dict['matc... |
def device_unmounted(self, device):
"""Show unmount notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_unmounted',
_('Device unmounted'),
_('{0.ui_label} unmounted', devi... | def function[device_unmounted, parameter[self, device]]:
constant[Show unmount notification for specified device object.]
if <ast.UnaryOp object at 0x7da20c6e5300> begin[:]
return[None]
call[name[self]._show_notification, parameter[constant[device_unmounted], call[name[_], parameter[cons... | keyword[def] identifier[device_unmounted] ( identifier[self] , identifier[device] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_mounter] . identifier[is_handleable] ( identifier[device] ):
keyword[return]
identifier[self] . identifier[_show_noti... | def device_unmounted(self, device):
"""Show unmount notification for specified device object."""
if not self._mounter.is_handleable(device):
return # depends on [control=['if'], data=[]]
self._show_notification('device_unmounted', _('Device unmounted'), _('{0.ui_label} unmounted', device), device.i... |
def update(self, play):
"""
Update the accumulator with the current play
:returns: new tally
:rtype: dict, ``{ 'period': per, 'time': clock, 'team': cumul, 'play': play }``
"""
new_tally = { }
#if any(isinstance(play.event, te) for te in self.trigger_even... | def function[update, parameter[self, play]]:
constant[
Update the accumulator with the current play
:returns: new tally
:rtype: dict, ``{ 'period': per, 'time': clock, 'team': cumul, 'play': play }``
]
variable[new_tally] assign[=] dictionary[[], []]
if c... | keyword[def] identifier[update] ( identifier[self] , identifier[play] ):
literal[string]
identifier[new_tally] ={}
keyword[if] identifier[self] . identifier[_count_play] ( identifier[play] ):
identifier[team] = identifier[self] . identifier[_get_team] ( ide... | def update(self, play):
"""
Update the accumulator with the current play
:returns: new tally
:rtype: dict, ``{ 'period': per, 'time': clock, 'team': cumul, 'play': play }``
"""
new_tally = {}
#if any(isinstance(play.event, te) for te in self.trigger_event_types):
... |
def reject_source(ident, comment):
'''Reject a source for automatic harvesting'''
source = get_source(ident)
source.validation.on = datetime.now()
source.validation.comment = comment
source.validation.state = VALIDATION_REFUSED
if current_user.is_authenticated:
source.validation.by = cur... | def function[reject_source, parameter[ident, comment]]:
constant[Reject a source for automatic harvesting]
variable[source] assign[=] call[name[get_source], parameter[name[ident]]]
name[source].validation.on assign[=] call[name[datetime].now, parameter[]]
name[source].validation.comment ... | keyword[def] identifier[reject_source] ( identifier[ident] , identifier[comment] ):
literal[string]
identifier[source] = identifier[get_source] ( identifier[ident] )
identifier[source] . identifier[validation] . identifier[on] = identifier[datetime] . identifier[now] ()
identifier[source] . ident... | def reject_source(ident, comment):
"""Reject a source for automatic harvesting"""
source = get_source(ident)
source.validation.on = datetime.now()
source.validation.comment = comment
source.validation.state = VALIDATION_REFUSED
if current_user.is_authenticated:
source.validation.by = cur... |
def expandService(service_element):
"""Take a service element and expand it into an iterator of:
([type_uri], uri, service_element)
"""
uris = sortedURIs(service_element)
if not uris:
uris = [None]
expanded = []
for uri in uris:
type_uris = getTypeURIs(service_element)
... | def function[expandService, parameter[service_element]]:
constant[Take a service element and expand it into an iterator of:
([type_uri], uri, service_element)
]
variable[uris] assign[=] call[name[sortedURIs], parameter[name[service_element]]]
if <ast.UnaryOp object at 0x7da18dc07af0> beg... | keyword[def] identifier[expandService] ( identifier[service_element] ):
literal[string]
identifier[uris] = identifier[sortedURIs] ( identifier[service_element] )
keyword[if] keyword[not] identifier[uris] :
identifier[uris] =[ keyword[None] ]
identifier[expanded] =[]
keyword[for] ... | def expandService(service_element):
"""Take a service element and expand it into an iterator of:
([type_uri], uri, service_element)
"""
uris = sortedURIs(service_element)
if not uris:
uris = [None] # depends on [control=['if'], data=[]]
expanded = []
for uri in uris:
type_ur... |
def euler_angles(self):
""":obj:`tuple` of float: The three euler angles for the rotation.
"""
q_wxyz = self.quaternion
q_xyzw = np.roll(q_wxyz, -1)
return transformations.euler_from_quaternion(q_xyzw) | def function[euler_angles, parameter[self]]:
constant[:obj:`tuple` of float: The three euler angles for the rotation.
]
variable[q_wxyz] assign[=] name[self].quaternion
variable[q_xyzw] assign[=] call[name[np].roll, parameter[name[q_wxyz], <ast.UnaryOp object at 0x7da1b12b4be0>]]
ret... | keyword[def] identifier[euler_angles] ( identifier[self] ):
literal[string]
identifier[q_wxyz] = identifier[self] . identifier[quaternion]
identifier[q_xyzw] = identifier[np] . identifier[roll] ( identifier[q_wxyz] ,- literal[int] )
keyword[return] identifier[transformations] . ... | def euler_angles(self):
""":obj:`tuple` of float: The three euler angles for the rotation.
"""
q_wxyz = self.quaternion
q_xyzw = np.roll(q_wxyz, -1)
return transformations.euler_from_quaternion(q_xyzw) |
def plot_survival(self,
on,
how="os",
survival_units="Days",
strata=None,
ax=None,
ci_show=False,
with_condition_color="#B38600",
no_condition_c... | def function[plot_survival, parameter[self, on, how, survival_units, strata, ax, ci_show, with_condition_color, no_condition_color, with_condition_label, no_condition_label, color_map, label_map, color_palette, threshold]]:
constant[Plot a Kaplan Meier survival curve by splitting the cohort into two groups
... | keyword[def] identifier[plot_survival] ( identifier[self] ,
identifier[on] ,
identifier[how] = literal[string] ,
identifier[survival_units] = literal[string] ,
identifier[strata] = keyword[None] ,
identifier[ax] = keyword[None] ,
identifier[ci_show] = keyword[False] ,
identifier[with_condition_color] = literal... | def plot_survival(self, on, how='os', survival_units='Days', strata=None, ax=None, ci_show=False, with_condition_color='#B38600', no_condition_color='#A941AC', with_condition_label=None, no_condition_label=None, color_map=None, label_map=None, color_palette='Set2', threshold=None, **kwargs):
"""Plot a Kaplan Meier ... |
def change_cell(self, x, y, ch, fg, bg):
"""Change cell in position (x;y).
"""
self.console.draw_char(x, y, ch, fg, bg) | def function[change_cell, parameter[self, x, y, ch, fg, bg]]:
constant[Change cell in position (x;y).
]
call[name[self].console.draw_char, parameter[name[x], name[y], name[ch], name[fg], name[bg]]] | keyword[def] identifier[change_cell] ( identifier[self] , identifier[x] , identifier[y] , identifier[ch] , identifier[fg] , identifier[bg] ):
literal[string]
identifier[self] . identifier[console] . identifier[draw_char] ( identifier[x] , identifier[y] , identifier[ch] , identifier[fg] , identifier... | def change_cell(self, x, y, ch, fg, bg):
"""Change cell in position (x;y).
"""
self.console.draw_char(x, y, ch, fg, bg) |
def _emit_internal(self, sid, event, data, namespace=None, id=None):
"""Send a message to a client."""
if six.PY2 and not self.binary:
binary = False # pragma: nocover
else:
binary = None
# tuples are expanded to multiple arguments, everything else is sent
... | def function[_emit_internal, parameter[self, sid, event, data, namespace, id]]:
constant[Send a message to a client.]
if <ast.BoolOp object at 0x7da1b21ba290> begin[:]
variable[binary] assign[=] constant[False]
if call[name[isinstance], parameter[name[data], name[tuple]]] begin[:... | keyword[def] identifier[_emit_internal] ( identifier[self] , identifier[sid] , identifier[event] , identifier[data] , identifier[namespace] = keyword[None] , identifier[id] = keyword[None] ):
literal[string]
keyword[if] identifier[six] . identifier[PY2] keyword[and] keyword[not] identifier[self... | def _emit_internal(self, sid, event, data, namespace=None, id=None):
"""Send a message to a client."""
if six.PY2 and (not self.binary):
binary = False # pragma: nocover # depends on [control=['if'], data=[]]
else:
binary = None
# tuples are expanded to multiple arguments, everything e... |
def routeByMonthAbbr(self, request, year, monthAbbr):
"""Route a request with a month abbreviation to the monthly view."""
month = (DatePictures['Mon'].index(monthAbbr.lower()) // 4) + 1
return self.serveMonth(request, year, month) | def function[routeByMonthAbbr, parameter[self, request, year, monthAbbr]]:
constant[Route a request with a month abbreviation to the monthly view.]
variable[month] assign[=] binary_operation[binary_operation[call[call[name[DatePictures]][constant[Mon]].index, parameter[call[name[monthAbbr].lower, parame... | keyword[def] identifier[routeByMonthAbbr] ( identifier[self] , identifier[request] , identifier[year] , identifier[monthAbbr] ):
literal[string]
identifier[month] =( identifier[DatePictures] [ literal[string] ]. identifier[index] ( identifier[monthAbbr] . identifier[lower] ())// literal[int] )+ lit... | def routeByMonthAbbr(self, request, year, monthAbbr):
"""Route a request with a month abbreviation to the monthly view."""
month = DatePictures['Mon'].index(monthAbbr.lower()) // 4 + 1
return self.serveMonth(request, year, month) |
def _extents(self):
"""
A (cx, cy) 2-tuple representing the effective rendering area for text
within this text frame when margins are taken into account.
"""
return (
self._parent.width - self.margin_left - self.margin_right,
self._parent.height - self.mar... | def function[_extents, parameter[self]]:
constant[
A (cx, cy) 2-tuple representing the effective rendering area for text
within this text frame when margins are taken into account.
]
return[tuple[[<ast.BinOp object at 0x7da20c6ab8b0>, <ast.BinOp object at 0x7da20c6a9b40>]]] | keyword[def] identifier[_extents] ( identifier[self] ):
literal[string]
keyword[return] (
identifier[self] . identifier[_parent] . identifier[width] - identifier[self] . identifier[margin_left] - identifier[self] . identifier[margin_right] ,
identifier[self] . identifier[_parent] ... | def _extents(self):
"""
A (cx, cy) 2-tuple representing the effective rendering area for text
within this text frame when margins are taken into account.
"""
return (self._parent.width - self.margin_left - self.margin_right, self._parent.height - self.margin_top - self.margin_bottom) |
def _batch_gather_with_broadcast(params, indices, axis):
"""Like batch_gather, but broadcasts to the left of axis."""
# batch_gather assumes...
# params.shape = [A1,...,AN, B1,...,BM]
# indices.shape = [A1,...,AN, C]
# which gives output of shape
# [A1,...,AN, C, B1,...,BM]
# Here w... | def function[_batch_gather_with_broadcast, parameter[params, indices, axis]]:
constant[Like batch_gather, but broadcasts to the left of axis.]
variable[leading_bcast_shape] assign[=] call[name[tf].broadcast_dynamic_shape, parameter[call[call[name[tf].shape, parameter[]]][<ast.Slice object at 0x7da1b03e3... | keyword[def] identifier[_batch_gather_with_broadcast] ( identifier[params] , identifier[indices] , identifier[axis] ):
literal[string]
identifier[leading_bcast_shape] = identifier[tf] . identifier[broadcast_dynamic_shape] (
identifier[tf] . identifier[shape] ( identifier... | def _batch_gather_with_broadcast(params, indices, axis):
"""Like batch_gather, but broadcasts to the left of axis."""
# batch_gather assumes...
# params.shape = [A1,...,AN, B1,...,BM]
# indices.shape = [A1,...,AN, C]
# which gives output of shape
# [A1,...,AN, C, B1,...,BM... |
def get_library_name(database='Human'):
"""return enrichr active enrichr library name.
:param str database: Select one from { 'Human', 'Mouse', 'Yeast', 'Fly', 'Fish', 'Worm' }
"""
# make a get request to get the gmt names and meta data from Enrichr
# old code
# response = requests.get(... | def function[get_library_name, parameter[database]]:
constant[return enrichr active enrichr library name.
:param str database: Select one from { 'Human', 'Mouse', 'Yeast', 'Fly', 'Fish', 'Worm' }
]
if compare[name[database] <ast.NotIn object at 0x7da2590d7190> list[[<ast.Constant object a... | keyword[def] identifier[get_library_name] ( identifier[database] = literal[string] ):
literal[string]
keyword[if] identifier[database] keyword[not] keyword[in] [ literal[string] , literal[string] , literal[string] , literal[string] , literal[str... | def get_library_name(database='Human'):
"""return enrichr active enrichr library name.
:param str database: Select one from { 'Human', 'Mouse', 'Yeast', 'Fly', 'Fish', 'Worm' }
"""
# make a get request to get the gmt names and meta data from Enrichr
# old code
# response = requests.get('h... |
def parse(self):
"""
Parse the vmstat file
:return: status of the metric parse
"""
file_status = True
for input_file in self.infile_list:
file_status = file_status and naarad.utils.is_valid_file(input_file)
if not file_status:
return False
status = True
data = {} # s... | def function[parse, parameter[self]]:
constant[
Parse the vmstat file
:return: status of the metric parse
]
variable[file_status] assign[=] constant[True]
for taget[name[input_file]] in starred[name[self].infile_list] begin[:]
variable[file_status] assign[=] <ast.Bool... | keyword[def] identifier[parse] ( identifier[self] ):
literal[string]
identifier[file_status] = keyword[True]
keyword[for] identifier[input_file] keyword[in] identifier[self] . identifier[infile_list] :
identifier[file_status] = identifier[file_status] keyword[and] identifier[naarad] . ide... | def parse(self):
"""
Parse the vmstat file
:return: status of the metric parse
"""
file_status = True
for input_file in self.infile_list:
file_status = file_status and naarad.utils.is_valid_file(input_file)
if not file_status:
return False # depends on [control=['if'... |
def remove_role_from_user(self, user, role):
"""Removes a role from a user.
:param user: The user to manipulate
:param role: The role to remove from the user
"""
rv = False
user, role = self._prepare_role_modify_args(user, role)
if role in user.roles:
... | def function[remove_role_from_user, parameter[self, user, role]]:
constant[Removes a role from a user.
:param user: The user to manipulate
:param role: The role to remove from the user
]
variable[rv] assign[=] constant[False]
<ast.Tuple object at 0x7da18fe91870> assign[=... | keyword[def] identifier[remove_role_from_user] ( identifier[self] , identifier[user] , identifier[role] ):
literal[string]
identifier[rv] = keyword[False]
identifier[user] , identifier[role] = identifier[self] . identifier[_prepare_role_modify_args] ( identifier[user] , identifier[role] )... | def remove_role_from_user(self, user, role):
"""Removes a role from a user.
:param user: The user to manipulate
:param role: The role to remove from the user
"""
rv = False
(user, role) = self._prepare_role_modify_args(user, role)
if role in user.roles:
rv = True
... |
def set_fft_params(func):
"""Decorate a method to automatically convert quantities to samples
"""
@wraps(func)
def wrapped_func(series, method_func, *args, **kwargs):
"""Wrap function to normalize FFT params before execution
"""
if isinstance(series, tuple):
data = se... | def function[set_fft_params, parameter[func]]:
constant[Decorate a method to automatically convert quantities to samples
]
def function[wrapped_func, parameter[series, method_func]]:
constant[Wrap function to normalize FFT params before execution
]
if call[nam... | keyword[def] identifier[set_fft_params] ( identifier[func] ):
literal[string]
@ identifier[wraps] ( identifier[func] )
keyword[def] identifier[wrapped_func] ( identifier[series] , identifier[method_func] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] iden... | def set_fft_params(func):
"""Decorate a method to automatically convert quantities to samples
"""
@wraps(func)
def wrapped_func(series, method_func, *args, **kwargs):
"""Wrap function to normalize FFT params before execution
"""
if isinstance(series, tuple):
data = s... |
def nlargest(n, iterable, key=None):
"""Find the n largest elements in a dataset.
Equivalent to: sorted(iterable, key=key, reverse=True)[:n]
"""
# Short-cut for n==1 is to use max()
if n == 1:
it = iter(iterable)
sentinel = object()
if key is None:
result = max... | def function[nlargest, parameter[n, iterable, key]]:
constant[Find the n largest elements in a dataset.
Equivalent to: sorted(iterable, key=key, reverse=True)[:n]
]
if compare[name[n] equal[==] constant[1]] begin[:]
variable[it] assign[=] call[name[iter], parameter[name[iterabl... | keyword[def] identifier[nlargest] ( identifier[n] , identifier[iterable] , identifier[key] = keyword[None] ):
literal[string]
keyword[if] identifier[n] == literal[int] :
identifier[it] = identifier[iter] ( identifier[iterable] )
identifier[sentinel] = identifier[object] ()
... | def nlargest(n, iterable, key=None):
"""Find the n largest elements in a dataset.
Equivalent to: sorted(iterable, key=key, reverse=True)[:n]
"""
# Short-cut for n==1 is to use max()
if n == 1:
it = iter(iterable)
sentinel = object()
if key is None:
result = max(... |
def _parse_response(resp):
""" Get xmlrpc response from scgi response
"""
# Assume they care for standards and send us CRLF (not just LF)
try:
headers, payload = resp.split("\r\n\r\n", 1)
except (TypeError, ValueError) as exc:
raise SCGIException("No header delimiter in SCGI response... | def function[_parse_response, parameter[resp]]:
constant[ Get xmlrpc response from scgi response
]
<ast.Try object at 0x7da18bcc9720>
variable[headers] assign[=] call[name[_parse_headers], parameter[name[headers]]]
variable[clen] assign[=] call[name[headers].get, parameter[constant[Conte... | keyword[def] identifier[_parse_response] ( identifier[resp] ):
literal[string]
keyword[try] :
identifier[headers] , identifier[payload] = identifier[resp] . identifier[split] ( literal[string] , literal[int] )
keyword[except] ( identifier[TypeError] , identifier[ValueError] ) keyword[as]... | def _parse_response(resp):
""" Get xmlrpc response from scgi response
"""
# Assume they care for standards and send us CRLF (not just LF)
try:
(headers, payload) = resp.split('\r\n\r\n', 1) # depends on [control=['try'], data=[]]
except (TypeError, ValueError) as exc:
raise SCGIExce... |
def sessions(status, access_key, id_only, all):
'''
List and manage compute sessions.
'''
fields = [
('Session ID', 'sess_id'),
]
with Session() as session:
if is_admin(session):
fields.append(('Owner', 'access_key'))
if not id_only:
fields.extend([
... | def function[sessions, parameter[status, access_key, id_only, all]]:
constant[
List and manage compute sessions.
]
variable[fields] assign[=] list[[<ast.Tuple object at 0x7da207f9aec0>]]
with call[name[Session], parameter[]] begin[:]
if call[name[is_admin], parameter[name... | keyword[def] identifier[sessions] ( identifier[status] , identifier[access_key] , identifier[id_only] , identifier[all] ):
literal[string]
identifier[fields] =[
( literal[string] , literal[string] ),
]
keyword[with] identifier[Session] () keyword[as] identifier[session] :
keyword[if... | def sessions(status, access_key, id_only, all):
"""
List and manage compute sessions.
"""
fields = [('Session ID', 'sess_id')]
with Session() as session:
if is_admin(session):
fields.append(('Owner', 'access_key')) # depends on [control=['if'], data=[]] # depends on [control=['... |
def cosmological_quantity_from_redshift(z, quantity, strip_unit=True,
**kwargs):
r"""Returns the value of a cosmological quantity (e.g., age) at a redshift.
Parameters
----------
z : float
The redshift.
quantity : str
The name of the quantity ... | def function[cosmological_quantity_from_redshift, parameter[z, quantity, strip_unit]]:
constant[Returns the value of a cosmological quantity (e.g., age) at a redshift.
Parameters
----------
z : float
The redshift.
quantity : str
The name of the quantity to get. The name may be a... | keyword[def] identifier[cosmological_quantity_from_redshift] ( identifier[z] , identifier[quantity] , identifier[strip_unit] = keyword[True] ,
** identifier[kwargs] ):
literal[string]
identifier[cosmology] = identifier[get_cosmology] (** identifier[kwargs] )
identifier[val] = identifier[getattr] ( ide... | def cosmological_quantity_from_redshift(z, quantity, strip_unit=True, **kwargs):
"""Returns the value of a cosmological quantity (e.g., age) at a redshift.
Parameters
----------
z : float
The redshift.
quantity : str
The name of the quantity to get. The name may be any attribute of
... |
def message_user(self, username, domain, subject, message):
"""Currently use send_message_chat and discard subject, because headline messages are not
stored by mod_offline."""
kwargs = {
'body': message,
'from': domain,
'to': '%s@%s' % (username, domain),
... | def function[message_user, parameter[self, username, domain, subject, message]]:
constant[Currently use send_message_chat and discard subject, because headline messages are not
stored by mod_offline.]
variable[kwargs] assign[=] dictionary[[<ast.Constant object at 0x7da1b0b10eb0>, <ast.Constant o... | keyword[def] identifier[message_user] ( identifier[self] , identifier[username] , identifier[domain] , identifier[subject] , identifier[message] ):
literal[string]
identifier[kwargs] ={
literal[string] : identifier[message] ,
literal[string] : identifier[domain] ,
litera... | def message_user(self, username, domain, subject, message):
"""Currently use send_message_chat and discard subject, because headline messages are not
stored by mod_offline."""
kwargs = {'body': message, 'from': domain, 'to': '%s@%s' % (username, domain)}
if self.api_version <= (14, 7):
# TOD... |
def create_view(self, query_criteria=None, uid='_all_users'):
'''
a method to add a view to a design document of a uid
:param query_criteria: dictionary with valid jsonmodel query criteria
:param uid: [optional] string with uid of design document to update
... | def function[create_view, parameter[self, query_criteria, uid]]:
constant[
a method to add a view to a design document of a uid
:param query_criteria: dictionary with valid jsonmodel query criteria
:param uid: [optional] string with uid of design document to update
... | keyword[def] identifier[create_view] ( identifier[self] , identifier[query_criteria] = keyword[None] , identifier[uid] = literal[string] ):
literal[string]
identifier[title] = literal[string] % identifier[self] . identifier[__class__] . identifier[__name__]
... | def create_view(self, query_criteria=None, uid='_all_users'):
"""
a method to add a view to a design document of a uid
:param query_criteria: dictionary with valid jsonmodel query criteria
:param uid: [optional] string with uid of design document to update
:return:... |
def tx_hash( cls, tx ):
"""
Calculate the hash of a transction structure given by bitcoind
"""
tx_hex = bits.btc_bitcoind_tx_serialize( tx )
tx_hash = hashing.bin_double_sha256(tx_hex.decode('hex'))[::-1].encode('hex')
return tx_hash | def function[tx_hash, parameter[cls, tx]]:
constant[
Calculate the hash of a transction structure given by bitcoind
]
variable[tx_hex] assign[=] call[name[bits].btc_bitcoind_tx_serialize, parameter[name[tx]]]
variable[tx_hash] assign[=] call[call[call[name[hashing].bin_double_sha... | keyword[def] identifier[tx_hash] ( identifier[cls] , identifier[tx] ):
literal[string]
identifier[tx_hex] = identifier[bits] . identifier[btc_bitcoind_tx_serialize] ( identifier[tx] )
identifier[tx_hash] = identifier[hashing] . identifier[bin_double_sha256] ( identifier[tx_hex] . identifie... | def tx_hash(cls, tx):
"""
Calculate the hash of a transction structure given by bitcoind
"""
tx_hex = bits.btc_bitcoind_tx_serialize(tx)
tx_hash = hashing.bin_double_sha256(tx_hex.decode('hex'))[::-1].encode('hex')
return tx_hash |
def _from_dict(cls, _dict):
"""Initialize a ListCollectionFieldsResponse object from a json dictionary."""
args = {}
if 'fields' in _dict:
args['fields'] = [
Field._from_dict(x) for x in (_dict.get('fields'))
]
return cls(**args) | def function[_from_dict, parameter[cls, _dict]]:
constant[Initialize a ListCollectionFieldsResponse object from a json dictionary.]
variable[args] assign[=] dictionary[[], []]
if compare[constant[fields] in name[_dict]] begin[:]
call[name[args]][constant[fields]] assign[=] <ast.L... | keyword[def] identifier[_from_dict] ( identifier[cls] , identifier[_dict] ):
literal[string]
identifier[args] ={}
keyword[if] literal[string] keyword[in] identifier[_dict] :
identifier[args] [ literal[string] ]=[
identifier[Field] . identifier[_from_dict] ( ide... | def _from_dict(cls, _dict):
"""Initialize a ListCollectionFieldsResponse object from a json dictionary."""
args = {}
if 'fields' in _dict:
args['fields'] = [Field._from_dict(x) for x in _dict.get('fields')] # depends on [control=['if'], data=['_dict']]
return cls(**args) |
def check_py_version():
"""Check if a propper Python version is used."""
try:
if sys.version_info >= (2, 7):
return
except:
pass
print(" ")
print(" ERROR - memtop needs python version at least 2.7")
print(("Chances are that you can install newer version from your "
... | def function[check_py_version, parameter[]]:
constant[Check if a propper Python version is used.]
<ast.Try object at 0x7da1b10a4100>
call[name[print], parameter[constant[ ]]]
call[name[print], parameter[constant[ ERROR - memtop needs python version at least 2.7]]]
call[name[print], p... | keyword[def] identifier[check_py_version] ():
literal[string]
keyword[try] :
keyword[if] identifier[sys] . identifier[version_info] >=( literal[int] , literal[int] ):
keyword[return]
keyword[except] :
keyword[pass]
identifier[print] ( literal[string] )
ident... | def check_py_version():
"""Check if a propper Python version is used."""
try:
if sys.version_info >= (2, 7):
return # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]]
except:
pass # depends on [control=['except'], data=[]]
print(' ')
print('... |
def save_task_info(self, res, mem_gb=0):
"""
:param self: an object with attributes .hdf5, .argnames, .sent
:parent res: a :class:`Result` object
:param mem_gb: memory consumption at the saving time (optional)
"""
mon = res.mon
name = mon.operation[6:] # strip 'total '
if self.hdf5:
... | def function[save_task_info, parameter[self, res, mem_gb]]:
constant[
:param self: an object with attributes .hdf5, .argnames, .sent
:parent res: a :class:`Result` object
:param mem_gb: memory consumption at the saving time (optional)
]
variable[mon] assign[=] name[res].mon
varia... | keyword[def] identifier[save_task_info] ( identifier[self] , identifier[res] , identifier[mem_gb] = literal[int] ):
literal[string]
identifier[mon] = identifier[res] . identifier[mon]
identifier[name] = identifier[mon] . identifier[operation] [ literal[int] :]
keyword[if] identifier[self] . ide... | def save_task_info(self, res, mem_gb=0):
"""
:param self: an object with attributes .hdf5, .argnames, .sent
:parent res: a :class:`Result` object
:param mem_gb: memory consumption at the saving time (optional)
"""
mon = res.mon
name = mon.operation[6:] # strip 'total '
if self.hdf5:
... |
def is_redundant_multiplicon(self, value):
""" Returns True if the passed multiplicon ID is redundant, False
otherwise.
- value, (int) multiplicon ID
"""
if not hasattr(self, '_redundant_multiplicon_cache'):
sql = '''SELECT id FROM multiplicons WHERE is_redun... | def function[is_redundant_multiplicon, parameter[self, value]]:
constant[ Returns True if the passed multiplicon ID is redundant, False
otherwise.
- value, (int) multiplicon ID
]
if <ast.UnaryOp object at 0x7da1b0ae1000> begin[:]
variable[sql] assign[=] c... | keyword[def] identifier[is_redundant_multiplicon] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[sql] = literal[string]
identifier[cur] = identifier[self] . identi... | def is_redundant_multiplicon(self, value):
""" Returns True if the passed multiplicon ID is redundant, False
otherwise.
- value, (int) multiplicon ID
"""
if not hasattr(self, '_redundant_multiplicon_cache'):
sql = 'SELECT id FROM multiplicons WHERE is_redundant="-1"'
... |
def _ConvertManagedPropertyType(self, propType):
"""
Convert vmodl.reflect.DynamicTypeManager.PropertyTypeInfo to pyVmomi
managed property definition
"""
if propType:
name = propType.name
version = propType.version
aType = propType.type
flags = self._Con... | def function[_ConvertManagedPropertyType, parameter[self, propType]]:
constant[
Convert vmodl.reflect.DynamicTypeManager.PropertyTypeInfo to pyVmomi
managed property definition
]
if name[propType] begin[:]
variable[name] assign[=] name[propType].name
var... | keyword[def] identifier[_ConvertManagedPropertyType] ( identifier[self] , identifier[propType] ):
literal[string]
keyword[if] identifier[propType] :
identifier[name] = identifier[propType] . identifier[name]
identifier[version] = identifier[propType] . identifier[version]
... | def _ConvertManagedPropertyType(self, propType):
"""
Convert vmodl.reflect.DynamicTypeManager.PropertyTypeInfo to pyVmomi
managed property definition
"""
if propType:
name = propType.name
version = propType.version
aType = propType.type
flags = self._ConvertAnno... |
def reverse_timezone(self, query, timeout=DEFAULT_SENTINEL):
"""
Find the timezone for a point in `query`.
GeoNames always returns a timezone: if the point being queried
doesn't have an assigned Olson timezone id, a ``pytz.FixedOffset``
timezone is used to produce the :class:`ge... | def function[reverse_timezone, parameter[self, query, timeout]]:
constant[
Find the timezone for a point in `query`.
GeoNames always returns a timezone: if the point being queried
doesn't have an assigned Olson timezone id, a ``pytz.FixedOffset``
timezone is used to produce the ... | keyword[def] identifier[reverse_timezone] ( identifier[self] , identifier[query] , identifier[timeout] = identifier[DEFAULT_SENTINEL] ):
literal[string]
identifier[ensure_pytz_is_installed] ()
keyword[try] :
identifier[lat] , identifier[lng] = identifier[self] . identifier[_c... | def reverse_timezone(self, query, timeout=DEFAULT_SENTINEL):
"""
Find the timezone for a point in `query`.
GeoNames always returns a timezone: if the point being queried
doesn't have an assigned Olson timezone id, a ``pytz.FixedOffset``
timezone is used to produce the :class:`geopy.... |
def add_transcription(self, gene: Gene, rna: Union[Rna, MicroRna]) -> str:
"""Add a transcription relation from a gene to an RNA or miRNA node.
:param gene: A gene node
:param rna: An RNA or microRNA node
"""
return self.add_unqualified_edge(gene, rna, TRANSCRIBED_TO) | def function[add_transcription, parameter[self, gene, rna]]:
constant[Add a transcription relation from a gene to an RNA or miRNA node.
:param gene: A gene node
:param rna: An RNA or microRNA node
]
return[call[name[self].add_unqualified_edge, parameter[name[gene], name[rna], name[T... | keyword[def] identifier[add_transcription] ( identifier[self] , identifier[gene] : identifier[Gene] , identifier[rna] : identifier[Union] [ identifier[Rna] , identifier[MicroRna] ])-> identifier[str] :
literal[string]
keyword[return] identifier[self] . identifier[add_unqualified_edge] ( identifier... | def add_transcription(self, gene: Gene, rna: Union[Rna, MicroRna]) -> str:
"""Add a transcription relation from a gene to an RNA or miRNA node.
:param gene: A gene node
:param rna: An RNA or microRNA node
"""
return self.add_unqualified_edge(gene, rna, TRANSCRIBED_TO) |
def fetch_and_parse(method, uri, params_prefix=None, **params):
"""Fetch the given uri and return python dictionary with parsed data-types."""
response = fetch(method, uri, params_prefix, **params)
return _parse(json.loads(response.text)) | def function[fetch_and_parse, parameter[method, uri, params_prefix]]:
constant[Fetch the given uri and return python dictionary with parsed data-types.]
variable[response] assign[=] call[name[fetch], parameter[name[method], name[uri], name[params_prefix]]]
return[call[name[_parse], parameter[call[na... | keyword[def] identifier[fetch_and_parse] ( identifier[method] , identifier[uri] , identifier[params_prefix] = keyword[None] ,** identifier[params] ):
literal[string]
identifier[response] = identifier[fetch] ( identifier[method] , identifier[uri] , identifier[params_prefix] ,** identifier[params] )
key... | def fetch_and_parse(method, uri, params_prefix=None, **params):
"""Fetch the given uri and return python dictionary with parsed data-types."""
response = fetch(method, uri, params_prefix, **params)
return _parse(json.loads(response.text)) |
def memoize(func):
""" Memoization decorator for a function taking one or more arguments. """
class Memodict(dict):
""" just a dict"""
def __getitem__(self, *key):
return dict.__getitem__(self, key)
def __missing__(self, key):
""" this makes it faster """
... | def function[memoize, parameter[func]]:
constant[ Memoization decorator for a function taking one or more arguments. ]
class class[Memodict, parameter[]] begin[:]
constant[ just a dict]
def function[__getitem__, parameter[self]]:
return[call[name[dict].__getit... | keyword[def] identifier[memoize] ( identifier[func] ):
literal[string]
keyword[class] identifier[Memodict] ( identifier[dict] ):
literal[string]
keyword[def] identifier[__getitem__] ( identifier[self] ,* identifier[key] ):
keyword[return] identifier[dict] . identifier[__g... | def memoize(func):
""" Memoization decorator for a function taking one or more arguments. """
class Memodict(dict):
""" just a dict"""
def __getitem__(self, *key):
return dict.__getitem__(self, key)
def __missing__(self, key):
""" this makes it faster """
... |
def _set_pseudotime(self):
"""Return pseudotime with respect to root point.
"""
self.pseudotime = self.distances_dpt[self.iroot].copy()
self.pseudotime /= np.max(self.pseudotime[self.pseudotime < np.inf]) | def function[_set_pseudotime, parameter[self]]:
constant[Return pseudotime with respect to root point.
]
name[self].pseudotime assign[=] call[call[name[self].distances_dpt][name[self].iroot].copy, parameter[]]
<ast.AugAssign object at 0x7da18f58faf0> | keyword[def] identifier[_set_pseudotime] ( identifier[self] ):
literal[string]
identifier[self] . identifier[pseudotime] = identifier[self] . identifier[distances_dpt] [ identifier[self] . identifier[iroot] ]. identifier[copy] ()
identifier[self] . identifier[pseudotime] /= identifier[np] ... | def _set_pseudotime(self):
"""Return pseudotime with respect to root point.
"""
self.pseudotime = self.distances_dpt[self.iroot].copy()
self.pseudotime /= np.max(self.pseudotime[self.pseudotime < np.inf]) |
def resetCanvasDimensions(self, windowHeight, windowWidth):
'sets total available canvas dimensions to (windowHeight, windowWidth) (in char cells)'
self.plotwidth = windowWidth*2
self.plotheight = (windowHeight-1)*4 # exclude status line
# pixels[y][x] = { attr: list(rows), ... }
... | def function[resetCanvasDimensions, parameter[self, windowHeight, windowWidth]]:
constant[sets total available canvas dimensions to (windowHeight, windowWidth) (in char cells)]
name[self].plotwidth assign[=] binary_operation[name[windowWidth] * constant[2]]
name[self].plotheight assign[=] binary... | keyword[def] identifier[resetCanvasDimensions] ( identifier[self] , identifier[windowHeight] , identifier[windowWidth] ):
literal[string]
identifier[self] . identifier[plotwidth] = identifier[windowWidth] * literal[int]
identifier[self] . identifier[plotheight] =( identifier[windowHeight]... | def resetCanvasDimensions(self, windowHeight, windowWidth):
"""sets total available canvas dimensions to (windowHeight, windowWidth) (in char cells)"""
self.plotwidth = windowWidth * 2
self.plotheight = (windowHeight - 1) * 4 # exclude status line
# pixels[y][x] = { attr: list(rows), ... }
self.pix... |
def verify_words(self):
"""Verify the fields source, imagery_used and comment of the changeset
for some suspect words.
"""
if self.comment:
if find_words(self.comment, self.suspect_words, self.excluded_words):
self.label_suspicious('suspect_word')
if ... | def function[verify_words, parameter[self]]:
constant[Verify the fields source, imagery_used and comment of the changeset
for some suspect words.
]
if name[self].comment begin[:]
if call[name[find_words], parameter[name[self].comment, name[self].suspect_words, name[self].... | keyword[def] identifier[verify_words] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[comment] :
keyword[if] identifier[find_words] ( identifier[self] . identifier[comment] , identifier[self] . identifier[suspect_words] , identifier[self] . identifier[... | def verify_words(self):
"""Verify the fields source, imagery_used and comment of the changeset
for some suspect words.
"""
if self.comment:
if find_words(self.comment, self.suspect_words, self.excluded_words):
self.label_suspicious('suspect_word') # depends on [control=['if'... |
def get_left_ngrams(mention, window=3, attrib="words", n_min=1, n_max=1, lower=True):
"""Get the ngrams within a window to the *left* from the sentence Context.
For higher-arity Candidates, defaults to the *first* argument.
:param mention: The Mention to evaluate. If a candidate is given, default
... | def function[get_left_ngrams, parameter[mention, window, attrib, n_min, n_max, lower]]:
constant[Get the ngrams within a window to the *left* from the sentence Context.
For higher-arity Candidates, defaults to the *first* argument.
:param mention: The Mention to evaluate. If a candidate is given, defa... | keyword[def] identifier[get_left_ngrams] ( identifier[mention] , identifier[window] = literal[int] , identifier[attrib] = literal[string] , identifier[n_min] = literal[int] , identifier[n_max] = literal[int] , identifier[lower] = keyword[True] ):
literal[string]
identifier[span] = identifier[_to_span] ( id... | def get_left_ngrams(mention, window=3, attrib='words', n_min=1, n_max=1, lower=True):
"""Get the ngrams within a window to the *left* from the sentence Context.
For higher-arity Candidates, defaults to the *first* argument.
:param mention: The Mention to evaluate. If a candidate is given, default
... |
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.error('Update {} caused error {}'.format(update, error), extra={"tag": "err"}) | def function[error, parameter[bot, update, error]]:
constant[Log Errors caused by Updates.]
call[name[logger].error, parameter[call[constant[Update {} caused error {}].format, parameter[name[update], name[error]]]]] | keyword[def] identifier[error] ( identifier[bot] , identifier[update] , identifier[error] ):
literal[string]
identifier[logger] . identifier[error] ( literal[string] . identifier[format] ( identifier[update] , identifier[error] ), identifier[extra] ={ literal[string] : literal[string] }) | def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.error('Update {} caused error {}'.format(update, error), extra={'tag': 'err'}) |
def run_via_binary(self, run_command_instance=None, command=None, volumes=None,
additional_opts=None, **kwargs):
"""
create a container using this image and run it in background;
this method is useful to test real user scenarios when users invoke containers using
b... | def function[run_via_binary, parameter[self, run_command_instance, command, volumes, additional_opts]]:
constant[
create a container using this image and run it in background;
this method is useful to test real user scenarios when users invoke containers using
binary
:param run_... | keyword[def] identifier[run_via_binary] ( identifier[self] , identifier[run_command_instance] = keyword[None] , identifier[command] = keyword[None] , identifier[volumes] = keyword[None] ,
identifier[additional_opts] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[logger] . id... | def run_via_binary(self, run_command_instance=None, command=None, volumes=None, additional_opts=None, **kwargs):
"""
create a container using this image and run it in background;
this method is useful to test real user scenarios when users invoke containers using
binary
:param run_c... |
def suggestion_list(inp, options):
"""
Given an invalid input string and a list of valid options, returns a filtered
list of valid options sorted based on their similarity with the input.
"""
options_by_distance = OrderedDict()
input_threshold = len(inp) / 2
for option in options:
... | def function[suggestion_list, parameter[inp, options]]:
constant[
Given an invalid input string and a list of valid options, returns a filtered
list of valid options sorted based on their similarity with the input.
]
variable[options_by_distance] assign[=] call[name[OrderedDict], parameter... | keyword[def] identifier[suggestion_list] ( identifier[inp] , identifier[options] ):
literal[string]
identifier[options_by_distance] = identifier[OrderedDict] ()
identifier[input_threshold] = identifier[len] ( identifier[inp] )/ literal[int]
keyword[for] identifier[option] keyword[in] identif... | def suggestion_list(inp, options):
"""
Given an invalid input string and a list of valid options, returns a filtered
list of valid options sorted based on their similarity with the input.
"""
options_by_distance = OrderedDict()
input_threshold = len(inp) / 2
for option in options:
... |
def getroot(self):
"""Return the root element of the figure.
The root element is a group of elements after stripping the toplevel
``<svg>`` tag.
Returns
-------
GroupElement
All elements of the figure without the ``<svg>`` tag.
"""
if 'class'... | def function[getroot, parameter[self]]:
constant[Return the root element of the figure.
The root element is a group of elements after stripping the toplevel
``<svg>`` tag.
Returns
-------
GroupElement
All elements of the figure without the ``<svg>`` tag.
... | keyword[def] identifier[getroot] ( identifier[self] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[self] . identifier[root] . identifier[attrib] :
identifier[attrib] ={ literal[string] : identifier[self] . identifier[root] . identifier[attrib] [ literal[string... | def getroot(self):
"""Return the root element of the figure.
The root element is a group of elements after stripping the toplevel
``<svg>`` tag.
Returns
-------
GroupElement
All elements of the figure without the ``<svg>`` tag.
"""
if 'class' in self... |
def parseFASTAFilteringCommandLineOptions(args, reads):
"""
Examine parsed FASTA filtering command-line options and return filtered
reads.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@param reads: A C{Reads} instance to filter.
@return: The fi... | def function[parseFASTAFilteringCommandLineOptions, parameter[args, reads]]:
constant[
Examine parsed FASTA filtering command-line options and return filtered
reads.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@param reads: A C{Reads} instance... | keyword[def] identifier[parseFASTAFilteringCommandLineOptions] ( identifier[args] , identifier[reads] ):
literal[string]
identifier[keepSequences] =(
identifier[parseRangeString] ( identifier[args] . identifier[keepSequences] , identifier[convertToZeroBased] = keyword[True] )
keyword[if] identif... | def parseFASTAFilteringCommandLineOptions(args, reads):
"""
Examine parsed FASTA filtering command-line options and return filtered
reads.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@param reads: A C{Reads} instance to filter.
@return: The fi... |
async def get_dnssec_validation(cls) -> DNSSEC:
"""Enable DNSSEC validation of upstream zones.
Only used when MAAS is running its own DNS server. This value is used
as the value of 'dnssec_validation' in the DNS server config.
"""
data = await cls.get_config("dnssec_validation")... | <ast.AsyncFunctionDef object at 0x7da20c992230> | keyword[async] keyword[def] identifier[get_dnssec_validation] ( identifier[cls] )-> identifier[DNSSEC] :
literal[string]
identifier[data] = keyword[await] identifier[cls] . identifier[get_config] ( literal[string] )
keyword[return] identifier[cls] . identifier[DNSSEC] . identifier[looku... | async def get_dnssec_validation(cls) -> DNSSEC:
"""Enable DNSSEC validation of upstream zones.
Only used when MAAS is running its own DNS server. This value is used
as the value of 'dnssec_validation' in the DNS server config.
"""
data = await cls.get_config('dnssec_validation')
ret... |
def set_right_margin(self, right_margin):
"""
Set the right margin of the menu. This will determine the number of spaces between the right edge of the
screen and the right menu border.
:param right_margin: an integer value
"""
self.__header.style.margins.right = right_ma... | def function[set_right_margin, parameter[self, right_margin]]:
constant[
Set the right margin of the menu. This will determine the number of spaces between the right edge of the
screen and the right menu border.
:param right_margin: an integer value
]
name[self].__header... | keyword[def] identifier[set_right_margin] ( identifier[self] , identifier[right_margin] ):
literal[string]
identifier[self] . identifier[__header] . identifier[style] . identifier[margins] . identifier[right] = identifier[right_margin]
identifier[self] . identifier[__prologue] . identifie... | def set_right_margin(self, right_margin):
"""
Set the right margin of the menu. This will determine the number of spaces between the right edge of the
screen and the right menu border.
:param right_margin: an integer value
"""
self.__header.style.margins.right = right_margin
... |
def make_transformer(self, decompose='svd', decompose_by=50, tsne_kwargs={}):
"""
Creates an internal transformer pipeline to project the data set into
2D space using TSNE, applying an pre-decomposition technique ahead of
embedding if necessary. This method will reset the transformer on ... | def function[make_transformer, parameter[self, decompose, decompose_by, tsne_kwargs]]:
constant[
Creates an internal transformer pipeline to project the data set into
2D space using TSNE, applying an pre-decomposition technique ahead of
embedding if necessary. This method will reset the ... | keyword[def] identifier[make_transformer] ( identifier[self] , identifier[decompose] = literal[string] , identifier[decompose_by] = literal[int] , identifier[tsne_kwargs] ={}):
literal[string]
identifier[decompositions] ={
literal[string] : identifier[TruncatedSVD] ,
... | def make_transformer(self, decompose='svd', decompose_by=50, tsne_kwargs={}):
"""
Creates an internal transformer pipeline to project the data set into
2D space using TSNE, applying an pre-decomposition technique ahead of
embedding if necessary. This method will reset the transformer on the
... |
def column_families(self):
"""List[:class:`~.external_config.BigtableColumnFamily`]: List of
column families to expose in the table schema along with their types.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.tableDefinitions.(key).bigtableOptions... | def function[column_families, parameter[self]]:
constant[List[:class:`~.external_config.BigtableColumnFamily`]: List of
column families to expose in the table schema along with their types.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.tableDefini... | keyword[def] identifier[column_families] ( identifier[self] ):
literal[string]
identifier[prop] = identifier[self] . identifier[_properties] . identifier[get] ( literal[string] ,[])
keyword[return] [ identifier[BigtableColumnFamily] . identifier[from_api_repr] ( identifier[cf] ) keyword[fo... | def column_families(self):
"""List[:class:`~.external_config.BigtableColumnFamily`]: List of
column families to expose in the table schema along with their types.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.tableDefinitions.(key).bigtableOptions.col... |
def extract_view(view, decorators=None):
"""
Extract a view object out of any wrapping decorators.
"""
# http://stackoverflow.com/questions/9222129/python-inspect-getmembers-does-not-return-the-actual-function-when-used-with-dec
if decorators is None:
decorators = []
if getattr(view, 'fu... | def function[extract_view, parameter[view, decorators]]:
constant[
Extract a view object out of any wrapping decorators.
]
if compare[name[decorators] is constant[None]] begin[:]
variable[decorators] assign[=] list[[]]
if compare[call[name[getattr], parameter[name[view], ... | keyword[def] identifier[extract_view] ( identifier[view] , identifier[decorators] = keyword[None] ):
literal[string]
keyword[if] identifier[decorators] keyword[is] keyword[None] :
identifier[decorators] =[]
keyword[if] identifier[getattr] ( identifier[view] , literal[string] , keywor... | def extract_view(view, decorators=None):
"""
Extract a view object out of any wrapping decorators.
"""
# http://stackoverflow.com/questions/9222129/python-inspect-getmembers-does-not-return-the-actual-function-when-used-with-dec
if decorators is None:
decorators = [] # depends on [control=[... |
def device(self, idx):
"""Get a specific GPU device
Args:
idx: index of device
Returns:
NvidiaDevice: single GPU device
"""
class GpuDevice(Structure):
pass
c_nvmlDevice_t = POINTER(GpuDevice)
c_index = c_uint(idx)
... | def function[device, parameter[self, idx]]:
constant[Get a specific GPU device
Args:
idx: index of device
Returns:
NvidiaDevice: single GPU device
]
class class[GpuDevice, parameter[]] begin[:]
pass
variable[c_nvmlDevice_t] assign[=] call... | keyword[def] identifier[device] ( identifier[self] , identifier[idx] ):
literal[string]
keyword[class] identifier[GpuDevice] ( identifier[Structure] ):
keyword[pass]
identifier[c_nvmlDevice_t] = identifier[POINTER] ( identifier[GpuDevice] )
identifier[c_index] = ... | def device(self, idx):
"""Get a specific GPU device
Args:
idx: index of device
Returns:
NvidiaDevice: single GPU device
"""
class GpuDevice(Structure):
pass
c_nvmlDevice_t = POINTER(GpuDevice)
c_index = c_uint(idx)
device = c_nvmlDevice_t()
... |
def removeApplicationManifest(self, pchApplicationManifestFullPath):
"""Removes an application manifest from the list to load when building the list of installed applications."""
fn = self.function_table.removeApplicationManifest
result = fn(pchApplicationManifestFullPath)
return result | def function[removeApplicationManifest, parameter[self, pchApplicationManifestFullPath]]:
constant[Removes an application manifest from the list to load when building the list of installed applications.]
variable[fn] assign[=] name[self].function_table.removeApplicationManifest
variable[result] ... | keyword[def] identifier[removeApplicationManifest] ( identifier[self] , identifier[pchApplicationManifestFullPath] ):
literal[string]
identifier[fn] = identifier[self] . identifier[function_table] . identifier[removeApplicationManifest]
identifier[result] = identifier[fn] ( identifier[pc... | def removeApplicationManifest(self, pchApplicationManifestFullPath):
"""Removes an application manifest from the list to load when building the list of installed applications."""
fn = self.function_table.removeApplicationManifest
result = fn(pchApplicationManifestFullPath)
return result |
def set_server(self, server_pos, key, value):
"""Set the key to the value for the server_pos (position in the list)."""
if zeroconf_tag and self.zeroconf_enable_tag:
self.listener.set_server(server_pos, key, value) | def function[set_server, parameter[self, server_pos, key, value]]:
constant[Set the key to the value for the server_pos (position in the list).]
if <ast.BoolOp object at 0x7da1b1c3d120> begin[:]
call[name[self].listener.set_server, parameter[name[server_pos], name[key], name[value]]] | keyword[def] identifier[set_server] ( identifier[self] , identifier[server_pos] , identifier[key] , identifier[value] ):
literal[string]
keyword[if] identifier[zeroconf_tag] keyword[and] identifier[self] . identifier[zeroconf_enable_tag] :
identifier[self] . identifier[listener] . i... | def set_server(self, server_pos, key, value):
"""Set the key to the value for the server_pos (position in the list)."""
if zeroconf_tag and self.zeroconf_enable_tag:
self.listener.set_server(server_pos, key, value) # depends on [control=['if'], data=[]] |
async def update_bucket(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
bucket: typing.Dict = None,
**kwargs):
"""
Update bucket for user in chat... | <ast.AsyncFunctionDef object at 0x7da1b18450c0> | keyword[async] keyword[def] identifier[update_bucket] ( identifier[self] ,*,
identifier[chat] : identifier[typing] . identifier[Union] [ identifier[str] , identifier[int] , keyword[None] ]= keyword[None] ,
identifier[user] : identifier[typing] . identifier[Union] [ identifier[str] , identifier[int] , keyword[None]... | async def update_bucket(self, *, chat: typing.Union[str, int, None]=None, user: typing.Union[str, int, None]=None, bucket: typing.Dict=None, **kwargs):
"""
Update bucket for user in chat
You can use bucket parameter or|and kwargs.
Chat or user is always required. If one of them is not prov... |
def get_viscosity(medium="CellCarrier", channel_width=20.0, flow_rate=0.16,
temperature=23.0):
"""Returns the viscosity for RT-DC-specific media
Parameters
----------
medium: str
The medium to compute the viscosity for.
One of ["CellCarrier", "CellCarrier B", "water"].... | def function[get_viscosity, parameter[medium, channel_width, flow_rate, temperature]]:
constant[Returns the viscosity for RT-DC-specific media
Parameters
----------
medium: str
The medium to compute the viscosity for.
One of ["CellCarrier", "CellCarrier B", "water"].
channel_wid... | keyword[def] identifier[get_viscosity] ( identifier[medium] = literal[string] , identifier[channel_width] = literal[int] , identifier[flow_rate] = literal[int] ,
identifier[temperature] = literal[int] ):
literal[string]
keyword[if] identifier[medium] . identifier[lower] () keyword[not] keyword[in] [ lit... | def get_viscosity(medium='CellCarrier', channel_width=20.0, flow_rate=0.16, temperature=23.0):
"""Returns the viscosity for RT-DC-specific media
Parameters
----------
medium: str
The medium to compute the viscosity for.
One of ["CellCarrier", "CellCarrier B", "water"].
channel_width... |
def dancing_links(size_universe, sets):
"""Exact set cover by the dancing links algorithm
:param size_universe: universe = {0, 1, ..., size_universe - 1}
:param sets: list of sets
:returns: list of set indices partitioning the universe, or None
:complexity: huge
"""
header = Cell(None, None... | def function[dancing_links, parameter[size_universe, sets]]:
constant[Exact set cover by the dancing links algorithm
:param size_universe: universe = {0, 1, ..., size_universe - 1}
:param sets: list of sets
:returns: list of set indices partitioning the universe, or None
:complexity: huge
]... | keyword[def] identifier[dancing_links] ( identifier[size_universe] , identifier[sets] ):
literal[string]
identifier[header] = identifier[Cell] ( keyword[None] , keyword[None] , literal[int] , keyword[None] )
identifier[col] =[]
keyword[for] identifier[j] keyword[in] identifier[range] ( identif... | def dancing_links(size_universe, sets):
"""Exact set cover by the dancing links algorithm
:param size_universe: universe = {0, 1, ..., size_universe - 1}
:param sets: list of sets
:returns: list of set indices partitioning the universe, or None
:complexity: huge
"""
header = Cell(None, None... |
def _enforce_no_overlap(self, start_at=0):
"""Enforce that no ranges overlap in internal storage."""
i = start_at
while i+1 < len(self.data):
if self.data[i][1] >= self.data[i+1][0]:
# beginning of i+1-th range is contained in i-th range
if self.data[i... | def function[_enforce_no_overlap, parameter[self, start_at]]:
constant[Enforce that no ranges overlap in internal storage.]
variable[i] assign[=] name[start_at]
while compare[binary_operation[name[i] + constant[1]] less[<] call[name[len], parameter[name[self].data]]] begin[:]
if ... | keyword[def] identifier[_enforce_no_overlap] ( identifier[self] , identifier[start_at] = literal[int] ):
literal[string]
identifier[i] = identifier[start_at]
keyword[while] identifier[i] + literal[int] < identifier[len] ( identifier[self] . identifier[data] ):
keyword[if] i... | def _enforce_no_overlap(self, start_at=0):
"""Enforce that no ranges overlap in internal storage."""
i = start_at
while i + 1 < len(self.data):
if self.data[i][1] >= self.data[i + 1][0]:
# beginning of i+1-th range is contained in i-th range
if self.data[i][1] < self.data[i +... |
def match_rules_context_multi(tree, rules, parent_context={}):
"""Recursively matches a Tree structure with rules and returns context
Args:
tree (Tree): Parsed tree structure
rules (dict): See match_rules
parent_context (dict): Context of parent call
Returns:
dict: Context m... | def function[match_rules_context_multi, parameter[tree, rules, parent_context]]:
constant[Recursively matches a Tree structure with rules and returns context
Args:
tree (Tree): Parsed tree structure
rules (dict): See match_rules
parent_context (dict): Context of parent call
Retu... | keyword[def] identifier[match_rules_context_multi] ( identifier[tree] , identifier[rules] , identifier[parent_context] ={}):
literal[string]
identifier[all_contexts] =[]
keyword[for] identifier[template] , identifier[match_rules] keyword[in] identifier[rules] . identifier[items] ():
identi... | def match_rules_context_multi(tree, rules, parent_context={}):
"""Recursively matches a Tree structure with rules and returns context
Args:
tree (Tree): Parsed tree structure
rules (dict): See match_rules
parent_context (dict): Context of parent call
Returns:
dict: Context m... |
def user_list(profile=None, **connection_args):
'''
Return a list of available users (keystone user-list)
CLI Example:
.. code-block:: bash
salt '*' keystone.user_list
'''
kstone = auth(profile, **connection_args)
ret = {}
for user in kstone.users.list():
ret[user.name... | def function[user_list, parameter[profile]]:
constant[
Return a list of available users (keystone user-list)
CLI Example:
.. code-block:: bash
salt '*' keystone.user_list
]
variable[kstone] assign[=] call[name[auth], parameter[name[profile]]]
variable[ret] assign[=] di... | keyword[def] identifier[user_list] ( identifier[profile] = keyword[None] ,** identifier[connection_args] ):
literal[string]
identifier[kstone] = identifier[auth] ( identifier[profile] ,** identifier[connection_args] )
identifier[ret] ={}
keyword[for] identifier[user] keyword[in] identifier[kst... | def user_list(profile=None, **connection_args):
"""
Return a list of available users (keystone user-list)
CLI Example:
.. code-block:: bash
salt '*' keystone.user_list
"""
kstone = auth(profile, **connection_args)
ret = {}
for user in kstone.users.list():
ret[user.name... |
def from_str(self, instr):
'''Undo affect of __str__'''
if not instr:
return FlexiDate()
out = self.our_re.match(instr)
if out is None: # no match TODO: raise Exception?
return None
else:
return FlexiDate(
out.group('year'),
... | def function[from_str, parameter[self, instr]]:
constant[Undo affect of __str__]
if <ast.UnaryOp object at 0x7da1b0c15420> begin[:]
return[call[name[FlexiDate], parameter[]]]
variable[out] assign[=] call[name[self].our_re.match, parameter[name[instr]]]
if compare[name[out] is con... | keyword[def] identifier[from_str] ( identifier[self] , identifier[instr] ):
literal[string]
keyword[if] keyword[not] identifier[instr] :
keyword[return] identifier[FlexiDate] ()
identifier[out] = identifier[self] . identifier[our_re] . identifier[match] ( identifier[instr]... | def from_str(self, instr):
"""Undo affect of __str__"""
if not instr:
return FlexiDate() # depends on [control=['if'], data=[]]
out = self.our_re.match(instr)
if out is None: # no match TODO: raise Exception?
return None # depends on [control=['if'], data=[]]
else:
return ... |
def weld_iloc_indices_with_missing(array, weld_type, indices):
"""Retrieve the values at indices. Indices greater than array length get replaced with
a corresponding-type missing value literal.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data. Assumed to be bool data.
... | def function[weld_iloc_indices_with_missing, parameter[array, weld_type, indices]]:
constant[Retrieve the values at indices. Indices greater than array length get replaced with
a corresponding-type missing value literal.
Parameters
----------
array : numpy.ndarray or WeldObject
Input da... | keyword[def] identifier[weld_iloc_indices_with_missing] ( identifier[array] , identifier[weld_type] , identifier[indices] ):
literal[string]
identifier[weld_obj] = identifier[create_empty_weld_object] ()
identifier[weld_obj_id_array] = identifier[get_weld_obj_id] ( identifier[weld_obj] , identifier[ar... | def weld_iloc_indices_with_missing(array, weld_type, indices):
"""Retrieve the values at indices. Indices greater than array length get replaced with
a corresponding-type missing value literal.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data. Assumed to be bool data.
... |
def move_datetime_year(dt, direction, num_shifts):
"""
Move datetime 1 year in the chosen direction.
unit is a no-op, to keep the API the same as the day case
"""
delta = relativedelta(years=+num_shifts)
return _move_datetime(dt, direction, delta) | def function[move_datetime_year, parameter[dt, direction, num_shifts]]:
constant[
Move datetime 1 year in the chosen direction.
unit is a no-op, to keep the API the same as the day case
]
variable[delta] assign[=] call[name[relativedelta], parameter[]]
return[call[name[_move_datetime], p... | keyword[def] identifier[move_datetime_year] ( identifier[dt] , identifier[direction] , identifier[num_shifts] ):
literal[string]
identifier[delta] = identifier[relativedelta] ( identifier[years] =+ identifier[num_shifts] )
keyword[return] identifier[_move_datetime] ( identifier[dt] , identifier[direc... | def move_datetime_year(dt, direction, num_shifts):
"""
Move datetime 1 year in the chosen direction.
unit is a no-op, to keep the API the same as the day case
"""
delta = relativedelta(years=+num_shifts)
return _move_datetime(dt, direction, delta) |
def get_fno_lot_sizes(self, cached=True, as_json=False):
"""
returns a dictionary with key as stock code and value as stock name.
It also implements cache functionality and hits the server only
if user insists or cache is empty
:return: dict
"""
url = self.fno_lot... | def function[get_fno_lot_sizes, parameter[self, cached, as_json]]:
constant[
returns a dictionary with key as stock code and value as stock name.
It also implements cache functionality and hits the server only
if user insists or cache is empty
:return: dict
]
vari... | keyword[def] identifier[get_fno_lot_sizes] ( identifier[self] , identifier[cached] = keyword[True] , identifier[as_json] = keyword[False] ):
literal[string]
identifier[url] = identifier[self] . identifier[fno_lot_size_url]
identifier[req] = identifier[Request] ( identifier[url] , keyword[... | def get_fno_lot_sizes(self, cached=True, as_json=False):
"""
returns a dictionary with key as stock code and value as stock name.
It also implements cache functionality and hits the server only
if user insists or cache is empty
:return: dict
"""
url = self.fno_lot_size_ur... |
def list_deelgemeenten(self, gewest=2):
'''
List all `deelgemeenten` in a `gewest`.
:param gewest: The :class:`Gewest` for which the \
`deelgemeenten` are wanted. Currently only Flanders is supported.
:rtype: A :class:`list` of :class:`Deelgemeente`.
'''
try:... | def function[list_deelgemeenten, parameter[self, gewest]]:
constant[
List all `deelgemeenten` in a `gewest`.
:param gewest: The :class:`Gewest` for which the `deelgemeenten` are wanted. Currently only Flanders is supported.
:rtype: A :class:`list` of :class:`Deelgemeente`.
... | keyword[def] identifier[list_deelgemeenten] ( identifier[self] , identifier[gewest] = literal[int] ):
literal[string]
keyword[try] :
identifier[gewest_id] = identifier[gewest] . identifier[id]
keyword[except] identifier[AttributeError] :
identifier[gewest_id] = ... | def list_deelgemeenten(self, gewest=2):
"""
List all `deelgemeenten` in a `gewest`.
:param gewest: The :class:`Gewest` for which the `deelgemeenten` are wanted. Currently only Flanders is supported.
:rtype: A :class:`list` of :class:`Deelgemeente`.
"""
try:
g... |
def input(self, field):
"""Gets user input for given field.
Can be interrupted with ^C.
:field: Field name.
:returns: User input.
"""
try:
desc = Get.TYPES[field]
return input("{}|{}[{}]> ".format(
field, "-" * (Get._LEN - len(fi... | def function[input, parameter[self, field]]:
constant[Gets user input for given field.
Can be interrupted with ^C.
:field: Field name.
:returns: User input.
]
<ast.Try object at 0x7da1b0b71720> | keyword[def] identifier[input] ( identifier[self] , identifier[field] ):
literal[string]
keyword[try] :
identifier[desc] = identifier[Get] . identifier[TYPES] [ identifier[field] ]
keyword[return] identifier[input] ( literal[string] . identifier[format] (
ide... | def input(self, field):
"""Gets user input for given field.
Can be interrupted with ^C.
:field: Field name.
:returns: User input.
"""
try:
desc = Get.TYPES[field]
return input('{}|{}[{}]> '.format(field, '-' * (Get._LEN - len(field) - len(desc)), desc)) # depe... |
def profile(self,
content,
accept,
content_language=None,
accept_language=None,
raw_scores=None,
csv_headers=None,
consumption_preferences=None,
content_type=None,
**kwargs):
... | def function[profile, parameter[self, content, accept, content_language, accept_language, raw_scores, csv_headers, consumption_preferences, content_type]]:
constant[
Get profile.
Generates a personality profile for the author of the input text. The service
accepts a maximum of 20 MB of ... | keyword[def] identifier[profile] ( identifier[self] ,
identifier[content] ,
identifier[accept] ,
identifier[content_language] = keyword[None] ,
identifier[accept_language] = keyword[None] ,
identifier[raw_scores] = keyword[None] ,
identifier[csv_headers] = keyword[None] ,
identifier[consumption_preferences] = ... | def profile(self, content, accept, content_language=None, accept_language=None, raw_scores=None, csv_headers=None, consumption_preferences=None, content_type=None, **kwargs):
"""
Get profile.
Generates a personality profile for the author of the input text. The service
accepts a maximum of ... |
def login(self, verbose=False):
'''
Authenticate with Opsview
:param verbose: Verbose output mode
:type verbose: bool
:return: The authentification token
:rtype: str or unicode
'''
url = '{}/{}'.format(self.rest_url, 'login')
logger.debug('POST: {}... | def function[login, parameter[self, verbose]]:
constant[
Authenticate with Opsview
:param verbose: Verbose output mode
:type verbose: bool
:return: The authentification token
:rtype: str or unicode
]
variable[url] assign[=] call[constant[{}/{}].format, par... | keyword[def] identifier[login] ( identifier[self] , identifier[verbose] = keyword[False] ):
literal[string]
identifier[url] = literal[string] . identifier[format] ( identifier[self] . identifier[rest_url] , literal[string] )
identifier[logger] . identifier[debug] ( literal[string] . identi... | def login(self, verbose=False):
"""
Authenticate with Opsview
:param verbose: Verbose output mode
:type verbose: bool
:return: The authentification token
:rtype: str or unicode
"""
url = '{}/{}'.format(self.rest_url, 'login')
logger.debug('POST: {}'.format(url... |
def linkcode_resolve(domain, info):
"""
Determine the URL corresponding to Python object
"""
if domain != 'py':
return None
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
return None
obj = submod
for part ... | def function[linkcode_resolve, parameter[domain, info]]:
constant[
Determine the URL corresponding to Python object
]
if compare[name[domain] not_equal[!=] constant[py]] begin[:]
return[constant[None]]
variable[modname] assign[=] call[name[info]][constant[module]]
variabl... | keyword[def] identifier[linkcode_resolve] ( identifier[domain] , identifier[info] ):
literal[string]
keyword[if] identifier[domain] != literal[string] :
keyword[return] keyword[None]
identifier[modname] = identifier[info] [ literal[string] ]
identifier[fullname] = identifier[info] [ l... | def linkcode_resolve(domain, info):
"""
Determine the URL corresponding to Python object
"""
if domain != 'py':
return None # depends on [control=['if'], data=[]]
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
re... |
def create_policy(policy_name, policy_document, path=None, description=None,
region=None, key=None, keyid=None, profile=None):
'''
Create a policy.
CLI Example:
.. code-block:: bash
salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effe... | def function[create_policy, parameter[policy_name, policy_document, path, description, region, key, keyid, profile]]:
constant[
Create a policy.
CLI Example:
.. code-block:: bash
salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "A... | keyword[def] identifier[create_policy] ( identifier[policy_name] , identifier[policy_document] , identifier[path] = keyword[None] , identifier[description] = keyword[None] ,
identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keyword[None] , identifier[profile] = keyword[None] ... | def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None):
"""
Create a policy.
CLI Example:
.. code-block:: bash
salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Ac... |
def global_add(self, key: str, value: Any) -> None:
"""
Adds a key and value to the global dictionary
"""
self.global_context[key] = value | def function[global_add, parameter[self, key, value]]:
constant[
Adds a key and value to the global dictionary
]
call[name[self].global_context][name[key]] assign[=] name[value] | keyword[def] identifier[global_add] ( identifier[self] , identifier[key] : identifier[str] , identifier[value] : identifier[Any] )-> keyword[None] :
literal[string]
identifier[self] . identifier[global_context] [ identifier[key] ]= identifier[value] | def global_add(self, key: str, value: Any) -> None:
"""
Adds a key and value to the global dictionary
"""
self.global_context[key] = value |
def is_model_mpttmeta_subclass(node):
"""Checks that node is derivative of MPTTMeta class."""
if node.name != 'MPTTMeta' or not isinstance(node.parent, ClassDef):
return False
parents = ('django.db.models.base.Model',
'.Model', # for the transformed version used in this plugin
... | def function[is_model_mpttmeta_subclass, parameter[node]]:
constant[Checks that node is derivative of MPTTMeta class.]
if <ast.BoolOp object at 0x7da18bcc8610> begin[:]
return[constant[False]]
variable[parents] assign[=] tuple[[<ast.Constant object at 0x7da18bcc8d90>, <ast.Constant objec... | keyword[def] identifier[is_model_mpttmeta_subclass] ( identifier[node] ):
literal[string]
keyword[if] identifier[node] . identifier[name] != literal[string] keyword[or] keyword[not] identifier[isinstance] ( identifier[node] . identifier[parent] , identifier[ClassDef] ):
keyword[return] keywor... | def is_model_mpttmeta_subclass(node):
"""Checks that node is derivative of MPTTMeta class."""
if node.name != 'MPTTMeta' or not isinstance(node.parent, ClassDef):
return False # depends on [control=['if'], data=[]] # for the transformed version used in this plugin
parents = ('django.db.models.base... |
def merge_mutect(job, perchrom_rvs):
"""
This module will merge the per-chromosome mutect files created by spawn_mutect into a genome
vcf. It will make 2 vcfs, one for PASSing non-germline calls, and one for all calls.
ARGUMENTS
1. perchrom_rvs: REFER RETURN VALUE of spawn_mutect()
RETURN VAL... | def function[merge_mutect, parameter[job, perchrom_rvs]]:
constant[
This module will merge the per-chromosome mutect files created by spawn_mutect into a genome
vcf. It will make 2 vcfs, one for PASSing non-germline calls, and one for all calls.
ARGUMENTS
1. perchrom_rvs: REFER RETURN VALUE of... | keyword[def] identifier[merge_mutect] ( identifier[job] , identifier[perchrom_rvs] ):
literal[string]
identifier[job] . identifier[fileStore] . identifier[logToMaster] ( literal[string] )
identifier[work_dir] = identifier[job] . identifier[fileStore] . identifier[getLocalTempDir] ()
ide... | def merge_mutect(job, perchrom_rvs):
"""
This module will merge the per-chromosome mutect files created by spawn_mutect into a genome
vcf. It will make 2 vcfs, one for PASSing non-germline calls, and one for all calls.
ARGUMENTS
1. perchrom_rvs: REFER RETURN VALUE of spawn_mutect()
RETURN VAL... |
def dot_product(self, other):
""" Return the dot product of the given vectors. """
return self.x * other.x + self.y * other.y | def function[dot_product, parameter[self, other]]:
constant[ Return the dot product of the given vectors. ]
return[binary_operation[binary_operation[name[self].x * name[other].x] + binary_operation[name[self].y * name[other].y]]] | keyword[def] identifier[dot_product] ( identifier[self] , identifier[other] ):
literal[string]
keyword[return] identifier[self] . identifier[x] * identifier[other] . identifier[x] + identifier[self] . identifier[y] * identifier[other] . identifier[y] | def dot_product(self, other):
""" Return the dot product of the given vectors. """
return self.x * other.x + self.y * other.y |
def add_program_dir(self, directory):
"""Hack in program directory"""
dirs = list(self.PROGRAM_DIRS)
dirs.append(directory)
self.PROGRAM_DIRS = dirs | def function[add_program_dir, parameter[self, directory]]:
constant[Hack in program directory]
variable[dirs] assign[=] call[name[list], parameter[name[self].PROGRAM_DIRS]]
call[name[dirs].append, parameter[name[directory]]]
name[self].PROGRAM_DIRS assign[=] name[dirs] | keyword[def] identifier[add_program_dir] ( identifier[self] , identifier[directory] ):
literal[string]
identifier[dirs] = identifier[list] ( identifier[self] . identifier[PROGRAM_DIRS] )
identifier[dirs] . identifier[append] ( identifier[directory] )
identifier[self] . identifier[... | def add_program_dir(self, directory):
"""Hack in program directory"""
dirs = list(self.PROGRAM_DIRS)
dirs.append(directory)
self.PROGRAM_DIRS = dirs |
def search_datasets(self):
"""
Returns an iterator over the Datasets on the server.
:return: An iterator over the :class:`ga4gh.protocol.Dataset`
objects on the server.
"""
request = protocol.SearchDatasetsRequest()
request.page_size = pb.int(self._page_size)... | def function[search_datasets, parameter[self]]:
constant[
Returns an iterator over the Datasets on the server.
:return: An iterator over the :class:`ga4gh.protocol.Dataset`
objects on the server.
]
variable[request] assign[=] call[name[protocol].SearchDatasetsRequest... | keyword[def] identifier[search_datasets] ( identifier[self] ):
literal[string]
identifier[request] = identifier[protocol] . identifier[SearchDatasetsRequest] ()
identifier[request] . identifier[page_size] = identifier[pb] . identifier[int] ( identifier[self] . identifier[_page_size] )
... | def search_datasets(self):
"""
Returns an iterator over the Datasets on the server.
:return: An iterator over the :class:`ga4gh.protocol.Dataset`
objects on the server.
"""
request = protocol.SearchDatasetsRequest()
request.page_size = pb.int(self._page_size)
return ... |
def is_domterm(cls):
"""
:return: whether we are inside DomTerm
:rtype: bool
"""
import os
if cls._is_domterm is not None:
return cls._is_domterm
if not os.environ.get("DOMTERM"):
cls._is_domterm = False
return False
cls... | def function[is_domterm, parameter[cls]]:
constant[
:return: whether we are inside DomTerm
:rtype: bool
]
import module[os]
if compare[name[cls]._is_domterm is_not constant[None]] begin[:]
return[name[cls]._is_domterm]
if <ast.UnaryOp object at 0x7da1b24ef7c0>... | keyword[def] identifier[is_domterm] ( identifier[cls] ):
literal[string]
keyword[import] identifier[os]
keyword[if] identifier[cls] . identifier[_is_domterm] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[cls] . identifier[_is_domterm]
key... | def is_domterm(cls):
"""
:return: whether we are inside DomTerm
:rtype: bool
"""
import os
if cls._is_domterm is not None:
return cls._is_domterm # depends on [control=['if'], data=[]]
if not os.environ.get('DOMTERM'):
cls._is_domterm = False
return False... |
def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
return vatm(
self.model,... | def function[generate, parameter[self, x]]:
constant[
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
]
assert[call[name[self].parse_params, parameter[]]]
return[call[name[vatm], parameter[name[self].m... | keyword[def] identifier[generate] ( identifier[self] , identifier[x] ,** identifier[kwargs] ):
literal[string]
keyword[assert] identifier[self] . identifier[parse_params] (** identifier[kwargs] )
keyword[return] identifier[vatm] (
identifier[self] . identifier[model] ,
identifier[x] ... | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
return vatm(self.model, x, self.m... |
def pop_arguments(instr, stack):
"""
Pop instructions off `stack` until we pop all instructions that will
produce values popped by `instr`.
"""
needed = instr.stack_effect
if needed >= 0:
raise DecompilationError(
"%s is does not have a negative stack effect" % instr
... | def function[pop_arguments, parameter[instr, stack]]:
constant[
Pop instructions off `stack` until we pop all instructions that will
produce values popped by `instr`.
]
variable[needed] assign[=] name[instr].stack_effect
if compare[name[needed] greater_or_equal[>=] constant[0]] begin... | keyword[def] identifier[pop_arguments] ( identifier[instr] , identifier[stack] ):
literal[string]
identifier[needed] = identifier[instr] . identifier[stack_effect]
keyword[if] identifier[needed] >= literal[int] :
keyword[raise] identifier[DecompilationError] (
literal[string] % id... | def pop_arguments(instr, stack):
"""
Pop instructions off `stack` until we pop all instructions that will
produce values popped by `instr`.
"""
needed = instr.stack_effect
if needed >= 0:
raise DecompilationError('%s is does not have a negative stack effect' % instr) # depends on [contr... |
def do_chan_log_all(self, line):
"""Set the channel log level to ALL_COMMS. Command syntax is: chan_log_all"""
self.application.channel.SetLogFilters(openpal.LogFilters(opendnp3.levels.ALL_COMMS))
print('Channel log filtering level is now: {0}'.format(opendnp3.levels.ALL_COMMS)) | def function[do_chan_log_all, parameter[self, line]]:
constant[Set the channel log level to ALL_COMMS. Command syntax is: chan_log_all]
call[name[self].application.channel.SetLogFilters, parameter[call[name[openpal].LogFilters, parameter[name[opendnp3].levels.ALL_COMMS]]]]
call[name[print], para... | keyword[def] identifier[do_chan_log_all] ( identifier[self] , identifier[line] ):
literal[string]
identifier[self] . identifier[application] . identifier[channel] . identifier[SetLogFilters] ( identifier[openpal] . identifier[LogFilters] ( identifier[opendnp3] . identifier[levels] . identifier[ALL_... | def do_chan_log_all(self, line):
"""Set the channel log level to ALL_COMMS. Command syntax is: chan_log_all"""
self.application.channel.SetLogFilters(openpal.LogFilters(opendnp3.levels.ALL_COMMS))
print('Channel log filtering level is now: {0}'.format(opendnp3.levels.ALL_COMMS)) |
def get_delete_branch_command(self, branch_name, message, author):
"""Get the command to delete or close a branch in the local repository."""
tokens = ['hg update --rev=%s && hg commit' % quote(branch_name)]
if author:
tokens.append('--user=%s' % quote(author.combined))
token... | def function[get_delete_branch_command, parameter[self, branch_name, message, author]]:
constant[Get the command to delete or close a branch in the local repository.]
variable[tokens] assign[=] list[[<ast.BinOp object at 0x7da1b0af1180>]]
if name[author] begin[:]
call[name[tokens... | keyword[def] identifier[get_delete_branch_command] ( identifier[self] , identifier[branch_name] , identifier[message] , identifier[author] ):
literal[string]
identifier[tokens] =[ literal[string] % identifier[quote] ( identifier[branch_name] )]
keyword[if] identifier[author] :
... | def get_delete_branch_command(self, branch_name, message, author):
"""Get the command to delete or close a branch in the local repository."""
tokens = ['hg update --rev=%s && hg commit' % quote(branch_name)]
if author:
tokens.append('--user=%s' % quote(author.combined)) # depends on [control=['if']... |
def register_all_add_grad(
add_grad_function, arg_types, exclude=(), ignore_existing=False):
"""Register a gradient adder for all combinations of given types.
This is a convenience shorthand for calling register_add_grad when registering
gradient adders for multiple types that can be interchanged for the pur... | def function[register_all_add_grad, parameter[add_grad_function, arg_types, exclude, ignore_existing]]:
constant[Register a gradient adder for all combinations of given types.
This is a convenience shorthand for calling register_add_grad when registering
gradient adders for multiple types that can be inter... | keyword[def] identifier[register_all_add_grad] (
identifier[add_grad_function] , identifier[arg_types] , identifier[exclude] =(), identifier[ignore_existing] = keyword[False] ):
literal[string]
keyword[for] identifier[t1] keyword[in] identifier[arg_types] :
keyword[for] identifier[t2] keyword[in] i... | def register_all_add_grad(add_grad_function, arg_types, exclude=(), ignore_existing=False):
"""Register a gradient adder for all combinations of given types.
This is a convenience shorthand for calling register_add_grad when registering
gradient adders for multiple types that can be interchanged for the purpos... |
def reorg_crawl_tasks(tasks, concurrency, logger=None):
""" Extract content returned by the crawler `iter_crawl_tasks`
member method.
:return:
tuple made of the sub-tasks to executed, the epilogue task to execute
or `None` is none was specified by the crawler, and the proper
tasks concurr... | def function[reorg_crawl_tasks, parameter[tasks, concurrency, logger]]:
constant[ Extract content returned by the crawler `iter_crawl_tasks`
member method.
:return:
tuple made of the sub-tasks to executed, the epilogue task to execute
or `None` is none was specified by the crawler, and the ... | keyword[def] identifier[reorg_crawl_tasks] ( identifier[tasks] , identifier[concurrency] , identifier[logger] = keyword[None] ):
literal[string]
identifier[futures] = identifier[tasks] [ literal[string] ]
identifier[epilogue] = identifier[tasks] . identifier[get] ( literal[string] )
identifier[cu... | def reorg_crawl_tasks(tasks, concurrency, logger=None):
""" Extract content returned by the crawler `iter_crawl_tasks`
member method.
:return:
tuple made of the sub-tasks to executed, the epilogue task to execute
or `None` is none was specified by the crawler, and the proper
tasks concurr... |
def parse_plist(entry):
"""Parse a XML dictionary entry."""
if is_leaf(entry):
url = entry[KEY_URLSTRING]
title = entry[KEY_URIDICTIONARY].get('title', url)
yield (url, title)
elif has_children(entry):
for child in entry[KEY_CHILDREN]:
for item in parse_plist(chil... | def function[parse_plist, parameter[entry]]:
constant[Parse a XML dictionary entry.]
if call[name[is_leaf], parameter[name[entry]]] begin[:]
variable[url] assign[=] call[name[entry]][name[KEY_URLSTRING]]
variable[title] assign[=] call[call[name[entry]][name[KEY_URIDICTION... | keyword[def] identifier[parse_plist] ( identifier[entry] ):
literal[string]
keyword[if] identifier[is_leaf] ( identifier[entry] ):
identifier[url] = identifier[entry] [ identifier[KEY_URLSTRING] ]
identifier[title] = identifier[entry] [ identifier[KEY_URIDICTIONARY] ]. identifier[get] ( ... | def parse_plist(entry):
"""Parse a XML dictionary entry."""
if is_leaf(entry):
url = entry[KEY_URLSTRING]
title = entry[KEY_URIDICTIONARY].get('title', url)
yield (url, title) # depends on [control=['if'], data=[]]
elif has_children(entry):
for child in entry[KEY_CHILDREN]:
... |
def tokenize_middle_english_words(text):
"""Tokenizes ME text:
>>> tokenize_middle_english_words("And then, went I fastyr!")
['And', 'then', ',', 'went', 'I', 'fastyr', '!']
"""
assert isinstance(text, str)
text = re.sub(r'\n', r' ', text)
text = re.sub(r'(?<=.)(?=[\.\";\,\:\-\[\]\(... | def function[tokenize_middle_english_words, parameter[text]]:
constant[Tokenizes ME text:
>>> tokenize_middle_english_words("And then, went I fastyr!")
['And', 'then', ',', 'went', 'I', 'fastyr', '!']
]
assert[call[name[isinstance], parameter[name[text], name[str]]]]
variable[text... | keyword[def] identifier[tokenize_middle_english_words] ( identifier[text] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[text] , identifier[str] )
identifier[text] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[text] )
identifier[tex... | def tokenize_middle_english_words(text):
"""Tokenizes ME text:
>>> tokenize_middle_english_words("And then, went I fastyr!")
['And', 'then', ',', 'went', 'I', 'fastyr', '!']
"""
assert isinstance(text, str)
text = re.sub('\\n', ' ', text)
text = re.sub('(?<=.)(?=[\\.\\";\\,\\:\\-\\[\\... |
def allsame(list_, strict=True):
"""
checks to see if list is equal everywhere
Args:
list_ (list):
Returns:
True if all items in the list are equal
"""
if len(list_) == 0:
return True
first_item = list_[0]
return list_all_eq_to(list_, first_item, strict) | def function[allsame, parameter[list_, strict]]:
constant[
checks to see if list is equal everywhere
Args:
list_ (list):
Returns:
True if all items in the list are equal
]
if compare[call[name[len], parameter[name[list_]]] equal[==] constant[0]] begin[:]
return[... | keyword[def] identifier[allsame] ( identifier[list_] , identifier[strict] = keyword[True] ):
literal[string]
keyword[if] identifier[len] ( identifier[list_] )== literal[int] :
keyword[return] keyword[True]
identifier[first_item] = identifier[list_] [ literal[int] ]
keyword[return] id... | def allsame(list_, strict=True):
"""
checks to see if list is equal everywhere
Args:
list_ (list):
Returns:
True if all items in the list are equal
"""
if len(list_) == 0:
return True # depends on [control=['if'], data=[]]
first_item = list_[0]
return list_all_... |
def _get_crud_params(compiler, stmt, **kw):
""" extract values from crud parameters
taken from SQLAlchemy's crud module (since 1.0.x) and
adapted for Crate dialect"""
compiler.postfetch = []
compiler.insert_prefetch = []
compiler.update_prefetch = []
compiler.re... | def function[_get_crud_params, parameter[compiler, stmt]]:
constant[ extract values from crud parameters
taken from SQLAlchemy's crud module (since 1.0.x) and
adapted for Crate dialect]
name[compiler].postfetch assign[=] list[[]]
name[compiler].insert_prefetch assign[=] list[[]]... | keyword[def] identifier[_get_crud_params] ( identifier[compiler] , identifier[stmt] ,** identifier[kw] ):
literal[string]
identifier[compiler] . identifier[postfetch] =[]
identifier[compiler] . identifier[insert_prefetch] =[]
identifier[compiler] . identifier[update_prefetch] =[]... | def _get_crud_params(compiler, stmt, **kw):
""" extract values from crud parameters
taken from SQLAlchemy's crud module (since 1.0.x) and
adapted for Crate dialect"""
compiler.postfetch = []
compiler.insert_prefetch = []
compiler.update_prefetch = []
compiler.returning = []
# no... |
def on_prev_button(self, event):
"""
update figures and text when a previous button is selected
"""
if 'saved' not in self.Data[self.s]['pars'] or self.Data[self.s]['pars']['saved'] != True:
# check preferences
if self.auto_save.GetValue():
self.on... | def function[on_prev_button, parameter[self, event]]:
constant[
update figures and text when a previous button is selected
]
if <ast.BoolOp object at 0x7da1b05115a0> begin[:]
if call[name[self].auto_save.GetValue, parameter[]] begin[:]
call[name[se... | keyword[def] identifier[on_prev_button] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[self] . identifier[Data] [ identifier[self] . identifier[s] ][ literal[string] ] keyword[or] identifier[self] . identifier[Data] [ i... | def on_prev_button(self, event):
"""
update figures and text when a previous button is selected
"""
if 'saved' not in self.Data[self.s]['pars'] or self.Data[self.s]['pars']['saved'] != True:
# check preferences
if self.auto_save.GetValue():
self.on_save_interpretation... |
def conditional_entropy(data, precision, min_period, max_period,
xbins=10, ybins=5, period_jobs=1):
"""
Returns the period of *data* by minimizing conditional entropy.
See `link <http://arxiv.org/pdf/1306.6664v2.pdf>`_ [GDDMD] for details.
**Parameters**
data : array-like, ... | def function[conditional_entropy, parameter[data, precision, min_period, max_period, xbins, ybins, period_jobs]]:
constant[
Returns the period of *data* by minimizing conditional entropy.
See `link <http://arxiv.org/pdf/1306.6664v2.pdf>`_ [GDDMD] for details.
**Parameters**
data : array-like, ... | keyword[def] identifier[conditional_entropy] ( identifier[data] , identifier[precision] , identifier[min_period] , identifier[max_period] ,
identifier[xbins] = literal[int] , identifier[ybins] = literal[int] , identifier[period_jobs] = literal[int] ):
literal[string]
identifier[periods] = identifier[np] .... | def conditional_entropy(data, precision, min_period, max_period, xbins=10, ybins=5, period_jobs=1):
"""
Returns the period of *data* by minimizing conditional entropy.
See `link <http://arxiv.org/pdf/1306.6664v2.pdf>`_ [GDDMD] for details.
**Parameters**
data : array-like, shape = [n_samples, 2] o... |
def _watch_folder(folder, destination, compiler_args):
"""Compares "modified" timestamps against the "compiled" dict, calls compiler
if necessary."""
for dirpath, dirnames, filenames in os.walk(folder):
for filename in filenames:
# Ignore filenames starting with ".#" for Emacs compatibil... | def function[_watch_folder, parameter[folder, destination, compiler_args]]:
constant[Compares "modified" timestamps against the "compiled" dict, calls compiler
if necessary.]
for taget[tuple[[<ast.Name object at 0x7da20c6ab2e0>, <ast.Name object at 0x7da20c6aa170>, <ast.Name object at 0x7da20c6a82b0... | keyword[def] identifier[_watch_folder] ( identifier[folder] , identifier[destination] , identifier[compiler_args] ):
literal[string]
keyword[for] identifier[dirpath] , identifier[dirnames] , identifier[filenames] keyword[in] identifier[os] . identifier[walk] ( identifier[folder] ):
keyword[for]... | def _watch_folder(folder, destination, compiler_args):
"""Compares "modified" timestamps against the "compiled" dict, calls compiler
if necessary."""
for (dirpath, dirnames, filenames) in os.walk(folder):
for filename in filenames:
# Ignore filenames starting with ".#" for Emacs compatib... |
def dot_product_single_head(q, k, v, gates_q, gates_k, bi):
"""Perform a dot product attention on a single sequence on a single head.
This function dispatch the q, k, v and loop over the buckets to compute the
attention dot product on each subsequences.
Args:
q (tf.Tensor): [length_q, depth_q]
k (tf.T... | def function[dot_product_single_head, parameter[q, k, v, gates_q, gates_k, bi]]:
constant[Perform a dot product attention on a single sequence on a single head.
This function dispatch the q, k, v and loop over the buckets to compute the
attention dot product on each subsequences.
Args:
q (tf.Tensor)... | keyword[def] identifier[dot_product_single_head] ( identifier[q] , identifier[k] , identifier[v] , identifier[gates_q] , identifier[gates_k] , identifier[bi] ):
literal[string]
identifier[nb_buckets] = identifier[gates_q] . identifier[get_shape] (). identifier[as_list] ()[- literal[int] ]
identifier[q_dis... | def dot_product_single_head(q, k, v, gates_q, gates_k, bi):
"""Perform a dot product attention on a single sequence on a single head.
This function dispatch the q, k, v and loop over the buckets to compute the
attention dot product on each subsequences.
Args:
q (tf.Tensor): [length_q, depth_q]
k (tf... |
def httpResponse_bodyParse(self, **kwargs):
"""
Returns the *body* from a http response.
:param kwargs: response = <string>
:return: the <body> from the http <string>
"""
str_response = ''
for k,v in kwargs.items():
if k == 'response': str_respons... | def function[httpResponse_bodyParse, parameter[self]]:
constant[
Returns the *body* from a http response.
:param kwargs: response = <string>
:return: the <body> from the http <string>
]
variable[str_response] assign[=] constant[]
for taget[tuple[[<ast.Name object... | keyword[def] identifier[httpResponse_bodyParse] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[str_response] = literal[string]
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[kwargs] . identifier[items] ():
keyword[if] identifie... | def httpResponse_bodyParse(self, **kwargs):
"""
Returns the *body* from a http response.
:param kwargs: response = <string>
:return: the <body> from the http <string>
"""
str_response = ''
for (k, v) in kwargs.items():
if k == 'response':
str_response = v... |
def cf_data_to_bytes(value):
"""
Extracts a bytestring from a CFData object
:param value:
A CFData object
:return:
A byte string
"""
start = CoreFoundation.CFDataGetBytePtr(value)
num_bytes = CoreFoundation.CFDataGetLength(value)
... | def function[cf_data_to_bytes, parameter[value]]:
constant[
Extracts a bytestring from a CFData object
:param value:
A CFData object
:return:
A byte string
]
variable[start] assign[=] call[name[CoreFoundation].CFDataGetBytePtr, parameter[name[val... | keyword[def] identifier[cf_data_to_bytes] ( identifier[value] ):
literal[string]
identifier[start] = identifier[CoreFoundation] . identifier[CFDataGetBytePtr] ( identifier[value] )
identifier[num_bytes] = identifier[CoreFoundation] . identifier[CFDataGetLength] ( identifier[value] )
... | def cf_data_to_bytes(value):
"""
Extracts a bytestring from a CFData object
:param value:
A CFData object
:return:
A byte string
"""
start = CoreFoundation.CFDataGetBytePtr(value)
num_bytes = CoreFoundation.CFDataGetLength(value)
return ffi.buffe... |
def ids(cls, values, itype=None):
'''
http://www.elasticsearch.org/guide/reference/query-dsl/ids-filter.html
Filters documents that only have the provided ids. Note, this filter does not require the _id field to be indexed since it works using the _uid field.
'''
instance = cls(ids={'va... | def function[ids, parameter[cls, values, itype]]:
constant[
http://www.elasticsearch.org/guide/reference/query-dsl/ids-filter.html
Filters documents that only have the provided ids. Note, this filter does not require the _id field to be indexed since it works using the _uid field.
]
var... | keyword[def] identifier[ids] ( identifier[cls] , identifier[values] , identifier[itype] = keyword[None] ):
literal[string]
identifier[instance] = identifier[cls] ( identifier[ids] ={ literal[string] : identifier[values] })
keyword[if] identifier[itype] keyword[is] keyword[not] keyword[... | def ids(cls, values, itype=None):
"""
http://www.elasticsearch.org/guide/reference/query-dsl/ids-filter.html
Filters documents that only have the provided ids. Note, this filter does not require the _id field to be indexed since it works using the _uid field.
"""
instance = cls(ids={'values': v... |
def asarray(self, *args, **kwargs):
"""Read image data from file and return as numpy array."""
# TODO: fix TypeError on Python 2
# "TypeError: unbound method asarray() must be called with TiffPage
# instance as first argument (got TiffFrame instance instead)"
if self._keyfram... | def function[asarray, parameter[self]]:
constant[Read image data from file and return as numpy array.]
if compare[name[self]._keyframe is constant[None]] begin[:]
<ast.Raise object at 0x7da1b1836050>
call[name[kwargs]][constant[validate]] assign[=] constant[False]
return[call[name[Ti... | keyword[def] identifier[asarray] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[_keyframe] keyword[is] keyword[None] :
keyword[raise] identifier[RuntimeError] ( literal[string] )
... | def asarray(self, *args, **kwargs):
"""Read image data from file and return as numpy array."""
# TODO: fix TypeError on Python 2
# "TypeError: unbound method asarray() must be called with TiffPage
# instance as first argument (got TiffFrame instance instead)"
if self._keyframe is None:
r... |
def _handle_offset_error(self, failure):
"""
Retry the offset fetch request if appropriate.
Once the :attr:`.retry_delay` reaches our :attr:`.retry_max_delay`, we
log a warning. This should perhaps be extended to abort sooner on
certain errors.
"""
# outstanding... | def function[_handle_offset_error, parameter[self, failure]]:
constant[
Retry the offset fetch request if appropriate.
Once the :attr:`.retry_delay` reaches our :attr:`.retry_max_delay`, we
log a warning. This should perhaps be extended to abort sooner on
certain errors.
... | keyword[def] identifier[_handle_offset_error] ( identifier[self] , identifier[failure] ):
literal[string]
identifier[self] . identifier[_request_d] = keyword[None]
keyword[if] identifier[self] . identifier[_stopping] keyword[and] identifier[failure] . identifier[check] ( iden... | def _handle_offset_error(self, failure):
"""
Retry the offset fetch request if appropriate.
Once the :attr:`.retry_delay` reaches our :attr:`.retry_max_delay`, we
log a warning. This should perhaps be extended to abort sooner on
certain errors.
"""
# outstanding request... |
def graph_type(self, graph):
"""What type of graph is this?"""
graph = self.pack(graph)
return self.sql('graph_type', graph).fetchone()[0] | def function[graph_type, parameter[self, graph]]:
constant[What type of graph is this?]
variable[graph] assign[=] call[name[self].pack, parameter[name[graph]]]
return[call[call[call[name[self].sql, parameter[constant[graph_type], name[graph]]].fetchone, parameter[]]][constant[0]]] | keyword[def] identifier[graph_type] ( identifier[self] , identifier[graph] ):
literal[string]
identifier[graph] = identifier[self] . identifier[pack] ( identifier[graph] )
keyword[return] identifier[self] . identifier[sql] ( literal[string] , identifier[graph] ). identifier[fetchone] ()[ ... | def graph_type(self, graph):
"""What type of graph is this?"""
graph = self.pack(graph)
return self.sql('graph_type', graph).fetchone()[0] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.