code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def action_print(reader, *args):
"""Simply print the Flow Log records to output."""
arg_count = len(args)
if arg_count == 0:
stop_after = 0
elif arg_count == 1:
stop_after = int(args[0])
else:
raise RuntimeError("0 or 1 arguments expected for action 'print'")
for i, reco... | Simply print the Flow Log records to output. | Below is the the instruction that describes the task:
### Input:
Simply print the Flow Log records to output.
### Response:
def action_print(reader, *args):
"""Simply print the Flow Log records to output."""
arg_count = len(args)
if arg_count == 0:
stop_after = 0
elif arg_count == 1:
... |
def add_node(self, node, weight=1):
"""Adds node to circle and rebuild it."""
self._nodes.add(node)
self._weights[node] = weight
self._rebuild_circle() | Adds node to circle and rebuild it. | Below is the the instruction that describes the task:
### Input:
Adds node to circle and rebuild it.
### Response:
def add_node(self, node, weight=1):
"""Adds node to circle and rebuild it."""
self._nodes.add(node)
self._weights[node] = weight
self._rebuild_circle() |
def remove_entry(data, entry):
'''
Remove an entry in place.
'''
file_field = entry['fields'].get('file')
if file_field:
try:
os.remove(file_field)
except IOError:
click.echo('This entry\'s file was missing')
data.remove(entry) | Remove an entry in place. | Below is the the instruction that describes the task:
### Input:
Remove an entry in place.
### Response:
def remove_entry(data, entry):
'''
Remove an entry in place.
'''
file_field = entry['fields'].get('file')
if file_field:
try:
os.remove(file_field)
except IOError... |
def as_dict(self):
"""
Makes Element obey the general json interface used in pymatgen for
easier serialization.
"""
return {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"element": self.symbol} | Makes Element obey the general json interface used in pymatgen for
easier serialization. | Below is the the instruction that describes the task:
### Input:
Makes Element obey the general json interface used in pymatgen for
easier serialization.
### Response:
def as_dict(self):
"""
Makes Element obey the general json interface used in pymatgen for
easier serialization.
... |
def moveforum_view(self, request, forum_id, direction):
""" Moves the given forum toward the requested direction. """
forum = get_object_or_404(Forum, pk=forum_id)
# Fetch the target
target, position = None, None
if direction == 'up':
target, position = forum.get_pre... | Moves the given forum toward the requested direction. | Below is the the instruction that describes the task:
### Input:
Moves the given forum toward the requested direction.
### Response:
def moveforum_view(self, request, forum_id, direction):
""" Moves the given forum toward the requested direction. """
forum = get_object_or_404(Forum, pk=forum_id)
... |
def stoch2array(self):
"""Return the stochastic objects as an array."""
a = np.empty(self.dim)
for stochastic in self.stochastics:
a[self._slices[stochastic]] = stochastic.value
return a | Return the stochastic objects as an array. | Below is the the instruction that describes the task:
### Input:
Return the stochastic objects as an array.
### Response:
def stoch2array(self):
"""Return the stochastic objects as an array."""
a = np.empty(self.dim)
for stochastic in self.stochastics:
a[self._slices[stochastic]... |
def _check_old_config_root():
"""
Prior versions of keyring would search for the config
in XDG_DATA_HOME, but should probably have been
searching for config in XDG_CONFIG_HOME. If the
config exists in the former but not in the latter,
raise a RuntimeError to force the change.
"""
# disab... | Prior versions of keyring would search for the config
in XDG_DATA_HOME, but should probably have been
searching for config in XDG_CONFIG_HOME. If the
config exists in the former but not in the latter,
raise a RuntimeError to force the change. | Below is the the instruction that describes the task:
### Input:
Prior versions of keyring would search for the config
in XDG_DATA_HOME, but should probably have been
searching for config in XDG_CONFIG_HOME. If the
config exists in the former but not in the latter,
raise a RuntimeError to force the ... |
def filebrowser(request, file_type):
""" Trigger view for filebrowser """
template = 'filebrowser.html'
upload_form = FileUploadForm()
uploaded_file = None
upload_tab_active = False
is_images_dialog = (file_type == 'img')
is_documents_dialog = (file_type == 'doc')
files = FileBrowse... | Trigger view for filebrowser | Below is the the instruction that describes the task:
### Input:
Trigger view for filebrowser
### Response:
def filebrowser(request, file_type):
""" Trigger view for filebrowser """
template = 'filebrowser.html'
upload_form = FileUploadForm()
uploaded_file = None
upload_tab_active = False
i... |
def ekopr(fname):
"""
Open an existing E-kernel file for reading.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopr_c.html
:param fname: Name of EK file.
:type fname: str
:return: Handle attached to EK file.
:rtype: int
"""
fname = stypes.stringToCharP(fname)
handle... | Open an existing E-kernel file for reading.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopr_c.html
:param fname: Name of EK file.
:type fname: str
:return: Handle attached to EK file.
:rtype: int | Below is the the instruction that describes the task:
### Input:
Open an existing E-kernel file for reading.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopr_c.html
:param fname: Name of EK file.
:type fname: str
:return: Handle attached to EK file.
:rtype: int
### Response:
def ... |
def lmeasure(reference_intervals_hier, reference_labels_hier,
estimated_intervals_hier, estimated_labels_hier,
frame_size=0.1, beta=1.0):
'''Computes the tree measures for hierarchical segment annotations.
Parameters
----------
reference_intervals_hier : list of ndarray
... | Computes the tree measures for hierarchical segment annotations.
Parameters
----------
reference_intervals_hier : list of ndarray
``reference_intervals_hier[i]`` contains the segment intervals
(in seconds) for the ``i`` th layer of the annotations. Layers are
ordered from top to bo... | Below is the the instruction that describes the task:
### Input:
Computes the tree measures for hierarchical segment annotations.
Parameters
----------
reference_intervals_hier : list of ndarray
``reference_intervals_hier[i]`` contains the segment intervals
(in seconds) for the ``i`` th... |
def _ValidatePathInfos(path_infos):
"""Validates a sequence of path infos."""
precondition.AssertIterableType(path_infos, rdf_objects.PathInfo)
validated = set()
for path_info in path_infos:
_ValidatePathInfo(path_info)
path_key = (path_info.path_type, path_info.GetPathID())
if path_key in validat... | Validates a sequence of path infos. | Below is the the instruction that describes the task:
### Input:
Validates a sequence of path infos.
### Response:
def _ValidatePathInfos(path_infos):
"""Validates a sequence of path infos."""
precondition.AssertIterableType(path_infos, rdf_objects.PathInfo)
validated = set()
for path_info in path_infos:
... |
def threaded(callback, listargs):
""" Returns the result of <callback> for each set of \*args in listargs. Each call
to <callback> is called concurrently in their own separate threads.
Parameters:
callback (func): Callback function to apply to each set of \*args.
listargs (l... | Returns the result of <callback> for each set of \*args in listargs. Each call
to <callback> is called concurrently in their own separate threads.
Parameters:
callback (func): Callback function to apply to each set of \*args.
listargs (list): List of lists; \*args to pass each t... | Below is the the instruction that describes the task:
### Input:
Returns the result of <callback> for each set of \*args in listargs. Each call
to <callback> is called concurrently in their own separate threads.
Parameters:
callback (func): Callback function to apply to each set of \*ar... |
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
... | Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
... | Below is the the instruction that describes the task:
### Input:
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of package... |
async def issuer_create_credential_offer(wallet_handle: int,
cred_def_id: str) -> str:
"""
Create credential offer that will be used by Prover for
credential request creation. Offer includes nonce and key correctness proof
for authentication between protocol step... | Create credential offer that will be used by Prover for
credential request creation. Offer includes nonce and key correctness proof
for authentication between protocol steps and integrity checking.
:param wallet_handle: wallet handler (created by open_wallet).
:param cred_def_id: id of credential defin... | Below is the the instruction that describes the task:
### Input:
Create credential offer that will be used by Prover for
credential request creation. Offer includes nonce and key correctness proof
for authentication between protocol steps and integrity checking.
:param wallet_handle: wallet handler (cr... |
def channelModeModifyAcknowledge():
"""CHANNEL MODE MODIFY ACKNOWLEDGE Section 9.1.6"""
a = TpPd(pd=0x6)
b = MessageType(mesType=0x17) # 00010111
c = ChannelDescription2()
d = ChannelMode()
packet = a / b / c / d
return packet | CHANNEL MODE MODIFY ACKNOWLEDGE Section 9.1.6 | Below is the the instruction that describes the task:
### Input:
CHANNEL MODE MODIFY ACKNOWLEDGE Section 9.1.6
### Response:
def channelModeModifyAcknowledge():
"""CHANNEL MODE MODIFY ACKNOWLEDGE Section 9.1.6"""
a = TpPd(pd=0x6)
b = MessageType(mesType=0x17) # 00010111
c = ChannelDescription2()
... |
def update_publisher_asset(self, upload_stream, publisher_name, asset_type=None, file_name=None, **kwargs):
"""UpdatePublisherAsset.
[Preview API] Update publisher asset like logo. It accepts asset file as an octet stream and file name is passed in header values.
:param object upload_stream: Str... | UpdatePublisherAsset.
[Preview API] Update publisher asset like logo. It accepts asset file as an octet stream and file name is passed in header values.
:param object upload_stream: Stream to upload
:param str publisher_name: Internal name of the publisher
:param str asset_type: Type of ... | Below is the the instruction that describes the task:
### Input:
UpdatePublisherAsset.
[Preview API] Update publisher asset like logo. It accepts asset file as an octet stream and file name is passed in header values.
:param object upload_stream: Stream to upload
:param str publisher_name: I... |
def query_symbol(self, asset: str) -> str:
"""
This interface is used to query the asset's symbol of ONT or ONG.
:param asset: a string which is used to indicate which asset's symbol we want to get.
:return: asset's symbol in the form of string.
"""
contract_address = se... | This interface is used to query the asset's symbol of ONT or ONG.
:param asset: a string which is used to indicate which asset's symbol we want to get.
:return: asset's symbol in the form of string. | Below is the the instruction that describes the task:
### Input:
This interface is used to query the asset's symbol of ONT or ONG.
:param asset: a string which is used to indicate which asset's symbol we want to get.
:return: asset's symbol in the form of string.
### Response:
def query_symbol(sel... |
def setup_sdk_logging(logfile=None, loglevel=logging.INFO):
"""
Setup a NullHandler to the root logger. If ``logfile`` is passed,
additionally add a FileHandler in ``loglevel`` level.
Args:
logfile(str): A path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
... | Setup a NullHandler to the root logger. If ``logfile`` is passed,
additionally add a FileHandler in ``loglevel`` level.
Args:
logfile(str): A path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
None | Below is the the instruction that describes the task:
### Input:
Setup a NullHandler to the root logger. If ``logfile`` is passed,
additionally add a FileHandler in ``loglevel`` level.
Args:
logfile(str): A path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
... |
def creator_type(self, creator_type):
"""Sets the creator_type of this Event.
:param creator_type: The creator_type of this Event. # noqa: E501
:type: list[str]
"""
allowed_values = ["USER", "ALERT", "SYSTEM"] # noqa: E501
if not set(creator_type).issubset(set(allowed... | Sets the creator_type of this Event.
:param creator_type: The creator_type of this Event. # noqa: E501
:type: list[str] | Below is the the instruction that describes the task:
### Input:
Sets the creator_type of this Event.
:param creator_type: The creator_type of this Event. # noqa: E501
:type: list[str]
### Response:
def creator_type(self, creator_type):
"""Sets the creator_type of this Event.
:... |
def getFeatureReport(self, report_num=0, length=63):
"""
Receive a feature report.
Blocks, unless you configured provided file (descriptor) to be
non-blocking.
"""
length += 1
buf = bytearray(length)
buf[0] = report_num
self._ioctl(
_HI... | Receive a feature report.
Blocks, unless you configured provided file (descriptor) to be
non-blocking. | Below is the the instruction that describes the task:
### Input:
Receive a feature report.
Blocks, unless you configured provided file (descriptor) to be
non-blocking.
### Response:
def getFeatureReport(self, report_num=0, length=63):
"""
Receive a feature report.
Blocks, un... |
def get_pipeline_yaml(file):
"""Return pipeline yaml from open file object.
Use specific custom representers to model the custom pypyr pipeline yaml
format, to load in special literal types like py and sic strings.
If looking to extend the pypyr pipeline syntax with special types, add
these to the... | Return pipeline yaml from open file object.
Use specific custom representers to model the custom pypyr pipeline yaml
format, to load in special literal types like py and sic strings.
If looking to extend the pypyr pipeline syntax with special types, add
these to the tag_representers list.
Args:
... | Below is the the instruction that describes the task:
### Input:
Return pipeline yaml from open file object.
Use specific custom representers to model the custom pypyr pipeline yaml
format, to load in special literal types like py and sic strings.
If looking to extend the pypyr pipeline syntax with sp... |
def add_tarball(self, tarball, package):
"""Add a tarball, possibly creating the directory if needed."""
if tarball is None:
logger.error(
"No tarball found for %s: probably a renamed project?",
package)
return
target_dir = os.path.join(sel... | Add a tarball, possibly creating the directory if needed. | Below is the the instruction that describes the task:
### Input:
Add a tarball, possibly creating the directory if needed.
### Response:
def add_tarball(self, tarball, package):
"""Add a tarball, possibly creating the directory if needed."""
if tarball is None:
logger.error(
... |
def corr(x, y, tail='two-sided', method='pearson'):
"""(Robust) correlation between two variables.
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
tail : string
Specify whether to return 'one-sided' or 'two-sided' p-value.
... | (Robust) correlation between two variables.
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
tail : string
Specify whether to return 'one-sided' or 'two-sided' p-value.
method : string
Specify which method to use for ... | Below is the the instruction that describes the task:
### Input:
(Robust) correlation between two variables.
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
tail : string
Specify whether to return 'one-sided' or 'two-sided' ... |
def get_event_data(self, section, time_in_seconds=False):
""" Get the template or complement event data.
:param section: Either template, complement, or both.
:param time_in_seconds: Return the start and length fields
in seconds, rather than samples.
:return: The eve... | Get the template or complement event data.
:param section: Either template, complement, or both.
:param time_in_seconds: Return the start and length fields
in seconds, rather than samples.
:return: The event dataset for the section. If section=both
then it return... | Below is the the instruction that describes the task:
### Input:
Get the template or complement event data.
:param section: Either template, complement, or both.
:param time_in_seconds: Return the start and length fields
in seconds, rather than samples.
:return: The even... |
def master_srcmdl_xml(self, **kwargs):
""" return the name of a source model file
"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
self._replace_none(kwargs_copy)
localpath = NameFactory.master_srcmdl_xml_format.format(**kwargs_copy)
if... | return the name of a source model file | Below is the the instruction that describes the task:
### Input:
return the name of a source model file
### Response:
def master_srcmdl_xml(self, **kwargs):
""" return the name of a source model file
"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
self._... |
def class_name_to_resource_name(class_name: str) -> str:
"""Converts a camel case class name to a resource name with spaces.
>>> class_name_to_resource_name('FooBarObject')
'Foo Bar Object'
:param class_name: The name to convert.
:returns: The resource name.
"""
s = re.sub('(.)([A-Z][a-z]+... | Converts a camel case class name to a resource name with spaces.
>>> class_name_to_resource_name('FooBarObject')
'Foo Bar Object'
:param class_name: The name to convert.
:returns: The resource name. | Below is the the instruction that describes the task:
### Input:
Converts a camel case class name to a resource name with spaces.
>>> class_name_to_resource_name('FooBarObject')
'Foo Bar Object'
:param class_name: The name to convert.
:returns: The resource name.
### Response:
def class_name_to_r... |
def clone(self, newname, config_path=None, flags=0, bdevtype=None,
bdevdata=None, newsize=0, hookargs=()):
"""
Clone the current container.
"""
args = {}
args['newname'] = newname
args['flags'] = flags
args['newsize'] = newsize
args['hoo... | Clone the current container. | Below is the the instruction that describes the task:
### Input:
Clone the current container.
### Response:
def clone(self, newname, config_path=None, flags=0, bdevtype=None,
bdevdata=None, newsize=0, hookargs=()):
"""
Clone the current container.
"""
args = {}
... |
def management_policies(self):
"""Instance depends on the API version:
* 2018-07-01: :class:`ManagementPoliciesOperations<azure.mgmt.storage.v2018_07_01.operations.ManagementPoliciesOperations>`
"""
api_version = self._get_api_version('management_policies')
if api_version == ... | Instance depends on the API version:
* 2018-07-01: :class:`ManagementPoliciesOperations<azure.mgmt.storage.v2018_07_01.operations.ManagementPoliciesOperations>` | Below is the the instruction that describes the task:
### Input:
Instance depends on the API version:
* 2018-07-01: :class:`ManagementPoliciesOperations<azure.mgmt.storage.v2018_07_01.operations.ManagementPoliciesOperations>`
### Response:
def management_policies(self):
"""Instance depends on t... |
def get_ipv6_neighbors_table(self):
"""Return the IPv6 neighbors table."""
ipv6_neighbors_table = []
ipv6_neighbors_table_raw = junos_views.junos_ipv6_neighbors_table(self.device)
ipv6_neighbors_table_raw.get()
ipv6_neighbors_table_items = ipv6_neighbors_table_raw.items()
... | Return the IPv6 neighbors table. | Below is the the instruction that describes the task:
### Input:
Return the IPv6 neighbors table.
### Response:
def get_ipv6_neighbors_table(self):
"""Return the IPv6 neighbors table."""
ipv6_neighbors_table = []
ipv6_neighbors_table_raw = junos_views.junos_ipv6_neighbors_table(self.device... |
def _should_split_column_cells(cls, column_cells: List[str]) -> bool:
"""
Returns true if there is any cell in this column that can be split.
"""
return any(cls._should_split_cell(cell_text) for cell_text in column_cells) | Returns true if there is any cell in this column that can be split. | Below is the the instruction that describes the task:
### Input:
Returns true if there is any cell in this column that can be split.
### Response:
def _should_split_column_cells(cls, column_cells: List[str]) -> bool:
"""
Returns true if there is any cell in this column that can be split.
""... |
def has_credentials_stored():
"""
Return 'auth token' string, if the user credentials are already stored
"""
try:
with open(credentials_file, 'r') as f:
token = f.readline().strip()
id = f.readline().strip()
return token
except Exception, e:
retu... | Return 'auth token' string, if the user credentials are already stored | Below is the the instruction that describes the task:
### Input:
Return 'auth token' string, if the user credentials are already stored
### Response:
def has_credentials_stored():
"""
Return 'auth token' string, if the user credentials are already stored
"""
try:
with open(credentials_file... |
def do_permissionif(parser, token):
"""
Permission if templatetag
Examples
--------
::
{% if user has 'blogs.add_article' %}
<p>This user have 'blogs.add_article' permission</p>
{% elif user has 'blog.change_article' of object %}
<p>This user have 'blogs.cha... | Permission if templatetag
Examples
--------
::
{% if user has 'blogs.add_article' %}
<p>This user have 'blogs.add_article' permission</p>
{% elif user has 'blog.change_article' of object %}
<p>This user have 'blogs.change_article' permission of {{object}}</p>
... | Below is the the instruction that describes the task:
### Input:
Permission if templatetag
Examples
--------
::
{% if user has 'blogs.add_article' %}
<p>This user have 'blogs.add_article' permission</p>
{% elif user has 'blog.change_article' of object %}
<p>This... |
def modify_prefix(channel, new_prefix):
"""
Creates an embed UI containing the prefix modified message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
new_prefix (str): The value of the new prefix
Returns:
embed: The created embed
"""
# Create... | Creates an embed UI containing the prefix modified message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
new_prefix (str): The value of the new prefix
Returns:
embed: The created embed | Below is the the instruction that describes the task:
### Input:
Creates an embed UI containing the prefix modified message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
new_prefix (str): The value of the new prefix
Returns:
embed: The created embed
### ... |
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_eth_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, "outpu... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_eth_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_i... |
def grid_tiles(self, bbox, zoomlevel):
"""
Return a grid of (x, y) tuples representing the juxtaposition
of tiles on the specified ``bbox`` at the specified ``zoomlevel``.
"""
tiles = self.tileslist(bbox, [zoomlevel])
grid = {}
for (z, x, y) in tiles:
... | Return a grid of (x, y) tuples representing the juxtaposition
of tiles on the specified ``bbox`` at the specified ``zoomlevel``. | Below is the the instruction that describes the task:
### Input:
Return a grid of (x, y) tuples representing the juxtaposition
of tiles on the specified ``bbox`` at the specified ``zoomlevel``.
### Response:
def grid_tiles(self, bbox, zoomlevel):
"""
Return a grid of (x, y) tuples represent... |
def allocate_correlation_matrix(self, iteration = None):
"""!
@brief Allocate correlation matrix between oscillators at the specified step of simulation.
@param[in] iteration (uint): Number of iteration of simulation for which correlation matrix should be allocated.
... | !
@brief Allocate correlation matrix between oscillators at the specified step of simulation.
@param[in] iteration (uint): Number of iteration of simulation for which correlation matrix should be allocated.
If iternation number is not specified, the last step of s... | Below is the the instruction that describes the task:
### Input:
!
@brief Allocate correlation matrix between oscillators at the specified step of simulation.
@param[in] iteration (uint): Number of iteration of simulation for which correlation matrix should be allocated.
... |
def from_main(cls, signature=''):
"""
A decorator that creates an instance and registers the decorated
function as main function, see :meth:`main` for more information.
.. versionadded:: 0.2
"""
instance = cls()
def decorate(function):
instance.main(... | A decorator that creates an instance and registers the decorated
function as main function, see :meth:`main` for more information.
.. versionadded:: 0.2 | Below is the the instruction that describes the task:
### Input:
A decorator that creates an instance and registers the decorated
function as main function, see :meth:`main` for more information.
.. versionadded:: 0.2
### Response:
def from_main(cls, signature=''):
"""
A decorator ... |
def on_key_press(self,symbol,modifiers):
"""
Keyboard event handler handling only the escape key.
If an escape key press is detected, mouse exclusivity is toggled via :py:meth:`PengWindow.toggle_exclusivity()`\ .
"""
if symbol == key.ESCAPE:
self.world.peng.w... | Keyboard event handler handling only the escape key.
If an escape key press is detected, mouse exclusivity is toggled via :py:meth:`PengWindow.toggle_exclusivity()`\ . | Below is the the instruction that describes the task:
### Input:
Keyboard event handler handling only the escape key.
If an escape key press is detected, mouse exclusivity is toggled via :py:meth:`PengWindow.toggle_exclusivity()`\ .
### Response:
def on_key_press(self,symbol,modifiers):
""... |
def _make_command_filename(self, exe):
"""The internal function to build up a filename based on a command."""
outfn = os.path.join(self.commons['cmddir'], self.name(),
self._mangle_command(exe))
# check for collisions
if os.path.exists(outfn):
i... | The internal function to build up a filename based on a command. | Below is the the instruction that describes the task:
### Input:
The internal function to build up a filename based on a command.
### Response:
def _make_command_filename(self, exe):
"""The internal function to build up a filename based on a command."""
outfn = os.path.join(self.commons['cmddir'],... |
def get_value(self, index):
""" Return the value of the given index
The index stores the section as internal pointer.
The row of the index determines the key.
The key is used on the section to return the value
:param index: The QModelIndex
:type index: QModelIndex
... | Return the value of the given index
The index stores the section as internal pointer.
The row of the index determines the key.
The key is used on the section to return the value
:param index: The QModelIndex
:type index: QModelIndex
:returns: The value for the given ind... | Below is the the instruction that describes the task:
### Input:
Return the value of the given index
The index stores the section as internal pointer.
The row of the index determines the key.
The key is used on the section to return the value
:param index: The QModelIndex
:... |
def diffPrefsPrior(priorstring):
"""Parses `priorstring` and returns `prior` tuple."""
assert isinstance(priorstring, str)
prior = priorstring.split(',')
if len(prior) == 3 and prior[0] == 'invquadratic':
[c1, c2] = [float(x) for x in prior[1 : ]]
assert c1 > 0 and c2 > 0, "C1 and C2 mus... | Parses `priorstring` and returns `prior` tuple. | Below is the the instruction that describes the task:
### Input:
Parses `priorstring` and returns `prior` tuple.
### Response:
def diffPrefsPrior(priorstring):
"""Parses `priorstring` and returns `prior` tuple."""
assert isinstance(priorstring, str)
prior = priorstring.split(',')
if len(prior) == 3... |
def ToByteArray(self):
"""Serialize the command.
Encodes the command as per the U2F specs, using the standard
ISO 7816-4 extended encoding. All Commands expect data, so
Le is always present.
Returns:
Python bytearray of the encoded command.
"""
lc = self.InternalEncodeLc()
out =... | Serialize the command.
Encodes the command as per the U2F specs, using the standard
ISO 7816-4 extended encoding. All Commands expect data, so
Le is always present.
Returns:
Python bytearray of the encoded command. | Below is the the instruction that describes the task:
### Input:
Serialize the command.
Encodes the command as per the U2F specs, using the standard
ISO 7816-4 extended encoding. All Commands expect data, so
Le is always present.
Returns:
Python bytearray of the encoded command.
### Respons... |
def edit_conf(edit_config=False, load_config=None, **kwargs):
"""
Edit the Andes config file which occurs first in the search path.
Parameters
----------
edit_config : bool
If ``True``, try to open up an editor and edit the config file.
Otherwise returns.
load_config : None or ... | Edit the Andes config file which occurs first in the search path.
Parameters
----------
edit_config : bool
If ``True``, try to open up an editor and edit the config file.
Otherwise returns.
load_config : None or str, optional
Path to the config file, which will be placed to the... | Below is the the instruction that describes the task:
### Input:
Edit the Andes config file which occurs first in the search path.
Parameters
----------
edit_config : bool
If ``True``, try to open up an editor and edit the config file.
Otherwise returns.
load_config : None or str, ... |
def Y_ampl(self, new_y_scale):
"""Make scaling on Y axis using predefined values"""
self.parent.value('y_scale', new_y_scale)
self.parent.traces.display() | Make scaling on Y axis using predefined values | Below is the the instruction that describes the task:
### Input:
Make scaling on Y axis using predefined values
### Response:
def Y_ampl(self, new_y_scale):
"""Make scaling on Y axis using predefined values"""
self.parent.value('y_scale', new_y_scale)
self.parent.traces.display() |
def GetSources(self, event):
"""Determines the the short and long source for an event object.
Args:
event (EventObject): event.
Returns:
tuple(str, str): short and long source string.
Raises:
WrongFormatter: if the event object cannot be formatted by the formatter.
"""
if se... | Determines the the short and long source for an event object.
Args:
event (EventObject): event.
Returns:
tuple(str, str): short and long source string.
Raises:
WrongFormatter: if the event object cannot be formatted by the formatter. | Below is the the instruction that describes the task:
### Input:
Determines the the short and long source for an event object.
Args:
event (EventObject): event.
Returns:
tuple(str, str): short and long source string.
Raises:
WrongFormatter: if the event object cannot be formatted by... |
def _generate_namespace():
"""
Generate an LSID namespace based off Jupyter user or system user
:return: string
"""
raw_namespace = None
# Get the Jupyter user, if available
try:
raw_namespace = os.environ['JPY_USER']
except KeyError:
... | Generate an LSID namespace based off Jupyter user or system user
:return: string | Below is the the instruction that describes the task:
### Input:
Generate an LSID namespace based off Jupyter user or system user
:return: string
### Response:
def _generate_namespace():
"""
Generate an LSID namespace based off Jupyter user or system user
:return: string
"""... |
def observer(self, component_type=ComponentType):
"""
You can use ``@broker.observer()`` as a decorator to your callback
instead of :func:`Broker.add_observer`.
"""
def inner(func):
self.add_observer(func, component_type)
return func
return inner | You can use ``@broker.observer()`` as a decorator to your callback
instead of :func:`Broker.add_observer`. | Below is the the instruction that describes the task:
### Input:
You can use ``@broker.observer()`` as a decorator to your callback
instead of :func:`Broker.add_observer`.
### Response:
def observer(self, component_type=ComponentType):
"""
You can use ``@broker.observer()`` as a decorator t... |
def aggregate_weights(weights, drop_date=False):
"""
Transforms list of tuples of weights into pandas.DataFrame of weights.
Parameters:
-----------
weights: list
A list of tuples consisting of the generic instrument name,
the tradeable contract as a string, the weight on this contra... | Transforms list of tuples of weights into pandas.DataFrame of weights.
Parameters:
-----------
weights: list
A list of tuples consisting of the generic instrument name,
the tradeable contract as a string, the weight on this contract as a
float and the date as a pandas.Timestamp.
... | Below is the the instruction that describes the task:
### Input:
Transforms list of tuples of weights into pandas.DataFrame of weights.
Parameters:
-----------
weights: list
A list of tuples consisting of the generic instrument name,
the tradeable contract as a string, the weight on thi... |
def load_state(self, state_id, delete=True):
"""
Load a state from storage identified by `state_id`.
:param state_id: The state reference of what to load
:return: The deserialized state
:rtype: State
"""
return self._store.load_state(f'{self._prefix}{state_id:08x... | Load a state from storage identified by `state_id`.
:param state_id: The state reference of what to load
:return: The deserialized state
:rtype: State | Below is the the instruction that describes the task:
### Input:
Load a state from storage identified by `state_id`.
:param state_id: The state reference of what to load
:return: The deserialized state
:rtype: State
### Response:
def load_state(self, state_id, delete=True):
"""
... |
def new_space(
self,
name=None,
bases=None,
formula=None,
*,
refs=None,
source=None,
is_derived=False,
prefix=""
):
"""Create a new child space.
Args:
name (str): Name of the space. If omitted, the space is
... | Create a new child space.
Args:
name (str): Name of the space. If omitted, the space is
created automatically.
bases: If specified, the new space becomes a derived space of
the `base` space.
formula: Function whose parameters used to set space... | Below is the the instruction that describes the task:
### Input:
Create a new child space.
Args:
name (str): Name of the space. If omitted, the space is
created automatically.
bases: If specified, the new space becomes a derived space of
the `base` sp... |
def validate(metric_class):
"""
Does basic Metric option validation.
"""
if not hasattr(metric_class, 'label'):
raise ImproperlyConfigured("No 'label' attribute found for metric %s." % metric_class.__name__)
if not hasattr(metric_class, 'widget'):
raise ImproperlyConfigured("No... | Does basic Metric option validation. | Below is the the instruction that describes the task:
### Input:
Does basic Metric option validation.
### Response:
def validate(metric_class):
"""
Does basic Metric option validation.
"""
if not hasattr(metric_class, 'label'):
raise ImproperlyConfigured("No 'label' attribute found for met... |
def fetch_access_token(self, url, verifier=None, **request_kwargs):
"""Fetch an access token.
This is the final step in the OAuth 1 workflow. An access token is
obtained using all previously obtained credentials, including the
verifier from the authorization step.
Note that a p... | Fetch an access token.
This is the final step in the OAuth 1 workflow. An access token is
obtained using all previously obtained credentials, including the
verifier from the authorization step.
Note that a previously set verifier will be reset for your
convenience, or else sign... | Below is the the instruction that describes the task:
### Input:
Fetch an access token.
This is the final step in the OAuth 1 workflow. An access token is
obtained using all previously obtained credentials, including the
verifier from the authorization step.
Note that a previously ... |
def load_file(self, path):
"""Load a YAML file with parameter data and other metadata.
:param path: Path to YAML file.
:type path: str
The data in the YAML file is used to set the properties for the instance.
The YAML file must contain a ``parameters`` key.
It may optio... | Load a YAML file with parameter data and other metadata.
:param path: Path to YAML file.
:type path: str
The data in the YAML file is used to set the properties for the instance.
The YAML file must contain a ``parameters`` key.
It may optionally include any keys defined in :att... | Below is the the instruction that describes the task:
### Input:
Load a YAML file with parameter data and other metadata.
:param path: Path to YAML file.
:type path: str
The data in the YAML file is used to set the properties for the instance.
The YAML file must contain a ``paramet... |
def reverse_mapping(mapping):
"""
For every key, value pair, return the mapping for the
equivalent value, key pair
>>> reverse_mapping({'a': 'b'}) == {'b': 'a'}
True
"""
keys, values = zip(*mapping.items())
return dict(zip(values, keys)) | For every key, value pair, return the mapping for the
equivalent value, key pair
>>> reverse_mapping({'a': 'b'}) == {'b': 'a'}
True | Below is the the instruction that describes the task:
### Input:
For every key, value pair, return the mapping for the
equivalent value, key pair
>>> reverse_mapping({'a': 'b'}) == {'b': 'a'}
True
### Response:
def reverse_mapping(mapping):
"""
For every key, value pair, return the mapping for the
equivalen... |
def show_fibrechannel_interface_info_output_show_fibrechannel_interface_portsgroup_rbridgeid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_fibrechannel_interface_info = ET.Element("show_fibrechannel_interface_info")
config = show_fibrechannel_inte... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def show_fibrechannel_interface_info_output_show_fibrechannel_interface_portsgroup_rbridgeid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_fibrechannel... |
def get_entries_for_scope(self, user_scope, scope_name, scope_value, key=None):
"""GetEntriesForScope.
[Preview API] Get all setting entries for the given named scope
:param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
... | GetEntriesForScope.
[Preview API] Get all setting entries for the given named scope
:param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
:param str scope_name: Scope at which to get the setting for (e.g. "project" or "team")
... | Below is the the instruction that describes the task:
### Input:
GetEntriesForScope.
[Preview API] Get all setting entries for the given named scope
:param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
:param str scope_name... |
def get_assessments_by_query(self, assessment_query):
"""Gets a list of ``Assessments`` matching the given assessment query.
arg: assessment_query (osid.assessment.AssessmentQuery): the
assessment query
return: (osid.assessment.AssessmentList) - the returned
`... | Gets a list of ``Assessments`` matching the given assessment query.
arg: assessment_query (osid.assessment.AssessmentQuery): the
assessment query
return: (osid.assessment.AssessmentList) - the returned
``AssessmentList``
raise: NullArgument - ``assessment_que... | Below is the the instruction that describes the task:
### Input:
Gets a list of ``Assessments`` matching the given assessment query.
arg: assessment_query (osid.assessment.AssessmentQuery): the
assessment query
return: (osid.assessment.AssessmentList) - the returned
... |
def write(self, target, *args, **kwargs):
"""Write this `SegmentList` to a file
Arguments and keywords depend on the output format, see the
online documentation for full details for each format.
Parameters
----------
target : `str`
output filename
N... | Write this `SegmentList` to a file
Arguments and keywords depend on the output format, see the
online documentation for full details for each format.
Parameters
----------
target : `str`
output filename
Notes
----- | Below is the the instruction that describes the task:
### Input:
Write this `SegmentList` to a file
Arguments and keywords depend on the output format, see the
online documentation for full details for each format.
Parameters
----------
target : `str`
output fil... |
def NewWalker(self, reader):
"""Setup an xmltextReader to parse a preparsed XML document.
This reuses the existing @reader xmlTextReader. """
if reader is None: reader__o = None
else: reader__o = reader._o
ret = libxml2mod.xmlReaderNewWalker(reader__o, self._o)
return ... | Setup an xmltextReader to parse a preparsed XML document.
This reuses the existing @reader xmlTextReader. | Below is the the instruction that describes the task:
### Input:
Setup an xmltextReader to parse a preparsed XML document.
This reuses the existing @reader xmlTextReader.
### Response:
def NewWalker(self, reader):
"""Setup an xmltextReader to parse a preparsed XML document.
This reuse... |
def nic_remove(self, nic):
"""
Detach a nic from a bridge
:param nic: nic name to detach
"""
args = {
'nic': nic,
}
self._nic_remove_chk.check(args)
return self._client.json('bridge.nic-remove', args) | Detach a nic from a bridge
:param nic: nic name to detach | Below is the the instruction that describes the task:
### Input:
Detach a nic from a bridge
:param nic: nic name to detach
### Response:
def nic_remove(self, nic):
"""
Detach a nic from a bridge
:param nic: nic name to detach
"""
args = {
'nic': nic,
... |
def allzeros(msg):
"""check if the data bits are all zeros
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
d = hex2bin(data(msg))
if bin2int(d) > 0:
return False
else:
return True | check if the data bits are all zeros
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False | Below is the the instruction that describes the task:
### Input:
check if the data bits are all zeros
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
### Response:
def allzeros(msg):
"""check if the data bits are all zeros
Args:
msg (S... |
def gamma_automatic(kpts=(1, 1, 1), shift=(0, 0, 0)):
"""
Convenient static constructor for an automatic Gamma centered Kpoint
grid.
Args:
kpts: Subdivisions N_1, N_2 and N_3 along reciprocal lattice
vectors. Defaults to (1,1,1)
shift: Shift to be... | Convenient static constructor for an automatic Gamma centered Kpoint
grid.
Args:
kpts: Subdivisions N_1, N_2 and N_3 along reciprocal lattice
vectors. Defaults to (1,1,1)
shift: Shift to be applied to the kpoints. Defaults to (0,0,0).
Returns:
... | Below is the the instruction that describes the task:
### Input:
Convenient static constructor for an automatic Gamma centered Kpoint
grid.
Args:
kpts: Subdivisions N_1, N_2 and N_3 along reciprocal lattice
vectors. Defaults to (1,1,1)
shift: Shift to be appl... |
def isExploitable(self):
"""
Guess how likely is it that the bug causing the crash can be leveraged
into an exploitable vulnerability.
@note: Don't take this as an equivalent of a real exploitability
analysis, that can only be done by a human being! This is only
... | Guess how likely is it that the bug causing the crash can be leveraged
into an exploitable vulnerability.
@note: Don't take this as an equivalent of a real exploitability
analysis, that can only be done by a human being! This is only
a guideline, useful for example to sort crash... | Below is the the instruction that describes the task:
### Input:
Guess how likely is it that the bug causing the crash can be leveraged
into an exploitable vulnerability.
@note: Don't take this as an equivalent of a real exploitability
analysis, that can only be done by a human being! T... |
def toggle_legend(self, evt=None, show=None):
"toggle legend display"
if show is None:
show = not self.conf.show_legend
self.conf.show_legend = show
self.conf.draw_legend() | toggle legend display | Below is the the instruction that describes the task:
### Input:
toggle legend display
### Response:
def toggle_legend(self, evt=None, show=None):
"toggle legend display"
if show is None:
show = not self.conf.show_legend
self.conf.show_legend = show
self.conf.draw_le... |
def zpad(v, Nv):
"""Zero-pad initial axes of array to specified size. Padding is
applied to the right, top, etc. of the array indices.
Parameters
----------
v : array_like
Array to be padded
Nv : tuple
Sizes to which each of initial indices should be padded
Returns
-------
... | Zero-pad initial axes of array to specified size. Padding is
applied to the right, top, etc. of the array indices.
Parameters
----------
v : array_like
Array to be padded
Nv : tuple
Sizes to which each of initial indices should be padded
Returns
-------
vp : ndarray
P... | Below is the the instruction that describes the task:
### Input:
Zero-pad initial axes of array to specified size. Padding is
applied to the right, top, etc. of the array indices.
Parameters
----------
v : array_like
Array to be padded
Nv : tuple
Sizes to which each of initial indic... |
def apply_and_get_result(self, string):
"""
Perform the substitution represented by this object on string and return
the result.
"""
if self.is_multiline:
compiled_pattern = re.compile(self.pattern, re.MULTILINE)
else:
compiled_pattern = re.compile... | Perform the substitution represented by this object on string and return
the result. | Below is the the instruction that describes the task:
### Input:
Perform the substitution represented by this object on string and return
the result.
### Response:
def apply_and_get_result(self, string):
"""
Perform the substitution represented by this object on string and return
th... |
def download(self,
files=None,
destination=None,
overwrite=False,
callback=None):
"""Download file or files.
:param files: file or files to download
:param destination: destination path (defaults to users home directory)
... | Download file or files.
:param files: file or files to download
:param destination: destination path (defaults to users home directory)
:param overwrite: replace existing files?
:param callback: callback function that will receive total file size
and written bytes as arguments
... | Below is the the instruction that describes the task:
### Input:
Download file or files.
:param files: file or files to download
:param destination: destination path (defaults to users home directory)
:param overwrite: replace existing files?
:param callback: callback function that ... |
def list_exchanges_for_vhost(self, vhost):
"""
A list of all exchanges in a given virtual host.
:param vhost: The vhost name
:type vhost: str
"""
return self._api_get('/api/exchanges/{0}'.format(
urllib.parse.quote_plus(vhost)
)) | A list of all exchanges in a given virtual host.
:param vhost: The vhost name
:type vhost: str | Below is the the instruction that describes the task:
### Input:
A list of all exchanges in a given virtual host.
:param vhost: The vhost name
:type vhost: str
### Response:
def list_exchanges_for_vhost(self, vhost):
"""
A list of all exchanges in a given virtual host.
:pa... |
def pageSizePicked( self, pageSize ):
"""
Updates when the user picks a page size.
:param pageSize | <str>
"""
try:
pageSize = int(self._pageSizeCombo.currentText())
except ValueError:
pageSize = 0
self.set... | Updates when the user picks a page size.
:param pageSize | <str> | Below is the the instruction that describes the task:
### Input:
Updates when the user picks a page size.
:param pageSize | <str>
### Response:
def pageSizePicked( self, pageSize ):
"""
Updates when the user picks a page size.
:param pageSize | <str... |
def _http_date(_date_str: str) -> Optional[datetime.datetime]:
"""Process a date string, return a datetime object
"""
if _date_str is not None:
timetuple = parsedate(_date_str)
if timetuple is not None:
return datetime.datetime(*timetuple[:6],
... | Process a date string, return a datetime object | Below is the the instruction that describes the task:
### Input:
Process a date string, return a datetime object
### Response:
def _http_date(_date_str: str) -> Optional[datetime.datetime]:
"""Process a date string, return a datetime object
"""
if _date_str is not None:
timetupl... |
def zplane(self,auto_scale=True,size=2,detect_mult=True,tol=0.001):
"""
Plot the poles and zeros of the FIR filter in the z-plane
"""
iir_d.sos_zplane(self.sos,auto_scale,size,tol) | Plot the poles and zeros of the FIR filter in the z-plane | Below is the the instruction that describes the task:
### Input:
Plot the poles and zeros of the FIR filter in the z-plane
### Response:
def zplane(self,auto_scale=True,size=2,detect_mult=True,tol=0.001):
"""
Plot the poles and zeros of the FIR filter in the z-plane
"""
iir_d.sos_zp... |
def parse(doc, treebuilder="etree", encoding=None,
namespaceHTMLElements=True):
"""Parse a string or file-like object into a tree"""
tb = treebuilders.getTreeBuilder(treebuilder)
p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements)
return p.parse(doc, encoding=encoding) | Parse a string or file-like object into a tree | Below is the the instruction that describes the task:
### Input:
Parse a string or file-like object into a tree
### Response:
def parse(doc, treebuilder="etree", encoding=None,
namespaceHTMLElements=True):
"""Parse a string or file-like object into a tree"""
tb = treebuilders.getTreeBuilder(treeb... |
def get_response(self, method, endpoint, headers=None, json=None, params=None, data=None):
# pylint: disable=too-many-arguments
"""
Returns the response from the requested endpoint with the requested method
:param method: str. one of the methods accepted by Requests ('POST', 'GET', ...)
... | Returns the response from the requested endpoint with the requested method
:param method: str. one of the methods accepted by Requests ('POST', 'GET', ...)
:param endpoint: str. the relative endpoint to access
:param params: (optional) Dictionary or bytes to be sent in the query string
f... | Below is the the instruction that describes the task:
### Input:
Returns the response from the requested endpoint with the requested method
:param method: str. one of the methods accepted by Requests ('POST', 'GET', ...)
:param endpoint: str. the relative endpoint to access
:param params: (o... |
def noreplynum_get(self, service_staff_id, start_date, end_date, session):
'''taobao.wangwang.eservice.noreplynum.get 客服未回复人数
根据操作者ID,返回被查者ID指定日期内每个帐号每日的"未回复情况" 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"未回复情况"(未回复人数、未回复的ID)。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"未回复情况"。
- 3、如... | taobao.wangwang.eservice.noreplynum.get 客服未回复人数
根据操作者ID,返回被查者ID指定日期内每个帐号每日的"未回复情况" 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"未回复情况"(未回复人数、未回复的ID)。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"未回复情况"。
- 3、如果操作者是主账户,他可以查询所有子帐号的"未回复情况"。
- 4、被查者ID可以是多个,用 "," 隔开,id数不能超过30。
- 5、... | Below is the the instruction that describes the task:
### Input:
taobao.wangwang.eservice.noreplynum.get 客服未回复人数
根据操作者ID,返回被查者ID指定日期内每个帐号每日的"未回复情况" 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"未回复情况"(未回复人数、未回复的ID)。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"未回复情况"。
- 3、如果操作者是主账户,他可以查询所有子... |
def parallel_worker(conn, steps):
"""
All messages follow the form: <message>, <data>
Valid messages
--------------
run, { 'step': <step_name>, 'input': <input_data> }
finalise, { 'step': <step_name> }
next, { 'step': <step_name> }
stop, None
"""
while True:
message, dat... | All messages follow the form: <message>, <data>
Valid messages
--------------
run, { 'step': <step_name>, 'input': <input_data> }
finalise, { 'step': <step_name> }
next, { 'step': <step_name> }
stop, None | Below is the the instruction that describes the task:
### Input:
All messages follow the form: <message>, <data>
Valid messages
--------------
run, { 'step': <step_name>, 'input': <input_data> }
finalise, { 'step': <step_name> }
next, { 'step': <step_name> }
stop, None
### Response:
def pa... |
def info(self):
"""Return info about the dimension instance.
Args::
no argument
Returns::
4-element tuple holding:
- dimension name; 'fakeDimx' is returned if the dimension
has not been named yet, where 'x' is the dimension
index number
... | Return info about the dimension instance.
Args::
no argument
Returns::
4-element tuple holding:
- dimension name; 'fakeDimx' is returned if the dimension
has not been named yet, where 'x' is the dimension
index number
- dimension lengt... | Below is the the instruction that describes the task:
### Input:
Return info about the dimension instance.
Args::
no argument
Returns::
4-element tuple holding:
- dimension name; 'fakeDimx' is returned if the dimension
has not been named yet, where 'x' ... |
def _slice_value(index, context=None):
"""Get the value of the given slice index."""
if isinstance(index, Const):
if isinstance(index.value, (int, type(None))):
return index.value
elif index is None:
return None
else:
# Try to infer what the index actually is.
... | Get the value of the given slice index. | Below is the the instruction that describes the task:
### Input:
Get the value of the given slice index.
### Response:
def _slice_value(index, context=None):
"""Get the value of the given slice index."""
if isinstance(index, Const):
if isinstance(index.value, (int, type(None))):
return... |
def load_bookmarks_without_file(filename):
"""Load all bookmarks but those from a specific file."""
bookmarks = _load_all_bookmarks()
return {k: v for k, v in bookmarks.items() if v[0] != filename} | Load all bookmarks but those from a specific file. | Below is the the instruction that describes the task:
### Input:
Load all bookmarks but those from a specific file.
### Response:
def load_bookmarks_without_file(filename):
"""Load all bookmarks but those from a specific file."""
bookmarks = _load_all_bookmarks()
return {k: v for k, v in bookmarks.item... |
def cpuinfo():
''' Return the information in /proc/cpuinfo
as a dictionary in the following format:
cpu_info['proc0']={...}
cpu_info['proc1']={...}
'''
cpuinfo=OrderedDict()
procinfo=OrderedDict()
nprocs = 0
with open('/proc/cpuinfo') as f:
for line in f:
if no... | Return the information in /proc/cpuinfo
as a dictionary in the following format:
cpu_info['proc0']={...}
cpu_info['proc1']={...} | Below is the the instruction that describes the task:
### Input:
Return the information in /proc/cpuinfo
as a dictionary in the following format:
cpu_info['proc0']={...}
cpu_info['proc1']={...}
### Response:
def cpuinfo():
''' Return the information in /proc/cpuinfo
as a dictionary in the follo... |
def p_numeric_literal(self, p):
"""numeric_literal : NUMBER"""
p[0] = self.asttypes.Number(p[1])
p[0].setpos(p) | numeric_literal : NUMBER | Below is the the instruction that describes the task:
### Input:
numeric_literal : NUMBER
### Response:
def p_numeric_literal(self, p):
"""numeric_literal : NUMBER"""
p[0] = self.asttypes.Number(p[1])
p[0].setpos(p) |
def _get_download_output_manager_cls(self, transfer_future, osutil):
"""Retrieves a class for managing output for a download
:type transfer_future: s3transfer.futures.TransferFuture
:param transfer_future: The transfer future for the request
:type osutil: s3transfer.utils.OSUtils
... | Retrieves a class for managing output for a download
:type transfer_future: s3transfer.futures.TransferFuture
:param transfer_future: The transfer future for the request
:type osutil: s3transfer.utils.OSUtils
:param osutil: The os utility associated to the transfer
:rtype: cla... | Below is the the instruction that describes the task:
### Input:
Retrieves a class for managing output for a download
:type transfer_future: s3transfer.futures.TransferFuture
:param transfer_future: The transfer future for the request
:type osutil: s3transfer.utils.OSUtils
:param o... |
def atomic_copy(src, dst):
"""Copy the file src to dst, overwriting dst atomically."""
with temporary_file(root_dir=os.path.dirname(dst)) as tmp_dst:
shutil.copyfile(src, tmp_dst.name)
os.chmod(tmp_dst.name, os.stat(src).st_mode)
os.rename(tmp_dst.name, dst) | Copy the file src to dst, overwriting dst atomically. | Below is the the instruction that describes the task:
### Input:
Copy the file src to dst, overwriting dst atomically.
### Response:
def atomic_copy(src, dst):
"""Copy the file src to dst, overwriting dst atomically."""
with temporary_file(root_dir=os.path.dirname(dst)) as tmp_dst:
shutil.copyfile(src, tmp... |
def _getContextFactory(path, workbench):
"""Get a context factory.
If the client already has a credentials at path, use them.
Otherwise, generate them at path. Notifications are reported to
the given workbench.
"""
try:
return succeed(getContextFactory(path))
except IOError:
... | Get a context factory.
If the client already has a credentials at path, use them.
Otherwise, generate them at path. Notifications are reported to
the given workbench. | Below is the the instruction that describes the task:
### Input:
Get a context factory.
If the client already has a credentials at path, use them.
Otherwise, generate them at path. Notifications are reported to
the given workbench.
### Response:
def _getContextFactory(path, workbench):
"""Get a co... |
def page_location_template(self):
"""
Returns the published URL template for a page type.
"""
cycle = self.election_day.cycle.name
model_class = self.model_type.model_class()
if model_class == ElectionDay:
return "/{}/".format(cycle)
if model_class == ... | Returns the published URL template for a page type. | Below is the the instruction that describes the task:
### Input:
Returns the published URL template for a page type.
### Response:
def page_location_template(self):
"""
Returns the published URL template for a page type.
"""
cycle = self.election_day.cycle.name
model_class =... |
def apply_T2(word):
'''There is a syllable boundary within a VV sequence of two nonidentical
vowels that are not a genuine diphthong, e.g., [ta.e], [ko.et.taa].'''
WORD = word
offset = 0
for vv in vv_sequences(WORD):
seq = vv.group(2)
if not is_diphthong(seq) and not is_long(seq):
... | There is a syllable boundary within a VV sequence of two nonidentical
vowels that are not a genuine diphthong, e.g., [ta.e], [ko.et.taa]. | Below is the the instruction that describes the task:
### Input:
There is a syllable boundary within a VV sequence of two nonidentical
vowels that are not a genuine diphthong, e.g., [ta.e], [ko.et.taa].
### Response:
def apply_T2(word):
'''There is a syllable boundary within a VV sequence of two nonidentic... |
def random_vector(size, mean=0, std=1, rng=None):
'''Create a vector of randomly-initialized values.
Parameters
----------
size : int
Length of vecctor to create.
mean : float, optional
Mean value for initial vector values. Defaults to 0.
std : float, optional
Standard d... | Create a vector of randomly-initialized values.
Parameters
----------
size : int
Length of vecctor to create.
mean : float, optional
Mean value for initial vector values. Defaults to 0.
std : float, optional
Standard deviation for initial vector values. Defaults to 1.
rn... | Below is the the instruction that describes the task:
### Input:
Create a vector of randomly-initialized values.
Parameters
----------
size : int
Length of vecctor to create.
mean : float, optional
Mean value for initial vector values. Defaults to 0.
std : float, optional
... |
def on_menu_criteria_file(self, event):
"""
read pmag_criteria.txt file
and open changecriteria dialog
"""
if self.data_model == 3:
default_file = "criteria.txt"
else:
default_file = "pmag_criteria.txt"
read_sucsess = False
dlg = wx... | read pmag_criteria.txt file
and open changecriteria dialog | Below is the the instruction that describes the task:
### Input:
read pmag_criteria.txt file
and open changecriteria dialog
### Response:
def on_menu_criteria_file(self, event):
"""
read pmag_criteria.txt file
and open changecriteria dialog
"""
if self.data_model == ... |
def _get_topologies_with_watch(self, callback, isWatching):
"""
Helper function to get topologies with
a callback. The future watch is placed
only if isWatching is True.
"""
path = self.get_topologies_path()
if isWatching:
LOG.info("Adding children watch for path: " + path)
# pyli... | Helper function to get topologies with
a callback. The future watch is placed
only if isWatching is True. | Below is the the instruction that describes the task:
### Input:
Helper function to get topologies with
a callback. The future watch is placed
only if isWatching is True.
### Response:
def _get_topologies_with_watch(self, callback, isWatching):
"""
Helper function to get topologies with
a callb... |
def p_label_list_list(p):
""" label_list : label_list COMMA ID
| label_list COMMA NUMBER
"""
p[0] = p[1]
entry = check_and_make_label(p[3], p.lineno(3))
p[1].append(entry) | label_list : label_list COMMA ID
| label_list COMMA NUMBER | Below is the the instruction that describes the task:
### Input:
label_list : label_list COMMA ID
| label_list COMMA NUMBER
### Response:
def p_label_list_list(p):
""" label_list : label_list COMMA ID
| label_list COMMA NUMBER
"""
p[0] = p[1]
entry = check_and_... |
def save(self, filename):
'''save settings to a file. Return True/False on success/failure'''
try:
f = open(filename, mode='w')
except Exception:
return False
for k in self.list():
f.write("%s=%s\n" % (k, self.get(k)))
f.close()
return ... | save settings to a file. Return True/False on success/failure | Below is the the instruction that describes the task:
### Input:
save settings to a file. Return True/False on success/failure
### Response:
def save(self, filename):
'''save settings to a file. Return True/False on success/failure'''
try:
f = open(filename, mode='w')
except Exc... |
def _construct_request(self):
"""
Utility for constructing the request header and connection
"""
if self.parsed_endpoint.scheme == 'https':
conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc)
else:
conn = httplib.HTTPConnection(self.parsed_endpoint... | Utility for constructing the request header and connection | Below is the the instruction that describes the task:
### Input:
Utility for constructing the request header and connection
### Response:
def _construct_request(self):
"""
Utility for constructing the request header and connection
"""
if self.parsed_endpoint.scheme == 'https':
... |
def _get_conn(self, host, port):
"""Get or create a connection to a broker using host and port"""
host_key = (host, port)
if host_key not in self.conns:
self.conns[host_key] = KafkaConnection(
host,
port,
timeout=self.timeout
... | Get or create a connection to a broker using host and port | Below is the the instruction that describes the task:
### Input:
Get or create a connection to a broker using host and port
### Response:
def _get_conn(self, host, port):
"""Get or create a connection to a broker using host and port"""
host_key = (host, port)
if host_key not in self.conns:
... |
def handle_alarm(sender, **kwargs):
"""
Handles alarm events from the AlarmDecoder.
"""
zone = kwargs.pop('zone', None)
text = "Alarm: Zone {0}".format(zone)
# Build the email message
msg = MIMEText(text)
msg['Subject'] = SUBJECT
msg['From'] = FROM_ADDRESS
msg['To'] = TO_ADDRESS... | Handles alarm events from the AlarmDecoder. | Below is the the instruction that describes the task:
### Input:
Handles alarm events from the AlarmDecoder.
### Response:
def handle_alarm(sender, **kwargs):
"""
Handles alarm events from the AlarmDecoder.
"""
zone = kwargs.pop('zone', None)
text = "Alarm: Zone {0}".format(zone)
# Build t... |
def combinatorics(self):
"""
Returns mutually exclusive/inclusive clampings
Returns
-------
(dict,dict)
A tuple of 2 dictionaries.
For each literal key, the first dict has as value the set of mutually exclusive clampings while
the second dict ... | Returns mutually exclusive/inclusive clampings
Returns
-------
(dict,dict)
A tuple of 2 dictionaries.
For each literal key, the first dict has as value the set of mutually exclusive clampings while
the second dict has as value the set of mutually inclusive cl... | Below is the the instruction that describes the task:
### Input:
Returns mutually exclusive/inclusive clampings
Returns
-------
(dict,dict)
A tuple of 2 dictionaries.
For each literal key, the first dict has as value the set of mutually exclusive clampings while
... |
def internal_get_completions(dbg, seq, thread_id, frame_id, act_tok, line=-1, column=-1):
'''
Note that if the column is >= 0, the act_tok is considered text and the actual
activation token/qualifier is computed in this command.
'''
try:
remove_path = None
try:
qualifier ... | Note that if the column is >= 0, the act_tok is considered text and the actual
activation token/qualifier is computed in this command. | Below is the the instruction that describes the task:
### Input:
Note that if the column is >= 0, the act_tok is considered text and the actual
activation token/qualifier is computed in this command.
### Response:
def internal_get_completions(dbg, seq, thread_id, frame_id, act_tok, line=-1, column=-1):
'''... |
def mesh_axis_to_cumprod(self, tensor_shape):
"""For each mesh axis, give the product of previous tensor axes.
Args:
tensor_shape: Shape.
Returns:
list with length self.ndims where each element is an integer or None.
"""
tensor_layout = self.tensor_layout(tensor_shape)
ma2ta = tens... | For each mesh axis, give the product of previous tensor axes.
Args:
tensor_shape: Shape.
Returns:
list with length self.ndims where each element is an integer or None. | Below is the the instruction that describes the task:
### Input:
For each mesh axis, give the product of previous tensor axes.
Args:
tensor_shape: Shape.
Returns:
list with length self.ndims where each element is an integer or None.
### Response:
def mesh_axis_to_cumprod(self, tensor_shape):
... |
def indices(self, index=None, params=None):
"""
The indices command provides a cross-section of each index.
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-indices.html>`_
:arg index: A comma-separated list of index names to limit the returned
informati... | The indices command provides a cross-section of each index.
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-indices.html>`_
:arg index: A comma-separated list of index names to limit the returned
information
:arg bytes: The unit in which to display byte values,... | Below is the the instruction that describes the task:
### Input:
The indices command provides a cross-section of each index.
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-indices.html>`_
:arg index: A comma-separated list of index names to limit the returned
info... |
def access_level_up_to(self, access_level):
""" returns all items that have an access level equal or lower than the one specified """
# if access_level is number
if isinstance(access_level, int):
value = access_level
# else if is string get the numeric value
else:
... | returns all items that have an access level equal or lower than the one specified | Below is the the instruction that describes the task:
### Input:
returns all items that have an access level equal or lower than the one specified
### Response:
def access_level_up_to(self, access_level):
""" returns all items that have an access level equal or lower than the one specified """
# if... |
def __add_class_views(self):
"""
Include any custom class views on the Sanic JWT Blueprint
"""
config = self.config
if "class_views" in self.kwargs:
class_views = self.kwargs.pop("class_views")
for route, view in class_views:
if issubclass... | Include any custom class views on the Sanic JWT Blueprint | Below is the the instruction that describes the task:
### Input:
Include any custom class views on the Sanic JWT Blueprint
### Response:
def __add_class_views(self):
"""
Include any custom class views on the Sanic JWT Blueprint
"""
config = self.config
if "class_views" in se... |
def pre_attention(self, segment_number, query_antecedent,
memory_antecedent, bias):
"""Called prior to self-attention, to incorporate memory items.
Args:
segment_number: an integer Tensor with shape [batch]
query_antecedent: a Tensor with shape [batch, length_q, channels]
... | Called prior to self-attention, to incorporate memory items.
Args:
segment_number: an integer Tensor with shape [batch]
query_antecedent: a Tensor with shape [batch, length_q, channels]
memory_antecedent: must be None. Attention normally allows this to be a
Tensor with shape [batch, lengt... | Below is the the instruction that describes the task:
### Input:
Called prior to self-attention, to incorporate memory items.
Args:
segment_number: an integer Tensor with shape [batch]
query_antecedent: a Tensor with shape [batch, length_q, channels]
memory_antecedent: must be None. Attention... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.