code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def register(**kwargs):
"""Decorator for registering API function.
Does not do any check or validation.
"""
def decorator(func):
_CALL_REGISTRY[kwargs.get(API_SYM, func.__name__)] = func
return func
return decorator | def function[register, parameter[]]:
constant[Decorator for registering API function.
Does not do any check or validation.
]
def function[decorator, parameter[func]]:
call[name[_CALL_REGISTRY]][call[name[kwargs].get, parameter[name[API_SYM], name[func].__name__]]] assign[=] name... | keyword[def] identifier[register] (** identifier[kwargs] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[func] ):
identifier[_CALL_REGISTRY] [ identifier[kwargs] . identifier[get] ( identifier[API_SYM] , identifier[func] . identifier[__name__] )]= identifier[func]
key... | def register(**kwargs):
"""Decorator for registering API function.
Does not do any check or validation.
"""
def decorator(func):
_CALL_REGISTRY[kwargs.get(API_SYM, func.__name__)] = func
return func
return decorator |
def resolver(*for_resolve, attr_package='__package_for_resolve_deco__'):
""" Resolve dotted names in function arguments
Usage:
>>> @resolver('obj')
>>> def func(param, obj):
>>> assert isinstance(param, str)
>>> assert not isinstance(obj, str)
>>>
>>> fu... | def function[resolver, parameter[]]:
constant[ Resolve dotted names in function arguments
Usage:
>>> @resolver('obj')
>>> def func(param, obj):
>>> assert isinstance(param, str)
>>> assert not isinstance(obj, str)
>>>
>>> func('os.path', 'sys.exit')
... | keyword[def] identifier[resolver] (* identifier[for_resolve] , identifier[attr_package] = literal[string] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[func] ):
identifier[spec] = identifier[inspect] . identifier[getargspec] ( identifier[func] ). identifier[args]
ke... | def resolver(*for_resolve, attr_package='__package_for_resolve_deco__'):
""" Resolve dotted names in function arguments
Usage:
>>> @resolver('obj')
>>> def func(param, obj):
>>> assert isinstance(param, str)
>>> assert not isinstance(obj, str)
>>>
>>> fu... |
def set(self, instance, items, prices=None, specs=None, hidden=None, **kw):
"""Set/Assign Analyses to this AR
:param items: List of Analysis objects/brains, AnalysisService
objects/brains and/or Analysis Service uids
:type items: list
:param prices: Mapping of Anal... | def function[set, parameter[self, instance, items, prices, specs, hidden]]:
constant[Set/Assign Analyses to this AR
:param items: List of Analysis objects/brains, AnalysisService
objects/brains and/or Analysis Service uids
:type items: list
:param prices: Mapping o... | keyword[def] identifier[set] ( identifier[self] , identifier[instance] , identifier[items] , identifier[prices] = keyword[None] , identifier[specs] = keyword[None] , identifier[hidden] = keyword[None] ,** identifier[kw] ):
literal[string]
identifier[new_analyses] =[]
ide... | def set(self, instance, items, prices=None, specs=None, hidden=None, **kw):
"""Set/Assign Analyses to this AR
:param items: List of Analysis objects/brains, AnalysisService
objects/brains and/or Analysis Service uids
:type items: list
:param prices: Mapping of Analysis... |
def close(self, status=STATUS_NORMAL, reason=six.b(""), timeout=3):
"""
Close Websocket object
status: status code to send. see STATUS_XXX.
reason: the reason to close. This must be string.
timeout: timeout until receive a close frame.
If None, it will wait forever... | def function[close, parameter[self, status, reason, timeout]]:
constant[
Close Websocket object
status: status code to send. see STATUS_XXX.
reason: the reason to close. This must be string.
timeout: timeout until receive a close frame.
If None, it will wait foreve... | keyword[def] identifier[close] ( identifier[self] , identifier[status] = identifier[STATUS_NORMAL] , identifier[reason] = identifier[six] . identifier[b] ( literal[string] ), identifier[timeout] = literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[connected] :
k... | def close(self, status=STATUS_NORMAL, reason=six.b(''), timeout=3):
"""
Close Websocket object
status: status code to send. see STATUS_XXX.
reason: the reason to close. This must be string.
timeout: timeout until receive a close frame.
If None, it will wait forever unt... |
def default_option(self, fn, optstr):
"""Make an entry in the options_table for fn, with value optstr"""
if fn not in self.lsmagic():
error("%s is not a magic function" % fn)
self.options_table[fn] = optstr | def function[default_option, parameter[self, fn, optstr]]:
constant[Make an entry in the options_table for fn, with value optstr]
if compare[name[fn] <ast.NotIn object at 0x7da2590d7190> call[name[self].lsmagic, parameter[]]] begin[:]
call[name[error], parameter[binary_operation[constant... | keyword[def] identifier[default_option] ( identifier[self] , identifier[fn] , identifier[optstr] ):
literal[string]
keyword[if] identifier[fn] keyword[not] keyword[in] identifier[self] . identifier[lsmagic] ():
identifier[error] ( literal[string] % identifier[fn] )
identi... | def default_option(self, fn, optstr):
"""Make an entry in the options_table for fn, with value optstr"""
if fn not in self.lsmagic():
error('%s is not a magic function' % fn) # depends on [control=['if'], data=['fn']]
self.options_table[fn] = optstr |
def getWindow(title, exact=False):
"""Return Window object if 'title' or its part found in visible windows titles, else return None
Return only 1 window found first
Args:
title: unicode string
exact (bool): True if search only exact match
"""
titles = getWindows()
hwnd = titles.... | def function[getWindow, parameter[title, exact]]:
constant[Return Window object if 'title' or its part found in visible windows titles, else return None
Return only 1 window found first
Args:
title: unicode string
exact (bool): True if search only exact match
]
variable[titl... | keyword[def] identifier[getWindow] ( identifier[title] , identifier[exact] = keyword[False] ):
literal[string]
identifier[titles] = identifier[getWindows] ()
identifier[hwnd] = identifier[titles] . identifier[get] ( identifier[title] , keyword[None] )
keyword[if] keyword[not] identifier[hwnd] ... | def getWindow(title, exact=False):
"""Return Window object if 'title' or its part found in visible windows titles, else return None
Return only 1 window found first
Args:
title: unicode string
exact (bool): True if search only exact match
"""
titles = getWindows()
hwnd = titles.... |
def near_to_position(self, position, max_distance):
'''Returns true iff the record is within max_distance of the given position.
Note: chromosome name not checked, so that's up to you to do first.'''
end = self.ref_end_pos()
return self.POS <= position <= end or abs(position - self.POS) ... | def function[near_to_position, parameter[self, position, max_distance]]:
constant[Returns true iff the record is within max_distance of the given position.
Note: chromosome name not checked, so that's up to you to do first.]
variable[end] assign[=] call[name[self].ref_end_pos, parameter[]]
r... | keyword[def] identifier[near_to_position] ( identifier[self] , identifier[position] , identifier[max_distance] ):
literal[string]
identifier[end] = identifier[self] . identifier[ref_end_pos] ()
keyword[return] identifier[self] . identifier[POS] <= identifier[position] <= identifier[end] ... | def near_to_position(self, position, max_distance):
"""Returns true iff the record is within max_distance of the given position.
Note: chromosome name not checked, so that's up to you to do first."""
end = self.ref_end_pos()
return self.POS <= position <= end or abs(position - self.POS) <= max_dista... |
def create_identity_from_private_key(self, label: str, pwd: str, private_key: str) -> Identity:
"""
This interface is used to create identity based on given label, password and private key.
:param label: a label for identity.
:param pwd: a password which will be used to encrypt and decr... | def function[create_identity_from_private_key, parameter[self, label, pwd, private_key]]:
constant[
This interface is used to create identity based on given label, password and private key.
:param label: a label for identity.
:param pwd: a password which will be used to encrypt and decr... | keyword[def] identifier[create_identity_from_private_key] ( identifier[self] , identifier[label] : identifier[str] , identifier[pwd] : identifier[str] , identifier[private_key] : identifier[str] )-> identifier[Identity] :
literal[string]
identifier[salt] = identifier[get_random_hex_str] ( literal[i... | def create_identity_from_private_key(self, label: str, pwd: str, private_key: str) -> Identity:
"""
This interface is used to create identity based on given label, password and private key.
:param label: a label for identity.
:param pwd: a password which will be used to encrypt and decrypt ... |
def _convert_to_indexer(self, obj, axis=None, is_setter=False):
""" much simpler as we only have to deal with our valid types """
if axis is None:
axis = self.axis or 0
# make need to convert a float key
if isinstance(obj, slice):
return self._convert_slice_index... | def function[_convert_to_indexer, parameter[self, obj, axis, is_setter]]:
constant[ much simpler as we only have to deal with our valid types ]
if compare[name[axis] is constant[None]] begin[:]
variable[axis] assign[=] <ast.BoolOp object at 0x7da18c4ccca0>
if call[name[isinstance... | keyword[def] identifier[_convert_to_indexer] ( identifier[self] , identifier[obj] , identifier[axis] = keyword[None] , identifier[is_setter] = keyword[False] ):
literal[string]
keyword[if] identifier[axis] keyword[is] keyword[None] :
identifier[axis] = identifier[self] . identifier[... | def _convert_to_indexer(self, obj, axis=None, is_setter=False):
""" much simpler as we only have to deal with our valid types """
if axis is None:
axis = self.axis or 0 # depends on [control=['if'], data=['axis']]
# make need to convert a float key
if isinstance(obj, slice):
return self... |
def process_packets(self, transaction_id=None, invoked_method=None,
timeout=None):
"""Wait for packets and process them as needed.
:param transaction_id: int, Wait until the result of this
transaction ID is recieved.
:param invoked_method: ... | def function[process_packets, parameter[self, transaction_id, invoked_method, timeout]]:
constant[Wait for packets and process them as needed.
:param transaction_id: int, Wait until the result of this
transaction ID is recieved.
:param invoked_method: int, Wait un... | keyword[def] identifier[process_packets] ( identifier[self] , identifier[transaction_id] = keyword[None] , identifier[invoked_method] = keyword[None] ,
identifier[timeout] = keyword[None] ):
literal[string]
identifier[start] = identifier[time] ()
keyword[while] identifier[self] . ident... | def process_packets(self, transaction_id=None, invoked_method=None, timeout=None):
"""Wait for packets and process them as needed.
:param transaction_id: int, Wait until the result of this
transaction ID is recieved.
:param invoked_method: int, Wait until this method ... |
def filename_add_custom_url_params(filename, request):
""" Adds custom url parameters to filename string
:param filename: Initial filename
:type filename: str
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcReq... | def function[filename_add_custom_url_params, parameter[filename, request]]:
constant[ Adds custom url parameters to filename string
:param filename: Initial filename
:type filename: str
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
... | keyword[def] identifier[filename_add_custom_url_params] ( identifier[filename] , identifier[request] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[request] , literal[string] ) keyword[and] identifier[request] . identifier[custom_url_params] keyword[is] keyword[not] keyword[No... | def filename_add_custom_url_params(filename, request):
""" Adds custom url parameters to filename string
:param filename: Initial filename
:type filename: str
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest... |
def check_namespace(namespace_id):
"""
Verify that a namespace ID is well-formed
>>> check_namespace(123)
False
>>> check_namespace(None)
False
>>> check_namespace('')
False
>>> check_namespace('abcd')
True
>>> check_namespace('Abcd')
False
>>> check_namespace('a+bcd... | def function[check_namespace, parameter[namespace_id]]:
constant[
Verify that a namespace ID is well-formed
>>> check_namespace(123)
False
>>> check_namespace(None)
False
>>> check_namespace('')
False
>>> check_namespace('abcd')
True
>>> check_namespace('Abcd')
False... | keyword[def] identifier[check_namespace] ( identifier[namespace_id] ):
literal[string]
keyword[if] identifier[type] ( identifier[namespace_id] ) keyword[not] keyword[in] [ identifier[str] , identifier[unicode] ]:
keyword[return] keyword[False]
keyword[if] keyword[not] identifier[is_nam... | def check_namespace(namespace_id):
"""
Verify that a namespace ID is well-formed
>>> check_namespace(123)
False
>>> check_namespace(None)
False
>>> check_namespace('')
False
>>> check_namespace('abcd')
True
>>> check_namespace('Abcd')
False
>>> check_namespace('a+bcd... |
def query(self, req) -> ResponseQuery:
"""Return the last tx count"""
v = encode_number(self.txCount)
return ResponseQuery(code=CodeTypeOk, value=v, height=self.last_block_height) | def function[query, parameter[self, req]]:
constant[Return the last tx count]
variable[v] assign[=] call[name[encode_number], parameter[name[self].txCount]]
return[call[name[ResponseQuery], parameter[]]] | keyword[def] identifier[query] ( identifier[self] , identifier[req] )-> identifier[ResponseQuery] :
literal[string]
identifier[v] = identifier[encode_number] ( identifier[self] . identifier[txCount] )
keyword[return] identifier[ResponseQuery] ( identifier[code] = identifier[CodeTypeOk] , ... | def query(self, req) -> ResponseQuery:
"""Return the last tx count"""
v = encode_number(self.txCount)
return ResponseQuery(code=CodeTypeOk, value=v, height=self.last_block_height) |
def diff(self):
"""
Only report difference in content between two directories
"""
self._copyfiles = False
self._updatefiles = False
self._purge = False
self._creatdirs = False
self._updatefiles = False
self.log('Difference of directory %s from %s... | def function[diff, parameter[self]]:
constant[
Only report difference in content between two directories
]
name[self]._copyfiles assign[=] constant[False]
name[self]._updatefiles assign[=] constant[False]
name[self]._purge assign[=] constant[False]
name[self]._cre... | keyword[def] identifier[diff] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_copyfiles] = keyword[False]
identifier[self] . identifier[_updatefiles] = keyword[False]
identifier[self] . identifier[_purge] = keyword[False]
identifier[self] . identi... | def diff(self):
"""
Only report difference in content between two directories
"""
self._copyfiles = False
self._updatefiles = False
self._purge = False
self._creatdirs = False
self._updatefiles = False
self.log('Difference of directory %s from %s\n' % (self._dir2, self._dir1)... |
def describe_reserved_db_instances_offerings(ReservedDBInstancesOfferingId=None, DBInstanceClass=None, Duration=None, ProductDescription=None, OfferingType=None, MultiAZ=None, Filters=None, MaxRecords=None, Marker=None):
"""
Lists available reserved DB instance offerings.
See also: AWS API Documentation
... | def function[describe_reserved_db_instances_offerings, parameter[ReservedDBInstancesOfferingId, DBInstanceClass, Duration, ProductDescription, OfferingType, MultiAZ, Filters, MaxRecords, Marker]]:
constant[
Lists available reserved DB instance offerings.
See also: AWS API Documentation
Examples... | keyword[def] identifier[describe_reserved_db_instances_offerings] ( identifier[ReservedDBInstancesOfferingId] = keyword[None] , identifier[DBInstanceClass] = keyword[None] , identifier[Duration] = keyword[None] , identifier[ProductDescription] = keyword[None] , identifier[OfferingType] = keyword[None] , identifier[Mu... | def describe_reserved_db_instances_offerings(ReservedDBInstancesOfferingId=None, DBInstanceClass=None, Duration=None, ProductDescription=None, OfferingType=None, MultiAZ=None, Filters=None, MaxRecords=None, Marker=None):
"""
Lists available reserved DB instance offerings.
See also: AWS API Documentation
... |
def random_ucast_ip():
"""
Function to generate a random unicast ip address
:return:
A unicast IP Address
"""
first_octet = str(__random.randrange(1, 224))
def get_other_octetes():
return str(__random.randrange(0, 255))
return '{first_octet}.{second_octet}.{third_octe... | def function[random_ucast_ip, parameter[]]:
constant[
Function to generate a random unicast ip address
:return:
A unicast IP Address
]
variable[first_octet] assign[=] call[name[str], parameter[call[name[__random].randrange, parameter[constant[1], constant[224]]]]]
def f... | keyword[def] identifier[random_ucast_ip] ():
literal[string]
identifier[first_octet] = identifier[str] ( identifier[__random] . identifier[randrange] ( literal[int] , literal[int] ))
keyword[def] identifier[get_other_octetes] ():
keyword[return] identifier[str] ( identifier[__random] . ide... | def random_ucast_ip():
"""
Function to generate a random unicast ip address
:return:
A unicast IP Address
"""
first_octet = str(__random.randrange(1, 224))
def get_other_octetes():
return str(__random.randrange(0, 255))
return '{first_octet}.{second_octet}.{third_octet... |
def changed_bit_pos(a, b):
"""
Return the index of the first bit that changed between `a` an `b`.
Return None if there are no changed bits.
"""
c = a ^ b
n = 0
while c > 0:
if c & 1 == 1:
return n
c >>= 1
n += 1
return None | def function[changed_bit_pos, parameter[a, b]]:
constant[
Return the index of the first bit that changed between `a` an `b`.
Return None if there are no changed bits.
]
variable[c] assign[=] binary_operation[name[a] <ast.BitXor object at 0x7da2590d6b00> name[b]]
variable[n] assign[=]... | keyword[def] identifier[changed_bit_pos] ( identifier[a] , identifier[b] ):
literal[string]
identifier[c] = identifier[a] ^ identifier[b]
identifier[n] = literal[int]
keyword[while] identifier[c] > literal[int] :
keyword[if] identifier[c] & literal[int] == literal[int] :
... | def changed_bit_pos(a, b):
"""
Return the index of the first bit that changed between `a` an `b`.
Return None if there are no changed bits.
"""
c = a ^ b
n = 0
while c > 0:
if c & 1 == 1:
return n # depends on [control=['if'], data=[]]
c >>= 1
n += 1 # d... |
def check_permissions(self, request):
""" Retrieves the controlled object and perform the permissions check. """
obj = (
hasattr(self, 'get_controlled_object') and self.get_controlled_object() or
hasattr(self, 'get_object') and self.get_object() or getattr(self, 'object', None)
... | def function[check_permissions, parameter[self, request]]:
constant[ Retrieves the controlled object and perform the permissions check. ]
variable[obj] assign[=] <ast.BoolOp object at 0x7da1b11786a0>
variable[user] assign[=] name[request].user
variable[perms] assign[=] call[name[self].ge... | keyword[def] identifier[check_permissions] ( identifier[self] , identifier[request] ):
literal[string]
identifier[obj] =(
identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and] identifier[self] . identifier[get_controlled_object] () keyword[or]
identifier[hasatt... | def check_permissions(self, request):
""" Retrieves the controlled object and perform the permissions check. """
obj = hasattr(self, 'get_controlled_object') and self.get_controlled_object() or (hasattr(self, 'get_object') and self.get_object()) or getattr(self, 'object', None)
user = request.user
# Get... |
def get_object(self):
""" Returns the OrganizationUser object based on the primary keys for both
the organization and the organization user.
"""
if hasattr(self, "organization_user"):
return self.organization_user
organization_pk = self.kwargs.get("organization_pk", N... | def function[get_object, parameter[self]]:
constant[ Returns the OrganizationUser object based on the primary keys for both
the organization and the organization user.
]
if call[name[hasattr], parameter[name[self], constant[organization_user]]] begin[:]
return[name[self].organiza... | keyword[def] identifier[get_object] ( identifier[self] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
keyword[return] identifier[self] . identifier[organization_user]
identifier[organization_pk] = identifier[self] . identifier[kwa... | def get_object(self):
""" Returns the OrganizationUser object based on the primary keys for both
the organization and the organization user.
"""
if hasattr(self, 'organization_user'):
return self.organization_user # depends on [control=['if'], data=[]]
organization_pk = self.kwargs.... |
def __find_reports(self, report_type, usage_page, usage_id = 0):
"Find input report referencing HID usage control/data item"
if not self.is_opened():
raise HIDError("Device must be opened")
#
results = list()
if usage_page:
for report_id in self.rep... | def function[__find_reports, parameter[self, report_type, usage_page, usage_id]]:
constant[Find input report referencing HID usage control/data item]
if <ast.UnaryOp object at 0x7da1b065b040> begin[:]
<ast.Raise object at 0x7da1b0659c90>
variable[results] assign[=] call[name[list], param... | keyword[def] identifier[__find_reports] ( identifier[self] , identifier[report_type] , identifier[usage_page] , identifier[usage_id] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[is_opened] ():
keyword[raise] identifier[HIDError] ( liter... | def __find_reports(self, report_type, usage_page, usage_id=0):
"""Find input report referencing HID usage control/data item"""
if not self.is_opened():
raise HIDError('Device must be opened') # depends on [control=['if'], data=[]] #
results = list()
if usage_page:
for report_id in self... |
def get_builder_toplevel(self, builder):
"""Get the toplevel widget from a Gtk.Builder file.
The main view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, or not
a Gtk.Window, the first toplevel window found in the ... | def function[get_builder_toplevel, parameter[self, builder]]:
constant[Get the toplevel widget from a Gtk.Builder file.
The main view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, or not
a Gtk.Window, the first to... | keyword[def] identifier[get_builder_toplevel] ( identifier[self] , identifier[builder] ):
literal[string]
identifier[toplevel] = identifier[builder] . identifier[get_object] ( identifier[self] . identifier[toplevel_name] )
keyword[if] keyword[not] identifier[GObject] . identifier[type_is... | def get_builder_toplevel(self, builder):
"""Get the toplevel widget from a Gtk.Builder file.
The main view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, or not
a Gtk.Window, the first toplevel window found in the Gtk.... |
def getsockopt(self, level, optname, *args, **kwargs):
"""get the value of a given socket option
the values for ``level`` and ``optname`` will usually come from
constants in the standard library ``socket`` module. consult the unix
manpage ``getsockopt(2)`` for more information.
... | def function[getsockopt, parameter[self, level, optname]]:
constant[get the value of a given socket option
the values for ``level`` and ``optname`` will usually come from
constants in the standard library ``socket`` module. consult the unix
manpage ``getsockopt(2)`` for more information... | keyword[def] identifier[getsockopt] ( identifier[self] , identifier[level] , identifier[optname] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_sock] . identifier[getsockopt] ( identifier[level] , identifier[optname] ,* identifier[args]... | def getsockopt(self, level, optname, *args, **kwargs):
"""get the value of a given socket option
the values for ``level`` and ``optname`` will usually come from
constants in the standard library ``socket`` module. consult the unix
manpage ``getsockopt(2)`` for more information.
:pa... |
async def restrict_chat_member(self, chat_id: typing.Union[base.Integer, base.String],
user_id: base.Integer,
until_date: typing.Union[base.Integer, None] = None,
can_send_messages: typing.Union[base.Boolean, None] ... | <ast.AsyncFunctionDef object at 0x7da1b1736cb0> | keyword[async] keyword[def] identifier[restrict_chat_member] ( identifier[self] , identifier[chat_id] : identifier[typing] . identifier[Union] [ identifier[base] . identifier[Integer] , identifier[base] . identifier[String] ],
identifier[user_id] : identifier[base] . identifier[Integer] ,
identifier[until_date] : ... | async def restrict_chat_member(self, chat_id: typing.Union[base.Integer, base.String], user_id: base.Integer, until_date: typing.Union[base.Integer, None]=None, can_send_messages: typing.Union[base.Boolean, None]=None, can_send_media_messages: typing.Union[base.Boolean, None]=None, can_send_other_messages: typing.Union... |
def merge_coords(objs, compat='minimal', join='outer', priority_arg=None,
indexes=None):
"""Merge coordinate variables.
See merge_core below for argument descriptions. This works similarly to
merge_core, except everything we don't worry about whether variables are
coordinates or not.
... | def function[merge_coords, parameter[objs, compat, join, priority_arg, indexes]]:
constant[Merge coordinate variables.
See merge_core below for argument descriptions. This works similarly to
merge_core, except everything we don't worry about whether variables are
coordinates or not.
]
c... | keyword[def] identifier[merge_coords] ( identifier[objs] , identifier[compat] = literal[string] , identifier[join] = literal[string] , identifier[priority_arg] = keyword[None] ,
identifier[indexes] = keyword[None] ):
literal[string]
identifier[_assert_compat_valid] ( identifier[compat] )
identifier[c... | def merge_coords(objs, compat='minimal', join='outer', priority_arg=None, indexes=None):
"""Merge coordinate variables.
See merge_core below for argument descriptions. This works similarly to
merge_core, except everything we don't worry about whether variables are
coordinates or not.
"""
_asser... |
def brancher( # noqa: E302
self, branches=None, all_branches=False, tags=None, all_tags=False
):
"""Generator that iterates over specified revisions.
Args:
branches (list): a list of branches to iterate over.
all_branches (bool): iterate over all available branches.
tags (list): a ... | def function[brancher, parameter[self, branches, all_branches, tags, all_tags]]:
constant[Generator that iterates over specified revisions.
Args:
branches (list): a list of branches to iterate over.
all_branches (bool): iterate over all available branches.
tags (list): a list of tag... | keyword[def] identifier[brancher] (
identifier[self] , identifier[branches] = keyword[None] , identifier[all_branches] = keyword[False] , identifier[tags] = keyword[None] , identifier[all_tags] = keyword[False]
):
literal[string]
keyword[if] keyword[not] identifier[any] ([ identifier[branches] , identi... | def brancher(self, branches=None, all_branches=False, tags=None, all_tags=False): # noqa: E302
'Generator that iterates over specified revisions.\n\n Args:\n branches (list): a list of branches to iterate over.\n all_branches (bool): iterate over all available branches.\n tags (list): a lis... |
def otp(ctx, access_code):
"""
Manage OTP Application.
The YubiKey provides two keyboard-based slots which can each be configured
with a credential. Several credential types are supported.
A slot configuration may be write-protected with an access code. This
prevents the configuration to be ov... | def function[otp, parameter[ctx, access_code]]:
constant[
Manage OTP Application.
The YubiKey provides two keyboard-based slots which can each be configured
with a credential. Several credential types are supported.
A slot configuration may be write-protected with an access code. This
prev... | keyword[def] identifier[otp] ( identifier[ctx] , identifier[access_code] ):
literal[string]
identifier[ctx] . identifier[obj] [ literal[string] ]= identifier[OtpController] ( identifier[ctx] . identifier[obj] [ literal[string] ]. identifier[driver] )
keyword[if] identifier[access_code] keyword[is] ... | def otp(ctx, access_code):
"""
Manage OTP Application.
The YubiKey provides two keyboard-based slots which can each be configured
with a credential. Several credential types are supported.
A slot configuration may be write-protected with an access code. This
prevents the configuration to be ov... |
def get_manhole_factory(namespace, **passwords):
"""Get a Manhole Factory
"""
realm = manhole_ssh.TerminalRealm()
realm.chainedProtocolFactory.protocolFactory = (
lambda _: EnhancedColoredManhole(namespace)
)
p = portal.Portal(realm)
p.registerChecker(
checkers.InMemoryUser... | def function[get_manhole_factory, parameter[namespace]]:
constant[Get a Manhole Factory
]
variable[realm] assign[=] call[name[manhole_ssh].TerminalRealm, parameter[]]
name[realm].chainedProtocolFactory.protocolFactory assign[=] <ast.Lambda object at 0x7da18f722320>
variable[p] assign... | keyword[def] identifier[get_manhole_factory] ( identifier[namespace] ,** identifier[passwords] ):
literal[string]
identifier[realm] = identifier[manhole_ssh] . identifier[TerminalRealm] ()
identifier[realm] . identifier[chainedProtocolFactory] . identifier[protocolFactory] =(
keyword[lambda] id... | def get_manhole_factory(namespace, **passwords):
"""Get a Manhole Factory
"""
realm = manhole_ssh.TerminalRealm()
realm.chainedProtocolFactory.protocolFactory = lambda _: EnhancedColoredManhole(namespace)
p = portal.Portal(realm)
p.registerChecker(checkers.InMemoryUsernamePasswordDatabaseDontUse... |
def close(self, using=None, **kwargs):
"""
Closes the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.close`` unchanged.
"""
return self._get_connection(using).indices.close(index=self._name, **kwargs) | def function[close, parameter[self, using]]:
constant[
Closes the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.close`` unchanged.
]
return[call[call[name[self]._get_connection, parameter[name[using]]].indices.close, param... | keyword[def] identifier[close] ( identifier[self] , identifier[using] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_get_connection] ( identifier[using] ). identifier[indices] . identifier[close] ( identifier[index] = identifier[self] . ide... | def close(self, using=None, **kwargs):
"""
Closes the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.close`` unchanged.
"""
return self._get_connection(using).indices.close(index=self._name, **kwargs) |
def _valid_date(self):
"""Check and return a valid query date."""
date = self._parse_date(self.date)
if not date:
exit_after_echo(INVALID_DATE)
try:
date = datetime.strptime(date, '%Y%m%d')
except ValueError:
exit_after_echo(INVALID_DATE)
... | def function[_valid_date, parameter[self]]:
constant[Check and return a valid query date.]
variable[date] assign[=] call[name[self]._parse_date, parameter[name[self].date]]
if <ast.UnaryOp object at 0x7da18c4cc850> begin[:]
call[name[exit_after_echo], parameter[name[INVALID_DATE]... | keyword[def] identifier[_valid_date] ( identifier[self] ):
literal[string]
identifier[date] = identifier[self] . identifier[_parse_date] ( identifier[self] . identifier[date] )
keyword[if] keyword[not] identifier[date] :
identifier[exit_after_echo] ( identifier[INVALID_DATE... | def _valid_date(self):
"""Check and return a valid query date."""
date = self._parse_date(self.date)
if not date:
exit_after_echo(INVALID_DATE) # depends on [control=['if'], data=[]]
try:
date = datetime.strptime(date, '%Y%m%d') # depends on [control=['try'], data=[]]
except ValueE... |
def windows_from_blocksize(self, blocksize_xy=512):
"""Create rasterio.windows.Window instances with given size which fully cover the raster.
Arguments:
blocksize_xy {int or list of two int} -- Size of the window. If one integer is given it defines
the width and height of th... | def function[windows_from_blocksize, parameter[self, blocksize_xy]]:
constant[Create rasterio.windows.Window instances with given size which fully cover the raster.
Arguments:
blocksize_xy {int or list of two int} -- Size of the window. If one integer is given it defines
the... | keyword[def] identifier[windows_from_blocksize] ( identifier[self] , identifier[blocksize_xy] = literal[int] ):
literal[string]
identifier[meta] = identifier[self] . identifier[_get_template_for_given_resolution] ( identifier[self] . identifier[dst_res] , literal[string] )
identifier[width... | def windows_from_blocksize(self, blocksize_xy=512):
"""Create rasterio.windows.Window instances with given size which fully cover the raster.
Arguments:
blocksize_xy {int or list of two int} -- Size of the window. If one integer is given it defines
the width and height of the wi... |
def getUserByNumber(self, base, uidNumber):
""" search for a user in LDAP and return its DN and uid """
res = self.query(base, "uidNumber="+str(uidNumber), ['uid'])
if len(res) > 1:
raise InputError(uidNumber, "Multiple users found. Expecting one.")
return res[0][0], res[0][1]['uid'][0] | def function[getUserByNumber, parameter[self, base, uidNumber]]:
constant[ search for a user in LDAP and return its DN and uid ]
variable[res] assign[=] call[name[self].query, parameter[name[base], binary_operation[constant[uidNumber=] + call[name[str], parameter[name[uidNumber]]]], list[[<ast.Constant ... | keyword[def] identifier[getUserByNumber] ( identifier[self] , identifier[base] , identifier[uidNumber] ):
literal[string]
identifier[res] = identifier[self] . identifier[query] ( identifier[base] , literal[string] + identifier[str] ( identifier[uidNumber] ),[ literal[string] ])
keyword[if] identifier[len] ... | def getUserByNumber(self, base, uidNumber):
""" search for a user in LDAP and return its DN and uid """
res = self.query(base, 'uidNumber=' + str(uidNumber), ['uid'])
if len(res) > 1:
raise InputError(uidNumber, 'Multiple users found. Expecting one.') # depends on [control=['if'], data=[]]
retu... |
def businesstime_hours(self, d1, d2):
"""
Returns a datetime.timedelta of business hours between d1 and d2,
based on the length of the businessday
"""
open_hours = self.open_hours.seconds / 3600
btd = self.businesstimedelta(d1, d2)
btd_hours = btd.seconds / 3600
... | def function[businesstime_hours, parameter[self, d1, d2]]:
constant[
Returns a datetime.timedelta of business hours between d1 and d2,
based on the length of the businessday
]
variable[open_hours] assign[=] binary_operation[name[self].open_hours.seconds / constant[3600]]
... | keyword[def] identifier[businesstime_hours] ( identifier[self] , identifier[d1] , identifier[d2] ):
literal[string]
identifier[open_hours] = identifier[self] . identifier[open_hours] . identifier[seconds] / literal[int]
identifier[btd] = identifier[self] . identifier[businesstimedelta] ( ... | def businesstime_hours(self, d1, d2):
"""
Returns a datetime.timedelta of business hours between d1 and d2,
based on the length of the businessday
"""
open_hours = self.open_hours.seconds / 3600
btd = self.businesstimedelta(d1, d2)
btd_hours = btd.seconds / 3600
return datet... |
def max_pairs(shape):
"""[DEPRECATED] Compute the maximum number of record pairs possible."""
if not isinstance(shape, (tuple, list)):
x = get_length(shape)
n = int(x * (x - 1) / 2)
elif (isinstance(shape, (tuple, list)) and len(shape) == 1):
x = get_length(shape[0])
n = in... | def function[max_pairs, parameter[shape]]:
constant[[DEPRECATED] Compute the maximum number of record pairs possible.]
if <ast.UnaryOp object at 0x7da18f58c0d0> begin[:]
variable[x] assign[=] call[name[get_length], parameter[name[shape]]]
variable[n] assign[=] call[name[i... | keyword[def] identifier[max_pairs] ( identifier[shape] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[shape] ,( identifier[tuple] , identifier[list] )):
identifier[x] = identifier[get_length] ( identifier[shape] )
identifier[n] = identifier[int] ( ident... | def max_pairs(shape):
"""[DEPRECATED] Compute the maximum number of record pairs possible."""
if not isinstance(shape, (tuple, list)):
x = get_length(shape)
n = int(x * (x - 1) / 2) # depends on [control=['if'], data=[]]
elif isinstance(shape, (tuple, list)) and len(shape) == 1:
x =... |
def readWindowsFile(wfile):
""""
reading file with windows
wfile File containing window info
"""
window_file = wfile+'.wnd'
assert os.path.exists(window_file), '%s is missing.'%window_file
rv = SP.loadtxt(window_file)
return rv | def function[readWindowsFile, parameter[wfile]]:
constant["
reading file with windows
wfile File containing window info
]
variable[window_file] assign[=] binary_operation[name[wfile] + constant[.wnd]]
assert[call[name[os].path.exists, parameter[name[window_file]]]]
variable[rv... | keyword[def] identifier[readWindowsFile] ( identifier[wfile] ):
literal[string]
identifier[window_file] = identifier[wfile] + literal[string]
keyword[assert] identifier[os] . identifier[path] . identifier[exists] ( identifier[window_file] ), literal[string] % identifier[window_file]
identifier... | def readWindowsFile(wfile):
""""
reading file with windows
wfile File containing window info
"""
window_file = wfile + '.wnd'
assert os.path.exists(window_file), '%s is missing.' % window_file
rv = SP.loadtxt(window_file)
return rv |
def load_library(self,libname):
"""Given the name of a library, load it."""
paths = self.getpaths(libname)
for path in paths:
if os.path.exists(path):
return self.load(path)
raise ImportError("%s not found." % libname) | def function[load_library, parameter[self, libname]]:
constant[Given the name of a library, load it.]
variable[paths] assign[=] call[name[self].getpaths, parameter[name[libname]]]
for taget[name[path]] in starred[name[paths]] begin[:]
if call[name[os].path.exists, parameter[name[... | keyword[def] identifier[load_library] ( identifier[self] , identifier[libname] ):
literal[string]
identifier[paths] = identifier[self] . identifier[getpaths] ( identifier[libname] )
keyword[for] identifier[path] keyword[in] identifier[paths] :
keyword[if] identifier[os] .... | def load_library(self, libname):
"""Given the name of a library, load it."""
paths = self.getpaths(libname)
for path in paths:
if os.path.exists(path):
return self.load(path) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['path']]
raise ImportError('%s ... |
def _RunUserDefinedFunctions_(config, data, histObj, position, namespace=__name__):
"""
Return a single updated data record and history object after running user-defined functions
:param dict config: DWM configuration (see DataDictionary)
:param dict data: single record (dictionary) to which user-defin... | def function[_RunUserDefinedFunctions_, parameter[config, data, histObj, position, namespace]]:
constant[
Return a single updated data record and history object after running user-defined functions
:param dict config: DWM configuration (see DataDictionary)
:param dict data: single record (dictionar... | keyword[def] identifier[_RunUserDefinedFunctions_] ( identifier[config] , identifier[data] , identifier[histObj] , identifier[position] , identifier[namespace] = identifier[__name__] ):
literal[string]
identifier[udfConfig] = identifier[config] [ literal[string] ]
keyword[if] identifier[position] ... | def _RunUserDefinedFunctions_(config, data, histObj, position, namespace=__name__):
"""
Return a single updated data record and history object after running user-defined functions
:param dict config: DWM configuration (see DataDictionary)
:param dict data: single record (dictionary) to which user-defin... |
def init(self):
'''
Initialize the device.
Parameters of visa.ResourceManager().open_resource()
'''
super(Visa, self).init()
backend = self._init.get('backend', '') # Empty string means std. backend (NI VISA)
rm = visa.ResourceManager(backend)
try:
... | def function[init, parameter[self]]:
constant[
Initialize the device.
Parameters of visa.ResourceManager().open_resource()
]
call[call[name[super], parameter[name[Visa], name[self]]].init, parameter[]]
variable[backend] assign[=] call[name[self]._init.get, parameter[const... | keyword[def] identifier[init] ( identifier[self] ):
literal[string]
identifier[super] ( identifier[Visa] , identifier[self] ). identifier[init] ()
identifier[backend] = identifier[self] . identifier[_init] . identifier[get] ( literal[string] , literal[string] )
identifier[rm] = id... | def init(self):
"""
Initialize the device.
Parameters of visa.ResourceManager().open_resource()
"""
super(Visa, self).init()
backend = self._init.get('backend', '') # Empty string means std. backend (NI VISA)
rm = visa.ResourceManager(backend)
try:
logger.info('BASIL... |
def base_boxes(self):
"""
Get the list of vagrant base boxes
"""
return sorted(list(set([name for name, provider in self._box_list()]))) | def function[base_boxes, parameter[self]]:
constant[
Get the list of vagrant base boxes
]
return[call[name[sorted], parameter[call[name[list], parameter[call[name[set], parameter[<ast.ListComp object at 0x7da1b0062da0>]]]]]]] | keyword[def] identifier[base_boxes] ( identifier[self] ):
literal[string]
keyword[return] identifier[sorted] ( identifier[list] ( identifier[set] ([ identifier[name] keyword[for] identifier[name] , identifier[provider] keyword[in] identifier[self] . identifier[_box_list] ()]))) | def base_boxes(self):
"""
Get the list of vagrant base boxes
"""
return sorted(list(set([name for (name, provider) in self._box_list()]))) |
def _do_layout(self):
"""Layout sizers"""
dialog_main_sizer = wx.BoxSizer(wx.HORIZONTAL)
upper_sizer = wx.BoxSizer(wx.HORIZONTAL)
lower_sizer = wx.FlexGridSizer(2, 1, 5, 0)
lower_sizer.AddGrowableRow(0)
lower_sizer.AddGrowableCol(0)
button_sizer = wx.BoxSizer(wx.... | def function[_do_layout, parameter[self]]:
constant[Layout sizers]
variable[dialog_main_sizer] assign[=] call[name[wx].BoxSizer, parameter[name[wx].HORIZONTAL]]
variable[upper_sizer] assign[=] call[name[wx].BoxSizer, parameter[name[wx].HORIZONTAL]]
variable[lower_sizer] assign[=] call[na... | keyword[def] identifier[_do_layout] ( identifier[self] ):
literal[string]
identifier[dialog_main_sizer] = identifier[wx] . identifier[BoxSizer] ( identifier[wx] . identifier[HORIZONTAL] )
identifier[upper_sizer] = identifier[wx] . identifier[BoxSizer] ( identifier[wx] . identifier[HORIZON... | def _do_layout(self):
"""Layout sizers"""
dialog_main_sizer = wx.BoxSizer(wx.HORIZONTAL)
upper_sizer = wx.BoxSizer(wx.HORIZONTAL)
lower_sizer = wx.FlexGridSizer(2, 1, 5, 0)
lower_sizer.AddGrowableRow(0)
lower_sizer.AddGrowableCol(0)
button_sizer = wx.BoxSizer(wx.HORIZONTAL)
upper_sizer.A... |
def get_list_key(self, data, key, header_lines=2):
"""Get the list of a key elements.
Each element is a tuple (key=None, description, type=None).
Note that the tuple's element can differ depending on the key.
:param data: the data to proceed
:param key: the key
"""
... | def function[get_list_key, parameter[self, data, key, header_lines]]:
constant[Get the list of a key elements.
Each element is a tuple (key=None, description, type=None).
Note that the tuple's element can differ depending on the key.
:param data: the data to proceed
:param key: ... | keyword[def] identifier[get_list_key] ( identifier[self] , identifier[data] , identifier[key] , identifier[header_lines] = literal[int] ):
literal[string]
keyword[return] identifier[super] ( identifier[NumpydocTools] , identifier[self] ). identifier[get_list_key] ( identifier[data] , identifier[ke... | def get_list_key(self, data, key, header_lines=2):
"""Get the list of a key elements.
Each element is a tuple (key=None, description, type=None).
Note that the tuple's element can differ depending on the key.
:param data: the data to proceed
:param key: the key
"""
retu... |
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL Ord... | def function[_handle_iorder, parameter[self, state]]:
constant[
Take a state and apply the iorder system
]
if call[name[self].opts][constant[state_auto_order]] begin[:]
for taget[name[name]] in starred[name[state]] begin[:]
for taget[name[s_dec]] i... | keyword[def] identifier[_handle_iorder] ( identifier[self] , identifier[state] ):
literal[string]
keyword[if] identifier[self] . identifier[opts] [ literal[string] ]:
keyword[for] identifier[name] keyword[in] identifier[state] :
keyword[for] identifier[s_dec] key... | def _handle_iorder(self, state):
"""
Take a state and apply the iorder system
"""
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
... |
def write_results(self, filename):
"""Writes samples, model stats, acceptance fraction, and random state
to the given file.
Parameters
-----------
filename : str
The file to write to. The file is opened using the ``io`` class
in an an append state.
... | def function[write_results, parameter[self, filename]]:
constant[Writes samples, model stats, acceptance fraction, and random state
to the given file.
Parameters
-----------
filename : str
The file to write to. The file is opened using the ``io`` class
in... | keyword[def] identifier[write_results] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[with] identifier[self] . identifier[io] ( identifier[filename] , literal[string] ) keyword[as] identifier[fp] :
identifier[fp] . identifier[write_samples] ( identifier... | def write_results(self, filename):
"""Writes samples, model stats, acceptance fraction, and random state
to the given file.
Parameters
-----------
filename : str
The file to write to. The file is opened using the ``io`` class
in an an append state.
""... |
def read(filename, encoding='utf-8'):
"""
Read text from file ('filename')
Return text and encoding
"""
text, encoding = decode( open(filename, 'rb').read() )
return text, encoding | def function[read, parameter[filename, encoding]]:
constant[
Read text from file ('filename')
Return text and encoding
]
<ast.Tuple object at 0x7da1b21d7d00> assign[=] call[name[decode], parameter[call[call[name[open], parameter[name[filename], constant[rb]]].read, parameter[]]]]
return[... | keyword[def] identifier[read] ( identifier[filename] , identifier[encoding] = literal[string] ):
literal[string]
identifier[text] , identifier[encoding] = identifier[decode] ( identifier[open] ( identifier[filename] , literal[string] ). identifier[read] ())
keyword[return] identifier[text] , ident... | def read(filename, encoding='utf-8'):
"""
Read text from file ('filename')
Return text and encoding
"""
(text, encoding) = decode(open(filename, 'rb').read())
return (text, encoding) |
def start(self, network_name, trunk_name, trunk_type):
"""Starts DHCP server process.
in network_name of type str
Name of internal network DHCP server should attach to.
in trunk_name of type str
Name of internal network trunk.
in trunk_type of type str
... | def function[start, parameter[self, network_name, trunk_name, trunk_type]]:
constant[Starts DHCP server process.
in network_name of type str
Name of internal network DHCP server should attach to.
in trunk_name of type str
Name of internal network trunk.
in trun... | keyword[def] identifier[start] ( identifier[self] , identifier[network_name] , identifier[trunk_name] , identifier[trunk_type] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[network_name] , identifier[basestring] ):
keyword[raise] identifier[TypeErro... | def start(self, network_name, trunk_name, trunk_type):
"""Starts DHCP server process.
in network_name of type str
Name of internal network DHCP server should attach to.
in trunk_name of type str
Name of internal network trunk.
in trunk_type of type str
... |
def encode_invocation_params(params):
""" Returns a list of paramaters meant to be passed to JSON-RPC endpoints. """
final_params = []
for p in params:
if isinstance(p, bool):
final_params.append({'type': ContractParameterTypes.BOOLEAN.value, 'value': p})
elif isinstance(p, int):... | def function[encode_invocation_params, parameter[params]]:
constant[ Returns a list of paramaters meant to be passed to JSON-RPC endpoints. ]
variable[final_params] assign[=] list[[]]
for taget[name[p]] in starred[name[params]] begin[:]
if call[name[isinstance], parameter[name[p]... | keyword[def] identifier[encode_invocation_params] ( identifier[params] ):
literal[string]
identifier[final_params] =[]
keyword[for] identifier[p] keyword[in] identifier[params] :
keyword[if] identifier[isinstance] ( identifier[p] , identifier[bool] ):
identifier[final_params]... | def encode_invocation_params(params):
""" Returns a list of paramaters meant to be passed to JSON-RPC endpoints. """
final_params = []
for p in params:
if isinstance(p, bool):
final_params.append({'type': ContractParameterTypes.BOOLEAN.value, 'value': p}) # depends on [control=['if'], d... |
def _get_var_type_code(self, coltype):
'''Determines the two-character type code for a given variable type
Parameters
----------
coltype : type or np.dtype
The type of the variable
Returns
-------
str
The variable type code for the given ... | def function[_get_var_type_code, parameter[self, coltype]]:
constant[Determines the two-character type code for a given variable type
Parameters
----------
coltype : type or np.dtype
The type of the variable
Returns
-------
str
The variab... | keyword[def] identifier[_get_var_type_code] ( identifier[self] , identifier[coltype] ):
literal[string]
keyword[if] identifier[type] ( identifier[coltype] ) keyword[is] identifier[np] . identifier[dtype] :
identifier[var_type] = identifier[coltype] . identifier[kind] + identifier[st... | def _get_var_type_code(self, coltype):
"""Determines the two-character type code for a given variable type
Parameters
----------
coltype : type or np.dtype
The type of the variable
Returns
-------
str
The variable type code for the given type... |
def neighbors(self, **kwargs):
"""list[dict]: A list of dictionary items describing the operational
state of LLDP.
"""
urn = "{urn:brocade.com:mgmt:brocade-lldp-ext}"
result = []
has_more = ''
last_ifindex = ''
rbridge_id = None
if 'rbridge_id' i... | def function[neighbors, parameter[self]]:
constant[list[dict]: A list of dictionary items describing the operational
state of LLDP.
]
variable[urn] assign[=] constant[{urn:brocade.com:mgmt:brocade-lldp-ext}]
variable[result] assign[=] list[[]]
variable[has_more] assign[=]... | keyword[def] identifier[neighbors] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[urn] = literal[string]
identifier[result] =[]
identifier[has_more] = literal[string]
identifier[last_ifindex] = literal[string]
identifier[rbridge_id] ... | def neighbors(self, **kwargs):
"""list[dict]: A list of dictionary items describing the operational
state of LLDP.
"""
urn = '{urn:brocade.com:mgmt:brocade-lldp-ext}'
result = []
has_more = ''
last_ifindex = ''
rbridge_id = None
if 'rbridge_id' in kwargs:
rbridge_id =... |
def _apply_pre_prepare(self, pre_prepare: PrePrepare):
"""
Applies (but not commits) requests of the PrePrepare
to the ledger and state
"""
reqs = []
idx = 0
rejects = []
invalid_indices = []
suspicious = False
# 1. apply each request
... | def function[_apply_pre_prepare, parameter[self, pre_prepare]]:
constant[
Applies (but not commits) requests of the PrePrepare
to the ledger and state
]
variable[reqs] assign[=] list[[]]
variable[idx] assign[=] constant[0]
variable[rejects] assign[=] list[[]]
... | keyword[def] identifier[_apply_pre_prepare] ( identifier[self] , identifier[pre_prepare] : identifier[PrePrepare] ):
literal[string]
identifier[reqs] =[]
identifier[idx] = literal[int]
identifier[rejects] =[]
identifier[invalid_indices] =[]
identifier[suspiciou... | def _apply_pre_prepare(self, pre_prepare: PrePrepare):
"""
Applies (but not commits) requests of the PrePrepare
to the ledger and state
"""
reqs = []
idx = 0
rejects = []
invalid_indices = []
suspicious = False
# 1. apply each request
for req_key in pre_prepare.re... |
def copy_from(self, src, dest):
"""
copy a file or a directory from container or image to host system.
:param src: str, path to a file or a directory within container or image
:param dest: str, path to a file or a directory on host system
:return: None
"""
logger... | def function[copy_from, parameter[self, src, dest]]:
constant[
copy a file or a directory from container or image to host system.
:param src: str, path to a file or a directory within container or image
:param dest: str, path to a file or a directory on host system
:return: None... | keyword[def] identifier[copy_from] ( identifier[self] , identifier[src] , identifier[dest] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] , identifier[src] , identifier[dest] )
identifier[cmd] =[ literal[string] , literal[string] , literal[string] , identifier[... | def copy_from(self, src, dest):
"""
copy a file or a directory from container or image to host system.
:param src: str, path to a file or a directory within container or image
:param dest: str, path to a file or a directory on host system
:return: None
"""
logger.debug('... |
def apply_motion_tracks(self, tracks, accuracy=0.004):
"""
Similar to click but press the screen for the given time interval and then release
Args:
tracks (:py:obj:`list`): list of :py:class:`poco.utils.track.MotionTrack` object
accuracy (:py:obj:`float`): motion accuracy ... | def function[apply_motion_tracks, parameter[self, tracks, accuracy]]:
constant[
Similar to click but press the screen for the given time interval and then release
Args:
tracks (:py:obj:`list`): list of :py:class:`poco.utils.track.MotionTrack` object
accuracy (:py:obj:`floa... | keyword[def] identifier[apply_motion_tracks] ( identifier[self] , identifier[tracks] , identifier[accuracy] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[tracks] :
keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[repr... | def apply_motion_tracks(self, tracks, accuracy=0.004):
"""
Similar to click but press the screen for the given time interval and then release
Args:
tracks (:py:obj:`list`): list of :py:class:`poco.utils.track.MotionTrack` object
accuracy (:py:obj:`float`): motion accuracy for ... |
def _ReadEventDataIntoEvent(self, event):
"""Reads the data into the event.
This function is intended to offer backwards compatible event behavior.
Args:
event (EventObject): event.
"""
if self._storage_type != definitions.STORAGE_TYPE_SESSION:
return
event_data_identifier = event... | def function[_ReadEventDataIntoEvent, parameter[self, event]]:
constant[Reads the data into the event.
This function is intended to offer backwards compatible event behavior.
Args:
event (EventObject): event.
]
if compare[name[self]._storage_type not_equal[!=] name[definitions].STORA... | keyword[def] identifier[_ReadEventDataIntoEvent] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] identifier[self] . identifier[_storage_type] != identifier[definitions] . identifier[STORAGE_TYPE_SESSION] :
keyword[return]
identifier[event_data_identifier] = identifier[e... | def _ReadEventDataIntoEvent(self, event):
"""Reads the data into the event.
This function is intended to offer backwards compatible event behavior.
Args:
event (EventObject): event.
"""
if self._storage_type != definitions.STORAGE_TYPE_SESSION:
return # depends on [control=['if'], d... |
def params_size(num_components, component_params_size, name=None):
"""Number of `params` needed to create a `MixtureSameFamily` distribution.
Arguments:
num_components: Number of component distributions in the mixture
distribution.
component_params_size: Number of parameters needed to creat... | def function[params_size, parameter[num_components, component_params_size, name]]:
constant[Number of `params` needed to create a `MixtureSameFamily` distribution.
Arguments:
num_components: Number of component distributions in the mixture
distribution.
component_params_size: Number of ... | keyword[def] identifier[params_size] ( identifier[num_components] , identifier[component_params_size] , identifier[name] = keyword[None] ):
literal[string]
keyword[with] identifier[tf] . identifier[compat] . identifier[v1] . identifier[name_scope] ( identifier[name] , literal[string] ,
[ identifier[nu... | def params_size(num_components, component_params_size, name=None):
"""Number of `params` needed to create a `MixtureSameFamily` distribution.
Arguments:
num_components: Number of component distributions in the mixture
distribution.
component_params_size: Number of parameters needed to creat... |
def run(self):
"""
each plugin has to implement this method -- it is used to run the plugin actually
response from plugin is kept and used in json result response
"""
user_params = None
build_json = get_build_json()
git_url = os.environ['SOURCE_URI']
git_... | def function[run, parameter[self]]:
constant[
each plugin has to implement this method -- it is used to run the plugin actually
response from plugin is kept and used in json result response
]
variable[user_params] assign[=] constant[None]
variable[build_json] assign[=] c... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[user_params] = keyword[None]
identifier[build_json] = identifier[get_build_json] ()
identifier[git_url] = identifier[os] . identifier[environ] [ literal[string] ]
identifier[git_ref] = identifi... | def run(self):
"""
each plugin has to implement this method -- it is used to run the plugin actually
response from plugin is kept and used in json result response
"""
user_params = None
build_json = get_build_json()
git_url = os.environ['SOURCE_URI']
git_ref = os.environ.get... |
def init_layout(self):
""" Initialize the layout of the toolkit widget.
This method is called during the bottom-up pass. This method
should initialize the layout of the widget. The child widgets
will be fully initialized and layed out when this is called.
"""
widget... | def function[init_layout, parameter[self]]:
constant[ Initialize the layout of the toolkit widget.
This method is called during the bottom-up pass. This method
should initialize the layout of the widget. The child widgets
will be fully initialized and layed out when this is called.
... | keyword[def] identifier[init_layout] ( identifier[self] ):
literal[string]
identifier[widget] = identifier[self] . identifier[widget]
keyword[for] identifier[child_widget] keyword[in] identifier[self] . identifier[child_widgets] ():
identifier[widget] . identifier[addSubvi... | def init_layout(self):
""" Initialize the layout of the toolkit widget.
This method is called during the bottom-up pass. This method
should initialize the layout of the widget. The child widgets
will be fully initialized and layed out when this is called.
"""
widget = self.... |
def get_stats(package):
"""
Fetch raw statistics of a package, no corrections are made to this
data. You should use get_corrected_stats().
"""
grand_total = 0
if '==' in package:
package, version = package.split('==')
try:
package = normalize(package)
version = None... | def function[get_stats, parameter[package]]:
constant[
Fetch raw statistics of a package, no corrections are made to this
data. You should use get_corrected_stats().
]
variable[grand_total] assign[=] constant[0]
if compare[constant[==] in name[package]] begin[:]
<ast.... | keyword[def] identifier[get_stats] ( identifier[package] ):
literal[string]
identifier[grand_total] = literal[int]
keyword[if] literal[string] keyword[in] identifier[package] :
identifier[package] , identifier[version] = identifier[package] . identifier[split] ( literal[string] )
k... | def get_stats(package):
"""
Fetch raw statistics of a package, no corrections are made to this
data. You should use get_corrected_stats().
"""
grand_total = 0
if '==' in package:
(package, version) = package.split('==') # depends on [control=['if'], data=['package']]
try:
pa... |
def update_keywords(self):
"""653 Free Keywords."""
for field in record_get_field_instances(self.record, '653', ind1='1'):
subs = field_get_subfields(field)
new_subs = []
if 'a' in subs:
for val in subs['a']:
new_subs.extend([('9', ... | def function[update_keywords, parameter[self]]:
constant[653 Free Keywords.]
for taget[name[field]] in starred[call[name[record_get_field_instances], parameter[name[self].record, constant[653]]]] begin[:]
variable[subs] assign[=] call[name[field_get_subfields], parameter[name[field]]]
... | keyword[def] identifier[update_keywords] ( identifier[self] ):
literal[string]
keyword[for] identifier[field] keyword[in] identifier[record_get_field_instances] ( identifier[self] . identifier[record] , literal[string] , identifier[ind1] = literal[string] ):
identifier[subs] = ident... | def update_keywords(self):
"""653 Free Keywords."""
for field in record_get_field_instances(self.record, '653', ind1='1'):
subs = field_get_subfields(field)
new_subs = []
if 'a' in subs:
for val in subs['a']:
new_subs.extend([('9', 'author'), ('a', val)]) # d... |
def GetList(self):
"""Get Info on Current List
This is run in __init__ so you don't
have to run it again.
Access from self.schema
"""
# Build Request
soap_request = soap('GetList')
soap_request.add_parameter('listName', self.listName)
sel... | def function[GetList, parameter[self]]:
constant[Get Info on Current List
This is run in __init__ so you don't
have to run it again.
Access from self.schema
]
variable[soap_request] assign[=] call[name[soap], parameter[constant[GetList]]]
call[name[soap_r... | keyword[def] identifier[GetList] ( identifier[self] ):
literal[string]
identifier[soap_request] = identifier[soap] ( literal[string] )
identifier[soap_request] . identifier[add_parameter] ( literal[string] , identifier[self] . identifier[listName] )
identifier[self] . id... | def GetList(self):
"""Get Info on Current List
This is run in __init__ so you don't
have to run it again.
Access from self.schema
"""
# Build Request
soap_request = soap('GetList')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(... |
def build_data_access(host, port, database_name, collection_name):
"""
Create data access gateway.
:param host: The database server to connect to.
:type host: str
:param port: Database port.
:type port: int
:param database_name: Database name.
:type datab... | def function[build_data_access, parameter[host, port, database_name, collection_name]]:
constant[
Create data access gateway.
:param host: The database server to connect to.
:type host: str
:param port: Database port.
:type port: int
:param database_name: Databas... | keyword[def] identifier[build_data_access] ( identifier[host] , identifier[port] , identifier[database_name] , identifier[collection_name] ):
literal[string]
keyword[return] identifier[PyMongoDataAccess] ( literal[string] %( identifier[host] , identifier[port] ),
identifier[database_name]... | def build_data_access(host, port, database_name, collection_name):
"""
Create data access gateway.
:param host: The database server to connect to.
:type host: str
:param port: Database port.
:type port: int
:param database_name: Database name.
:type database_... |
def start_monitor(self):
"""Start the monitor."""
stdout_file, stderr_file = self.new_log_files("monitor")
process_info = ray.services.start_monitor(
self._redis_address,
stdout_file=stdout_file,
stderr_file=stderr_file,
autoscaling_config=self._ra... | def function[start_monitor, parameter[self]]:
constant[Start the monitor.]
<ast.Tuple object at 0x7da1b23459f0> assign[=] call[name[self].new_log_files, parameter[constant[monitor]]]
variable[process_info] assign[=] call[name[ray].services.start_monitor, parameter[name[self]._redis_address]]
... | keyword[def] identifier[start_monitor] ( identifier[self] ):
literal[string]
identifier[stdout_file] , identifier[stderr_file] = identifier[self] . identifier[new_log_files] ( literal[string] )
identifier[process_info] = identifier[ray] . identifier[services] . identifier[start_monitor] (
... | def start_monitor(self):
"""Start the monitor."""
(stdout_file, stderr_file) = self.new_log_files('monitor')
process_info = ray.services.start_monitor(self._redis_address, stdout_file=stdout_file, stderr_file=stderr_file, autoscaling_config=self._ray_params.autoscaling_config, redis_password=self._ray_param... |
def upload(self, f):
"""Upload a file to the Puush account.
Parameters:
* f: The file. Either a path to a file or a file-like object.
"""
if hasattr(f, 'read'):
needs_closing = False
else:
f = open(f, 'rb')
needs_closing = ... | def function[upload, parameter[self, f]]:
constant[Upload a file to the Puush account.
Parameters:
* f: The file. Either a path to a file or a file-like object.
]
if call[name[hasattr], parameter[name[f], constant[read]]] begin[:]
variable[needs_closi... | keyword[def] identifier[upload] ( identifier[self] , identifier[f] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[f] , literal[string] ):
identifier[needs_closing] = keyword[False]
keyword[else] :
identifier[f] = identifier[open] ( identifier[f]... | def upload(self, f):
"""Upload a file to the Puush account.
Parameters:
* f: The file. Either a path to a file or a file-like object.
"""
if hasattr(f, 'read'):
needs_closing = False # depends on [control=['if'], data=[]]
else:
f = open(f, 'rb')
... |
def get_file(self):
"""stub"""
if self.has_file_asset():
return self._get_asset_content(
Id(self.my_osid_object._my_map['fileId']['assetId']),
self.my_osid_object._my_map['fileId']['assetContentTypeId']).get_data()
raise IllegalState() | def function[get_file, parameter[self]]:
constant[stub]
if call[name[self].has_file_asset, parameter[]] begin[:]
return[call[call[name[self]._get_asset_content, parameter[call[name[Id], parameter[call[call[name[self].my_osid_object._my_map][constant[fileId]]][constant[assetId]]]], call[call[name... | keyword[def] identifier[get_file] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[has_file_asset] ():
keyword[return] identifier[self] . identifier[_get_asset_content] (
identifier[Id] ( identifier[self] . identifier[my_osid_object] . iden... | def get_file(self):
"""stub"""
if self.has_file_asset():
return self._get_asset_content(Id(self.my_osid_object._my_map['fileId']['assetId']), self.my_osid_object._my_map['fileId']['assetContentTypeId']).get_data() # depends on [control=['if'], data=[]]
raise IllegalState() |
def list_node(self, tab_level=-1):
"""
Lists the current Node and its children.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> ... | def function[list_node, parameter[self, tab_level]]:
constant[
Lists the current Node and its children.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", ... | keyword[def] identifier[list_node] ( identifier[self] , identifier[tab_level] =- literal[int] ):
literal[string]
identifier[output] = literal[string]
identifier[tab_level] += literal[int]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[tab_level] ):
... | def list_node(self, tab_level=-1):
"""
Lists the current Node and its children.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> prin... |
def save_value(self, key, value):
"""
Save an arbitrary, serializable `value` under `key`.
:param str key: A string identifier under which to store the value.
:param value: A serializable value
:return:
"""
with self.save_stream(key) as s:
s.write(val... | def function[save_value, parameter[self, key, value]]:
constant[
Save an arbitrary, serializable `value` under `key`.
:param str key: A string identifier under which to store the value.
:param value: A serializable value
:return:
]
with call[name[self].save_strea... | keyword[def] identifier[save_value] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
keyword[with] identifier[self] . identifier[save_stream] ( identifier[key] ) keyword[as] identifier[s] :
identifier[s] . identifier[write] ( identifier[value] ) | def save_value(self, key, value):
"""
Save an arbitrary, serializable `value` under `key`.
:param str key: A string identifier under which to store the value.
:param value: A serializable value
:return:
"""
with self.save_stream(key) as s:
s.write(value) # depen... |
def progressbar(stream, prefix='Loading: ', width=0.5, **options):
""" Generator filter to print a progress bar. """
size = len(stream)
if not size:
return stream
if 'width' not in options:
if width <= 1:
width = round(shutil.get_terminal_size()[0] * width)
options['w... | def function[progressbar, parameter[stream, prefix, width]]:
constant[ Generator filter to print a progress bar. ]
variable[size] assign[=] call[name[len], parameter[name[stream]]]
if <ast.UnaryOp object at 0x7da1b1600400> begin[:]
return[name[stream]]
if compare[constant[width] ... | keyword[def] identifier[progressbar] ( identifier[stream] , identifier[prefix] = literal[string] , identifier[width] = literal[int] ,** identifier[options] ):
literal[string]
identifier[size] = identifier[len] ( identifier[stream] )
keyword[if] keyword[not] identifier[size] :
keyword[return... | def progressbar(stream, prefix='Loading: ', width=0.5, **options):
""" Generator filter to print a progress bar. """
size = len(stream)
if not size:
return stream # depends on [control=['if'], data=[]]
if 'width' not in options:
if width <= 1:
width = round(shutil.get_termin... |
def analyzers_mapping(cls):
"""
Return instance of itself where all used properties are set to
:class:`FuncInfo`.
This method is used by the database, which map all the properties
defined here to itself, runs the functions as new processes and stores
the result in itself... | def function[analyzers_mapping, parameter[cls]]:
constant[
Return instance of itself where all used properties are set to
:class:`FuncInfo`.
This method is used by the database, which map all the properties
defined here to itself, runs the functions as new processes and stores
... | keyword[def] identifier[analyzers_mapping] ( identifier[cls] ):
literal[string]
keyword[import] identifier[analyzers]
keyword[return] identifier[cls] (
identifier[title_tags] = identifier[_compose_func] ( identifier[analyzers] . identifier[get_title_tags] ),
identifier... | def analyzers_mapping(cls):
"""
Return instance of itself where all used properties are set to
:class:`FuncInfo`.
This method is used by the database, which map all the properties
defined here to itself, runs the functions as new processes and stores
the result in itself. Be... |
def get_fields_and_fragment_names(
context: ValidationContext,
cached_fields_and_fragment_names: Dict,
parent_type: Optional[GraphQLNamedType],
selection_set: SelectionSetNode,
) -> Tuple[NodeAndDefCollection, List[str]]:
"""Get fields and referenced fragment names
Given a selection set, return... | def function[get_fields_and_fragment_names, parameter[context, cached_fields_and_fragment_names, parent_type, selection_set]]:
constant[Get fields and referenced fragment names
Given a selection set, return the collection of fields (a mapping of response name
to field nodes and definitions) as well as ... | keyword[def] identifier[get_fields_and_fragment_names] (
identifier[context] : identifier[ValidationContext] ,
identifier[cached_fields_and_fragment_names] : identifier[Dict] ,
identifier[parent_type] : identifier[Optional] [ identifier[GraphQLNamedType] ],
identifier[selection_set] : identifier[SelectionSetNode]... | def get_fields_and_fragment_names(context: ValidationContext, cached_fields_and_fragment_names: Dict, parent_type: Optional[GraphQLNamedType], selection_set: SelectionSetNode) -> Tuple[NodeAndDefCollection, List[str]]:
"""Get fields and referenced fragment names
Given a selection set, return the collection of ... |
def _create_doc_summary(self, obj, fullname, refrole):
"""Create a paragraph containing the object's one-sentence docstring
summary with a link to further documentation.
The paragrah should be inserted into the ``desc`` node's
``desc_content``.
"""
summary_text = extract... | def function[_create_doc_summary, parameter[self, obj, fullname, refrole]]:
constant[Create a paragraph containing the object's one-sentence docstring
summary with a link to further documentation.
The paragrah should be inserted into the ``desc`` node's
``desc_content``.
]
... | keyword[def] identifier[_create_doc_summary] ( identifier[self] , identifier[obj] , identifier[fullname] , identifier[refrole] ):
literal[string]
identifier[summary_text] = identifier[extract_docstring_summary] ( identifier[get_docstring] ( identifier[obj] ))
identifier[summary_text] = ide... | def _create_doc_summary(self, obj, fullname, refrole):
"""Create a paragraph containing the object's one-sentence docstring
summary with a link to further documentation.
The paragrah should be inserted into the ``desc`` node's
``desc_content``.
"""
summary_text = extract_docstri... |
def ToVegaMag(self, wave, flux, **kwargs):
"""Convert to ``vegamag``.
.. math::
\\textnormal{vegamag} = -2.5 \\; \\log(\\frac{\\textnormal{photlam}}{f_{\\textnormal{Vega}}})
where :math:`f_{\\textnormal{Vega}}` is the flux of
:ref:`pysynphot-vega-spec` resampled at given w... | def function[ToVegaMag, parameter[self, wave, flux]]:
constant[Convert to ``vegamag``.
.. math::
\textnormal{vegamag} = -2.5 \; \log(\frac{\textnormal{photlam}}{f_{\textnormal{Vega}}})
where :math:`f_{\textnormal{Vega}}` is the flux of
:ref:`pysynphot-vega-spec` resampled ... | keyword[def] identifier[ToVegaMag] ( identifier[self] , identifier[wave] , identifier[flux] ,** identifier[kwargs] ):
literal[string]
keyword[from] . keyword[import] identifier[spectrum]
identifier[resampled] = identifier[spectrum] . identifier[Vega] . identifier[resample] ( identifier[w... | def ToVegaMag(self, wave, flux, **kwargs):
"""Convert to ``vegamag``.
.. math::
\\textnormal{vegamag} = -2.5 \\; \\log(\\frac{\\textnormal{photlam}}{f_{\\textnormal{Vega}}})
where :math:`f_{\\textnormal{Vega}}` is the flux of
:ref:`pysynphot-vega-spec` resampled at given wavel... |
def get_all_deferred_code_breakpoints(self):
"""
Returns a list of deferred code breakpoints.
@rtype: tuple of (int, str, callable, bool)
@return: Tuple containing the following elements:
- Process ID where to set the breakpoint.
- Label pointing to the addres... | def function[get_all_deferred_code_breakpoints, parameter[self]]:
constant[
Returns a list of deferred code breakpoints.
@rtype: tuple of (int, str, callable, bool)
@return: Tuple containing the following elements:
- Process ID where to set the breakpoint.
- L... | keyword[def] identifier[get_all_deferred_code_breakpoints] ( identifier[self] ):
literal[string]
identifier[result] =[]
keyword[for] identifier[pid] , identifier[deferred] keyword[in] identifier[compat] . identifier[iteritems] ( identifier[self] . identifier[__deferredBP] ):
... | def get_all_deferred_code_breakpoints(self):
"""
Returns a list of deferred code breakpoints.
@rtype: tuple of (int, str, callable, bool)
@return: Tuple containing the following elements:
- Process ID where to set the breakpoint.
- Label pointing to the address wh... |
def check_guest_exist(check_index=0):
"""Check guest exist in database.
:param check_index: The parameter index of userid(s), default as 0
"""
def outer(f):
@six.wraps(f)
def inner(self, *args, **kw):
userids = args[check_index]
if isinstance(userids, list):
... | def function[check_guest_exist, parameter[check_index]]:
constant[Check guest exist in database.
:param check_index: The parameter index of userid(s), default as 0
]
def function[outer, parameter[f]]:
def function[inner, parameter[self]]:
variable[userid... | keyword[def] identifier[check_guest_exist] ( identifier[check_index] = literal[int] ):
literal[string]
keyword[def] identifier[outer] ( identifier[f] ):
@ identifier[six] . identifier[wraps] ( identifier[f] )
keyword[def] identifier[inner] ( identifier[self] ,* identifier[args] ,** iden... | def check_guest_exist(check_index=0):
"""Check guest exist in database.
:param check_index: The parameter index of userid(s), default as 0
"""
def outer(f):
@six.wraps(f)
def inner(self, *args, **kw):
userids = args[check_index]
if isinstance(userids, list):
... |
def valid_file(value):
"""
Check if given file exists and is a regular file.
Args:
value (str): path to the file.
Raises:
argparse.ArgumentTypeError: if not valid.
Returns:
str: original value argument.
"""
if not value:
raise argparse.ArgumentTypeError("''... | def function[valid_file, parameter[value]]:
constant[
Check if given file exists and is a regular file.
Args:
value (str): path to the file.
Raises:
argparse.ArgumentTypeError: if not valid.
Returns:
str: original value argument.
]
if <ast.UnaryOp object at... | keyword[def] identifier[valid_file] ( identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[value] :
keyword[raise] identifier[argparse] . identifier[ArgumentTypeError] ( literal[string] )
keyword[elif] keyword[not] identifier[os] . identifier[path] . identifier[exists... | def valid_file(value):
"""
Check if given file exists and is a regular file.
Args:
value (str): path to the file.
Raises:
argparse.ArgumentTypeError: if not valid.
Returns:
str: original value argument.
"""
if not value:
raise argparse.ArgumentTypeError("''... |
def amplify_ground_shaking(T, vs30, gmvs):
"""
:param T: period
:param vs30: velocity
:param gmvs: ground motion values for the current site in units of g
"""
gmvs[gmvs > MAX_GMV] = MAX_GMV # accelerations > 5g are absurd
interpolator = interpolate.interp1d(
[0, 0.1, 0.2, 0.3, 0.4, ... | def function[amplify_ground_shaking, parameter[T, vs30, gmvs]]:
constant[
:param T: period
:param vs30: velocity
:param gmvs: ground motion values for the current site in units of g
]
call[name[gmvs]][compare[name[gmvs] greater[>] name[MAX_GMV]]] assign[=] name[MAX_GMV]
variable[... | keyword[def] identifier[amplify_ground_shaking] ( identifier[T] , identifier[vs30] , identifier[gmvs] ):
literal[string]
identifier[gmvs] [ identifier[gmvs] > identifier[MAX_GMV] ]= identifier[MAX_GMV]
identifier[interpolator] = identifier[interpolate] . identifier[interp1d] (
[ literal[int] , li... | def amplify_ground_shaking(T, vs30, gmvs):
"""
:param T: period
:param vs30: velocity
:param gmvs: ground motion values for the current site in units of g
"""
gmvs[gmvs > MAX_GMV] = MAX_GMV # accelerations > 5g are absurd
interpolator = interpolate.interp1d([0, 0.1, 0.2, 0.3, 0.4, 5], [(760... |
def most_energetic(df):
"""Grab most energetic particle from mc_tracks dataframe."""
idx = df.groupby(['event_id'])['energy'].transform(max) == df['energy']
return df[idx].reindex() | def function[most_energetic, parameter[df]]:
constant[Grab most energetic particle from mc_tracks dataframe.]
variable[idx] assign[=] compare[call[call[call[name[df].groupby, parameter[list[[<ast.Constant object at 0x7da18f812a70>]]]]][constant[energy]].transform, parameter[name[max]]] equal[==] call[na... | keyword[def] identifier[most_energetic] ( identifier[df] ):
literal[string]
identifier[idx] = identifier[df] . identifier[groupby] ([ literal[string] ])[ literal[string] ]. identifier[transform] ( identifier[max] )== identifier[df] [ literal[string] ]
keyword[return] identifier[df] [ identifier[idx] ... | def most_energetic(df):
"""Grab most energetic particle from mc_tracks dataframe."""
idx = df.groupby(['event_id'])['energy'].transform(max) == df['energy']
return df[idx].reindex() |
def clean_dateobject_to_string(x):
"""Convert a Pandas Timestamp object or datetime object
to 'YYYY-MM-DD' string
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A Pandas Timestamp object or datetime object,
or an array of these objects
Returns
-... | def function[clean_dateobject_to_string, parameter[x]]:
constant[Convert a Pandas Timestamp object or datetime object
to 'YYYY-MM-DD' string
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A Pandas Timestamp object or datetime object,
or an array of t... | keyword[def] identifier[clean_dateobject_to_string] ( identifier[x] ):
literal[string]
keyword[import] identifier[numpy] keyword[as] identifier[np]
keyword[import] identifier[pandas] keyword[as] identifier[pd]
keyword[def] identifier[proc_elem] ( identifier[e] ):
keyword[try] :... | def clean_dateobject_to_string(x):
"""Convert a Pandas Timestamp object or datetime object
to 'YYYY-MM-DD' string
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A Pandas Timestamp object or datetime object,
or an array of these objects
Returns
-... |
def write_input(self, output_dir, make_dir_if_not_present=True,
write_cif=False, write_path_cif=False,
write_endpoint_inputs=False):
"""
NEB inputs has a special directory structure where inputs are in 00,
01, 02, ....
Args:
output_dir... | def function[write_input, parameter[self, output_dir, make_dir_if_not_present, write_cif, write_path_cif, write_endpoint_inputs]]:
constant[
NEB inputs has a special directory structure where inputs are in 00,
01, 02, ....
Args:
output_dir (str): Directory to output the VASP... | keyword[def] identifier[write_input] ( identifier[self] , identifier[output_dir] , identifier[make_dir_if_not_present] = keyword[True] ,
identifier[write_cif] = keyword[False] , identifier[write_path_cif] = keyword[False] ,
identifier[write_endpoint_inputs] = keyword[False] ):
literal[string]
ide... | def write_input(self, output_dir, make_dir_if_not_present=True, write_cif=False, write_path_cif=False, write_endpoint_inputs=False):
"""
NEB inputs has a special directory structure where inputs are in 00,
01, 02, ....
Args:
output_dir (str): Directory to output the VASP input f... |
def assert_datetime_about_now(actual, msg_fmt="{msg}"):
"""Fail if a datetime object is not within 5 seconds of the local time.
>>> assert_datetime_about_now(datetime.now())
>>> assert_datetime_about_now(datetime(1900, 1, 1, 12, 0, 0))
Traceback (most recent call last):
...
AssertionError: ... | def function[assert_datetime_about_now, parameter[actual, msg_fmt]]:
constant[Fail if a datetime object is not within 5 seconds of the local time.
>>> assert_datetime_about_now(datetime.now())
>>> assert_datetime_about_now(datetime(1900, 1, 1, 12, 0, 0))
Traceback (most recent call last):
.... | keyword[def] identifier[assert_datetime_about_now] ( identifier[actual] , identifier[msg_fmt] = literal[string] ):
literal[string]
identifier[now] = identifier[datetime] . identifier[now] ()
keyword[if] identifier[actual] keyword[is] keyword[None] :
identifier[msg] = literal[string]
... | def assert_datetime_about_now(actual, msg_fmt='{msg}'):
"""Fail if a datetime object is not within 5 seconds of the local time.
>>> assert_datetime_about_now(datetime.now())
>>> assert_datetime_about_now(datetime(1900, 1, 1, 12, 0, 0))
Traceback (most recent call last):
...
AssertionError: ... |
def remove_event_detect(channel):
"""
:param channel: the channel based on the numbering system you have specified
(:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`).
"""
_check_configured(channel, direction=IN)
pin = get_gpio_pin(_mode, channel)
event.remove_edge_dete... | def function[remove_event_detect, parameter[channel]]:
constant[
:param channel: the channel based on the numbering system you have specified
(:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`).
]
call[name[_check_configured], parameter[name[channel]]]
variable[... | keyword[def] identifier[remove_event_detect] ( identifier[channel] ):
literal[string]
identifier[_check_configured] ( identifier[channel] , identifier[direction] = identifier[IN] )
identifier[pin] = identifier[get_gpio_pin] ( identifier[_mode] , identifier[channel] )
identifier[event] . identifie... | def remove_event_detect(channel):
"""
:param channel: the channel based on the numbering system you have specified
(:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`).
"""
_check_configured(channel, direction=IN)
pin = get_gpio_pin(_mode, channel)
event.remove_edge_dete... |
def get_arguments():
"""Get the command line arguments"""
import argparse
parser = argparse.ArgumentParser(
description='Plot spectral responses for a set of satellite imagers')
parser.add_argument("--platform_name", '-p', nargs='*',
help="The Platform name",
... | def function[get_arguments, parameter[]]:
constant[Get the command line arguments]
import module[argparse]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, parameter[constant[--platform_name], constant[-p]]]
call[name[parser]... | keyword[def] identifier[get_arguments] ():
literal[string]
keyword[import] identifier[argparse]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[description] = literal[string] )
identifier[parser] . identifier[add_argument] ( literal[string] , literal[st... | def get_arguments():
"""Get the command line arguments"""
import argparse
parser = argparse.ArgumentParser(description='Plot spectral responses for a set of satellite imagers')
parser.add_argument('--platform_name', '-p', nargs='*', help='The Platform name', type=str, required=True)
parser.add_argum... |
def contained_in(filename, directory):
"""Test if a file is located within the given directory."""
filename = os.path.normcase(os.path.abspath(filename))
directory = os.path.normcase(os.path.abspath(directory))
return os.path.commonprefix([filename, directory]) == directory | def function[contained_in, parameter[filename, directory]]:
constant[Test if a file is located within the given directory.]
variable[filename] assign[=] call[name[os].path.normcase, parameter[call[name[os].path.abspath, parameter[name[filename]]]]]
variable[directory] assign[=] call[name[os].pat... | keyword[def] identifier[contained_in] ( identifier[filename] , identifier[directory] ):
literal[string]
identifier[filename] = identifier[os] . identifier[path] . identifier[normcase] ( identifier[os] . identifier[path] . identifier[abspath] ( identifier[filename] ))
identifier[directory] = identifier... | def contained_in(filename, directory):
"""Test if a file is located within the given directory."""
filename = os.path.normcase(os.path.abspath(filename))
directory = os.path.normcase(os.path.abspath(directory))
return os.path.commonprefix([filename, directory]) == directory |
def get_content(self, params=None):
"""
Returns the raw byte content of a given Filelink
*returns* [Bytes]
```python
from filestack import Client
client = Client('API_KEY')
filelink = client.upload(filepath='/path/to/file/foo.jpg')
byte_content = fileli... | def function[get_content, parameter[self, params]]:
constant[
Returns the raw byte content of a given Filelink
*returns* [Bytes]
```python
from filestack import Client
client = Client('API_KEY')
filelink = client.upload(filepath='/path/to/file/foo.jpg')
... | keyword[def] identifier[get_content] ( identifier[self] , identifier[params] = keyword[None] ):
literal[string]
keyword[if] identifier[params] :
identifier[CONTENT_DOWNLOAD_SCHEMA] . identifier[check] ( identifier[params] )
identifier[response] = identifier[utils] . identifie... | def get_content(self, params=None):
"""
Returns the raw byte content of a given Filelink
*returns* [Bytes]
```python
from filestack import Client
client = Client('API_KEY')
filelink = client.upload(filepath='/path/to/file/foo.jpg')
byte_content = filelink.g... |
def config_examples(dest, user_dir):
""" Copy the example workflows to a directory.
\b
DEST: Path to which the examples should be copied.
"""
examples_path = Path(lightflow.__file__).parents[1] / 'examples'
if examples_path.exists():
dest_path = Path(dest).resolve()
if not user_... | def function[config_examples, parameter[dest, user_dir]]:
constant[ Copy the example workflows to a directory.
DEST: Path to which the examples should be copied.
]
variable[examples_path] assign[=] binary_operation[call[call[name[Path], parameter[name[lightflow].__file__]].parents][consta... | keyword[def] identifier[config_examples] ( identifier[dest] , identifier[user_dir] ):
literal[string]
identifier[examples_path] = identifier[Path] ( identifier[lightflow] . identifier[__file__] ). identifier[parents] [ literal[int] ]/ literal[string]
keyword[if] identifier[examples_path] . identifie... | def config_examples(dest, user_dir):
""" Copy the example workflows to a directory.
\x08
DEST: Path to which the examples should be copied.
"""
examples_path = Path(lightflow.__file__).parents[1] / 'examples'
if examples_path.exists():
dest_path = Path(dest).resolve()
if not use... |
def target_path (self):
""" Computes the target path that should be used for
target with these properties.
Returns a tuple of
- the computed path
- if the path is relative to build directory, a value of
'true'.
"""
if not self.t... | def function[target_path, parameter[self]]:
constant[ Computes the target path that should be used for
target with these properties.
Returns a tuple of
- the computed path
- if the path is relative to build directory, a value of
'true'.
... | keyword[def] identifier[target_path] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[target_path_] :
identifier[l] = identifier[self] . identifier[get] ( literal[string] )
keyword[if] identifier[l] :
... | def target_path(self):
""" Computes the target path that should be used for
target with these properties.
Returns a tuple of
- the computed path
- if the path is relative to build directory, a value of
'true'.
"""
if not self.target_pat... |
def delete_repository(self, repository, params=None):
"""
Removes a shared file system repository.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_
:arg repository: A comma-separated list of repository names
:arg master_timeout: Explicit... | def function[delete_repository, parameter[self, repository, params]]:
constant[
Removes a shared file system repository.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_
:arg repository: A comma-separated list of repository names
:arg ma... | keyword[def] identifier[delete_repository] ( identifier[self] , identifier[repository] , identifier[params] = keyword[None] ):
literal[string]
keyword[if] identifier[repository] keyword[in] identifier[SKIP_IN_PATH] :
keyword[raise] identifier[ValueError] ( literal[string] )
... | def delete_repository(self, repository, params=None):
"""
Removes a shared file system repository.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_
:arg repository: A comma-separated list of repository names
:arg master_timeout: Explicit ope... |
async def start(self, host=None, port=0, **kwargs):
"""
:py:func:`asyncio.coroutine`
Start server.
:param host: ip address to bind for listening.
:type host: :py:class:`str`
:param port: port number to bind for listening.
:type port: :py:class:`int`
:p... | <ast.AsyncFunctionDef object at 0x7da18f09ed40> | keyword[async] keyword[def] identifier[start] ( identifier[self] , identifier[host] = keyword[None] , identifier[port] = literal[int] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[_start_server_extra_arguments] = identifier[kwargs]
identifier[self] . identifier[... | async def start(self, host=None, port=0, **kwargs):
"""
:py:func:`asyncio.coroutine`
Start server.
:param host: ip address to bind for listening.
:type host: :py:class:`str`
:param port: port number to bind for listening.
:type port: :py:class:`int`
:param... |
def marshal_bson(
obj,
types=BSON_TYPES,
fields=None,
):
""" Recursively marshal a Python object to a BSON-compatible dict
that can be passed to PyMongo, Motor, etc...
Args:
obj: object, It's members can be nested Python
objects which will be converted to dictiona... | def function[marshal_bson, parameter[obj, types, fields]]:
constant[ Recursively marshal a Python object to a BSON-compatible dict
that can be passed to PyMongo, Motor, etc...
Args:
obj: object, It's members can be nested Python
objects which will be converted to dictiona... | keyword[def] identifier[marshal_bson] (
identifier[obj] ,
identifier[types] = identifier[BSON_TYPES] ,
identifier[fields] = keyword[None] ,
):
literal[string]
keyword[return] identifier[marshal_dict] (
identifier[obj] ,
identifier[types] ,
identifier[fields] = identifier[fields] ,
) | def marshal_bson(obj, types=BSON_TYPES, fields=None):
""" Recursively marshal a Python object to a BSON-compatible dict
that can be passed to PyMongo, Motor, etc...
Args:
obj: object, It's members can be nested Python
objects which will be converted to dictionaries
ty... |
def validate_feature_api(project, force=False):
"""Validate feature API"""
if not force and not project.on_pr():
raise SkippedValidationTest('Not on PR')
validator = FeatureApiValidator(project)
result = validator.validate()
if not result:
raise InvalidFeatureApi | def function[validate_feature_api, parameter[project, force]]:
constant[Validate feature API]
if <ast.BoolOp object at 0x7da18bcc9060> begin[:]
<ast.Raise object at 0x7da18bccb7c0>
variable[validator] assign[=] call[name[FeatureApiValidator], parameter[name[project]]]
variable[re... | keyword[def] identifier[validate_feature_api] ( identifier[project] , identifier[force] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[force] keyword[and] keyword[not] identifier[project] . identifier[on_pr] ():
keyword[raise] identifier[SkippedValidationTest] ( lite... | def validate_feature_api(project, force=False):
"""Validate feature API"""
if not force and (not project.on_pr()):
raise SkippedValidationTest('Not on PR') # depends on [control=['if'], data=[]]
validator = FeatureApiValidator(project)
result = validator.validate()
if not result:
ra... |
def change_first_point_by_coords(self, x, y, max_distance=1e-4,
raise_if_too_far_away=True):
"""
Set the first point of the exterior to the given point based on its coordinates.
If multiple points are found, the closest one will be picked.
If no matc... | def function[change_first_point_by_coords, parameter[self, x, y, max_distance, raise_if_too_far_away]]:
constant[
Set the first point of the exterior to the given point based on its coordinates.
If multiple points are found, the closest one will be picked.
If no matching points are foun... | keyword[def] identifier[change_first_point_by_coords] ( identifier[self] , identifier[x] , identifier[y] , identifier[max_distance] = literal[int] ,
identifier[raise_if_too_far_away] = keyword[True] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[exterior] )== liter... | def change_first_point_by_coords(self, x, y, max_distance=0.0001, raise_if_too_far_away=True):
"""
Set the first point of the exterior to the given point based on its coordinates.
If multiple points are found, the closest one will be picked.
If no matching points are found, an exception is ... |
def vb_get_network_adapters(machine_name=None, machine=None):
'''
A valid machine_name or a machine is needed to make this work!
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@return: INetorkAdapter's converted to dicts
@rtype: [dict]
'''
... | def function[vb_get_network_adapters, parameter[machine_name, machine]]:
constant[
A valid machine_name or a machine is needed to make this work!
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@return: INetorkAdapter's converted to dicts
@rtype:... | keyword[def] identifier[vb_get_network_adapters] ( identifier[machine_name] = keyword[None] , identifier[machine] = keyword[None] ):
literal[string]
keyword[if] identifier[machine_name] :
identifier[machine] = identifier[vb_get_box] (). identifier[findMachine] ( identifier[machine_name] )
i... | def vb_get_network_adapters(machine_name=None, machine=None):
"""
A valid machine_name or a machine is needed to make this work!
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@return: INetorkAdapter's converted to dicts
@rtype: [dict]
"""
i... |
def time_slice(self, t_from, t_to=None):
"""Return an new graph containing nodes and interactions present in [t_from, t_to].
Parameters
----------
t_from : snapshot id, mandatory
t_to : snapshot id, optional (default=None)
If None t_to will be se... | def function[time_slice, parameter[self, t_from, t_to]]:
constant[Return an new graph containing nodes and interactions present in [t_from, t_to].
Parameters
----------
t_from : snapshot id, mandatory
t_to : snapshot id, optional (default=None)
I... | keyword[def] identifier[time_slice] ( identifier[self] , identifier[t_from] , identifier[t_to] = keyword[None] ):
literal[string]
identifier[H] = identifier[self] . identifier[__class__] ()
keyword[if] identifier[t_to] keyword[is] keyword[not] keyword[None] :
key... | def time_slice(self, t_from, t_to=None):
"""Return an new graph containing nodes and interactions present in [t_from, t_to].
Parameters
----------
t_from : snapshot id, mandatory
t_to : snapshot id, optional (default=None)
If None t_to will be set eq... |
def napi_compare(left, ops, comparators, **kwargs):
"""Make pairwise comparisons of comparators."""
values = []
for op, right in zip(ops, comparators):
value = COMPARE[op](left, right)
values.append(value)
left = right
result = napi_and(values, **kwargs)
if isinstance(result... | def function[napi_compare, parameter[left, ops, comparators]]:
constant[Make pairwise comparisons of comparators.]
variable[values] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b277c430>, <ast.Name object at 0x7da1b277c460>]]] in starred[call[name[zip], parameter[name[ops], name... | keyword[def] identifier[napi_compare] ( identifier[left] , identifier[ops] , identifier[comparators] ,** identifier[kwargs] ):
literal[string]
identifier[values] =[]
keyword[for] identifier[op] , identifier[right] keyword[in] identifier[zip] ( identifier[ops] , identifier[comparators] ):
... | def napi_compare(left, ops, comparators, **kwargs):
"""Make pairwise comparisons of comparators."""
values = []
for (op, right) in zip(ops, comparators):
value = COMPARE[op](left, right)
values.append(value)
left = right # depends on [control=['for'], data=[]]
result = napi_and(... |
def __filter(filterable, filter_, logic_operation='and'):
""" filtering DataFrame using filter_ key-value conditions applying logic_operation
only find rows strictly fitting the filter_ criterion"""
condition = []
if not filter_:
return filterable
elif filter_.get('ty... | def function[__filter, parameter[filterable, filter_, logic_operation]]:
constant[ filtering DataFrame using filter_ key-value conditions applying logic_operation
only find rows strictly fitting the filter_ criterion]
variable[condition] assign[=] list[[]]
if <ast.UnaryOp object at 0x7da... | keyword[def] identifier[__filter] ( identifier[filterable] , identifier[filter_] , identifier[logic_operation] = literal[string] ):
literal[string]
identifier[condition] =[]
keyword[if] keyword[not] identifier[filter_] :
keyword[return] identifier[filterable]
keyw... | def __filter(filterable, filter_, logic_operation='and'):
""" filtering DataFrame using filter_ key-value conditions applying logic_operation
only find rows strictly fitting the filter_ criterion"""
condition = []
if not filter_:
return filterable # depends on [control=['if'], data=[]]
... |
def qry_coords(self):
'''Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the query sequence'''
return pyfastaq.intervals.Interval(min(self.qry_start, self.qry_end), max(self.qry_start, self.qry_end)) | def function[qry_coords, parameter[self]]:
constant[Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the query sequence]
return[call[name[pyfastaq].intervals.Interval, parameter[call[name[min], parameter[name[self].qry_start, name[self].qry_end]], call[name[max], parameter[na... | keyword[def] identifier[qry_coords] ( identifier[self] ):
literal[string]
keyword[return] identifier[pyfastaq] . identifier[intervals] . identifier[Interval] ( identifier[min] ( identifier[self] . identifier[qry_start] , identifier[self] . identifier[qry_end] ), identifier[max] ( identifier[self] ... | def qry_coords(self):
"""Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the query sequence"""
return pyfastaq.intervals.Interval(min(self.qry_start, self.qry_end), max(self.qry_start, self.qry_end)) |
def get_file_history_2(self, path):
"""
Returns history of file as reversed list of ``Changeset`` objects for
which file at given ``path`` has been modified.
"""
self._get_filectx(path)
from dulwich.walk import Walker
include = [self.id]
walker = Walker(s... | def function[get_file_history_2, parameter[self, path]]:
constant[
Returns history of file as reversed list of ``Changeset`` objects for
which file at given ``path`` has been modified.
]
call[name[self]._get_filectx, parameter[name[path]]]
from relative_module[dulwich.walk] ... | keyword[def] identifier[get_file_history_2] ( identifier[self] , identifier[path] ):
literal[string]
identifier[self] . identifier[_get_filectx] ( identifier[path] )
keyword[from] identifier[dulwich] . identifier[walk] keyword[import] identifier[Walker]
identifier[include] =[ ... | def get_file_history_2(self, path):
"""
Returns history of file as reversed list of ``Changeset`` objects for
which file at given ``path`` has been modified.
"""
self._get_filectx(path)
from dulwich.walk import Walker
include = [self.id]
walker = Walker(self.repository._repo... |
def _connect(self):
"""
Attemps connection to the server
"""
self.logger.info("Attempting connection to %s:%s", self.server[0], self.server[1])
try:
self._open_socket()
peer = self.sock.getpeername()
self.logger.info("Connected to %s", str(... | def function[_connect, parameter[self]]:
constant[
Attemps connection to the server
]
call[name[self].logger.info, parameter[constant[Attempting connection to %s:%s], call[name[self].server][constant[0]], call[name[self].server][constant[1]]]]
<ast.Try object at 0x7da1aff02d70>
... | keyword[def] identifier[_connect] ( identifier[self] ):
literal[string]
identifier[self] . identifier[logger] . identifier[info] ( literal[string] , identifier[self] . identifier[server] [ literal[int] ], identifier[self] . identifier[server] [ literal[int] ])
keyword[try] :
... | def _connect(self):
"""
Attemps connection to the server
"""
self.logger.info('Attempting connection to %s:%s', self.server[0], self.server[1])
try:
self._open_socket()
peer = self.sock.getpeername()
self.logger.info('Connected to %s', str(peer))
# 5 second ti... |
def classes(self):
"""return all class nodes in the diagram"""
return [o for o in self.objects if isinstance(o.node, astroid.ClassDef)] | def function[classes, parameter[self]]:
constant[return all class nodes in the diagram]
return[<ast.ListComp object at 0x7da1b020ffa0>] | keyword[def] identifier[classes] ( identifier[self] ):
literal[string]
keyword[return] [ identifier[o] keyword[for] identifier[o] keyword[in] identifier[self] . identifier[objects] keyword[if] identifier[isinstance] ( identifier[o] . identifier[node] , identifier[astroid] . identifier[ClassDe... | def classes(self):
"""return all class nodes in the diagram"""
return [o for o in self.objects if isinstance(o.node, astroid.ClassDef)] |
def handle_import(self, options):
"""
Gets the posts from either the provided URL or the path if it
is local.
"""
url = options.get("url")
if url is None:
raise CommandError("Usage is import_wordpress %s" % self.args)
try:
import feedparse... | def function[handle_import, parameter[self, options]]:
constant[
Gets the posts from either the provided URL or the path if it
is local.
]
variable[url] assign[=] call[name[options].get, parameter[constant[url]]]
if compare[name[url] is constant[None]] begin[:]
<a... | keyword[def] identifier[handle_import] ( identifier[self] , identifier[options] ):
literal[string]
identifier[url] = identifier[options] . identifier[get] ( literal[string] )
keyword[if] identifier[url] keyword[is] keyword[None] :
keyword[raise] identifier[CommandError] (... | def handle_import(self, options):
"""
Gets the posts from either the provided URL or the path if it
is local.
"""
url = options.get('url')
if url is None:
raise CommandError('Usage is import_wordpress %s' % self.args) # depends on [control=['if'], data=[]]
try:
i... |
def outputjson(self, obj):
"""
Serialize `obj` with JSON and output to the client
"""
self.header('Content-Type', 'application/json')
self.outputdata(json.dumps(obj).encode('ascii')) | def function[outputjson, parameter[self, obj]]:
constant[
Serialize `obj` with JSON and output to the client
]
call[name[self].header, parameter[constant[Content-Type], constant[application/json]]]
call[name[self].outputdata, parameter[call[call[name[json].dumps, parameter[name[o... | keyword[def] identifier[outputjson] ( identifier[self] , identifier[obj] ):
literal[string]
identifier[self] . identifier[header] ( literal[string] , literal[string] )
identifier[self] . identifier[outputdata] ( identifier[json] . identifier[dumps] ( identifier[obj] ). identifier[encode] (... | def outputjson(self, obj):
"""
Serialize `obj` with JSON and output to the client
"""
self.header('Content-Type', 'application/json')
self.outputdata(json.dumps(obj).encode('ascii')) |
def elevate_element(node, adopt_name=None, adopt_attrs=None):
"""
This method serves a specialized function. It comes up most often when
working with block level elements that may not be contained within
paragraph elements, which are presented in the source document as
inline ele... | def function[elevate_element, parameter[node, adopt_name, adopt_attrs]]:
constant[
This method serves a specialized function. It comes up most often when
working with block level elements that may not be contained within
paragraph elements, which are presented in the source document as
... | keyword[def] identifier[elevate_element] ( identifier[node] , identifier[adopt_name] = keyword[None] , identifier[adopt_attrs] = keyword[None] ):
literal[string]
identifier[parent] = identifier[node] . identifier[getparent] ()
identifier[grandparent] = identifier[parent] . identi... | def elevate_element(node, adopt_name=None, adopt_attrs=None):
"""
This method serves a specialized function. It comes up most often when
working with block level elements that may not be contained within
paragraph elements, which are presented in the source document as
inline element... |
def _find_matching_collections_externally(collections, record):
"""Find matching collections with percolator engine.
:param collections: set of collections where search
:param record: record to match
"""
index, doc_type = RecordIndexer().record_to_index(record)
body = {"doc": record.dumps()}
... | def function[_find_matching_collections_externally, parameter[collections, record]]:
constant[Find matching collections with percolator engine.
:param collections: set of collections where search
:param record: record to match
]
<ast.Tuple object at 0x7da1b0a71f60> assign[=] call[call[name[... | keyword[def] identifier[_find_matching_collections_externally] ( identifier[collections] , identifier[record] ):
literal[string]
identifier[index] , identifier[doc_type] = identifier[RecordIndexer] (). identifier[record_to_index] ( identifier[record] )
identifier[body] ={ literal[string] : identifier[... | def _find_matching_collections_externally(collections, record):
"""Find matching collections with percolator engine.
:param collections: set of collections where search
:param record: record to match
"""
(index, doc_type) = RecordIndexer().record_to_index(record)
body = {'doc': record.dumps()}
... |
def _format_name(self, name, surname, snake_case=False):
"""Format a first name and a surname into a cohesive string.
Note that either name or surname can be empty strings, and
formatting will still succeed.
:param str name: A first name.
:param str surname: A surname.
... | def function[_format_name, parameter[self, name, surname, snake_case]]:
constant[Format a first name and a surname into a cohesive string.
Note that either name or surname can be empty strings, and
formatting will still succeed.
:param str name: A first name.
:param str surname... | keyword[def] identifier[_format_name] ( identifier[self] , identifier[name] , identifier[surname] , identifier[snake_case] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[name] keyword[or] keyword[not] identifier[surname] :
identifier[sep] = literal[string]... | def _format_name(self, name, surname, snake_case=False):
"""Format a first name and a surname into a cohesive string.
Note that either name or surname can be empty strings, and
formatting will still succeed.
:param str name: A first name.
:param str surname: A surname.
:par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.