code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def cache(opts, serial):
'''
Returns the returner modules
'''
return LazyLoader(
_module_dirs(opts, 'cache', 'cache'),
opts,
tag='cache',
pack={'__opts__': opts, '__context__': {'serial': serial}},
) | Returns the returner modules | Below is the the instruction that describes the task:
### Input:
Returns the returner modules
### Response:
def cache(opts, serial):
'''
Returns the returner modules
'''
return LazyLoader(
_module_dirs(opts, 'cache', 'cache'),
opts,
tag='cache',
pack={'__opts__': opt... |
def create_button(self, style=Gtk.ReliefStyle.NORMAL):
"""
This is generalized method for creating Gtk.Button
"""
btn = Gtk.Button()
btn.set_relief(style)
return btn | This is generalized method for creating Gtk.Button | Below is the the instruction that describes the task:
### Input:
This is generalized method for creating Gtk.Button
### Response:
def create_button(self, style=Gtk.ReliefStyle.NORMAL):
"""
This is generalized method for creating Gtk.Button
"""
btn = Gtk.Button()
btn.set_reli... |
def dist_location(dist):
"""
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
"""
egg_link = egg_link_path(... | Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is. | Below is the the instruction that describes the task:
### Input:
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
### Re... |
def SetMaxCurrent(self, i):
"""Set the max output current.
"""
if i < 0 or i > 8:
raise MonsoonError(("Target max current %sA, is out of acceptable "
"range [0, 8].") % i)
val = 1023 - int((i / 8) * 1023)
self._SendStruct("BBB", 0x01, 0... | Set the max output current. | Below is the the instruction that describes the task:
### Input:
Set the max output current.
### Response:
def SetMaxCurrent(self, i):
"""Set the max output current.
"""
if i < 0 or i > 8:
raise MonsoonError(("Target max current %sA, is out of acceptable "
... |
def search(self, CorpNum, DType, SDate, EDate, State, TradeType, TradeUsage, TaxationType, Page, PerPage, Order,
UserID=None, QString=None, TradeOpt=None):
""" λͺ©λ‘ μ‘°ν
args
CorpNum : νλΉνμ μ¬μ
μλ²νΈ
DType : μΌμμ ν, R-λ±λ‘μΌμ, T-κ±°λμΌμ, I-λ°νμΌμ μ€ ν 1
... | λͺ©λ‘ μ‘°ν
args
CorpNum : νλΉνμ μ¬μ
μλ²νΈ
DType : μΌμμ ν, R-λ±λ‘μΌμ, T-κ±°λμΌμ, I-λ°νμΌμ μ€ ν 1
SDate : μμμΌμ, νμνμ(yyyyMMdd)
EDate : μ’
λ£μΌμ, νμνμ(yyyyMMdd)
State : μνμ½λ λ°°μ΄, 2,3λ²μ§Έ μ리μ μμΌλμΉ΄λ(*) μ¬μ©κ°λ₯
TradeType : λ¬Έμνν λ°°μ΄, N-μΌλ°νκΈμμμ¦,... | Below is the the instruction that describes the task:
### Input:
λͺ©λ‘ μ‘°ν
args
CorpNum : νλΉνμ μ¬μ
μλ²νΈ
DType : μΌμμ ν, R-λ±λ‘μΌμ, T-κ±°λμΌμ, I-λ°νμΌμ μ€ ν 1
SDate : μμμΌμ, νμνμ(yyyyMMdd)
EDate : μ’
λ£μΌμ, νμνμ(yyyyMMdd)
State : μνμ½λ λ°°μ΄, 2,3... |
def queryName(self, queryName):
"""Specifies the name of the :class:`StreamingQuery` that can be started with
:func:`start`. This name must be unique among all the currently active queries
in the associated SparkSession.
.. note:: Evolving.
:param queryName: unique name for the... | Specifies the name of the :class:`StreamingQuery` that can be started with
:func:`start`. This name must be unique among all the currently active queries
in the associated SparkSession.
.. note:: Evolving.
:param queryName: unique name for the query
>>> writer = sdf.writeStrea... | Below is the the instruction that describes the task:
### Input:
Specifies the name of the :class:`StreamingQuery` that can be started with
:func:`start`. This name must be unique among all the currently active queries
in the associated SparkSession.
.. note:: Evolving.
:param quer... |
def set_title(self, title=None):
"""
Sets the title on the current axes.
Parameters
----------
title: string, default: None
Add title to figure or if None leave untitled.
"""
title = self.title or title
if title is not None:
self.a... | Sets the title on the current axes.
Parameters
----------
title: string, default: None
Add title to figure or if None leave untitled. | Below is the the instruction that describes the task:
### Input:
Sets the title on the current axes.
Parameters
----------
title: string, default: None
Add title to figure or if None leave untitled.
### Response:
def set_title(self, title=None):
"""
Sets the tit... |
def _getSyntaxByFirstLine(self, firstLine):
"""Get syntax by first line of the file
"""
for pattern, xmlFileName in self._firstLineToXmlFileName.items():
if fnmatch.fnmatch(firstLine, pattern):
return self._getSyntaxByXmlFileName(xmlFileName)
else:
... | Get syntax by first line of the file | Below is the the instruction that describes the task:
### Input:
Get syntax by first line of the file
### Response:
def _getSyntaxByFirstLine(self, firstLine):
"""Get syntax by first line of the file
"""
for pattern, xmlFileName in self._firstLineToXmlFileName.items():
if fnmatc... |
def get_network_remove_kwargs(self, action, network_name, kwargs=None):
"""
Generates keyword arguments for the Docker client to remove a network.
:param action: Action configuration.
:type action: ActionConfig
:param network_name: Network name or id.
:type network_name:... | Generates keyword arguments for the Docker client to remove a network.
:param action: Action configuration.
:type action: ActionConfig
:param network_name: Network name or id.
:type network_name: unicode | str
:param kwargs: Additional keyword arguments to complement or override... | Below is the the instruction that describes the task:
### Input:
Generates keyword arguments for the Docker client to remove a network.
:param action: Action configuration.
:type action: ActionConfig
:param network_name: Network name or id.
:type network_name: unicode | str
... |
def encode_timeseries_put(self, tsobj):
"""
Fills an TsPutReq message with the appropriate data and
metadata from a TsObject.
:param tsobj: a TsObject
:type tsobj: TsObject
:param req: the protobuf message to fill
:type req: riak.pb.riak_ts_pb2.TsPutReq
"... | Fills an TsPutReq message with the appropriate data and
metadata from a TsObject.
:param tsobj: a TsObject
:type tsobj: TsObject
:param req: the protobuf message to fill
:type req: riak.pb.riak_ts_pb2.TsPutReq | Below is the the instruction that describes the task:
### Input:
Fills an TsPutReq message with the appropriate data and
metadata from a TsObject.
:param tsobj: a TsObject
:type tsobj: TsObject
:param req: the protobuf message to fill
:type req: riak.pb.riak_ts_pb2.TsPutReq
... |
def score_samples(self, X):
"""Return the per-sample likelihood of the data under the model.
Compute the log probability of X under the model and
return the posterior distribution (responsibilities) of each
mixture component for each element of X.
Parameters
----------
... | Return the per-sample likelihood of the data under the model.
Compute the log probability of X under the model and
return the posterior distribution (responsibilities) of each
mixture component for each element of X.
Parameters
----------
X: array_like, shape (n_samples... | Below is the the instruction that describes the task:
### Input:
Return the per-sample likelihood of the data under the model.
Compute the log probability of X under the model and
return the posterior distribution (responsibilities) of each
mixture component for each element of X.
... |
def _tls_auth_encrypt(self, s):
"""
Return the TLSCiphertext.fragment for AEAD ciphers, i.e. the whole
GenericAEADCipher. Also, the additional data is computed right here.
"""
write_seq_num = struct.pack("!Q", self.tls_session.wcs.seq_num)
self.tls_session.wcs.seq_num += ... | Return the TLSCiphertext.fragment for AEAD ciphers, i.e. the whole
GenericAEADCipher. Also, the additional data is computed right here. | Below is the the instruction that describes the task:
### Input:
Return the TLSCiphertext.fragment for AEAD ciphers, i.e. the whole
GenericAEADCipher. Also, the additional data is computed right here.
### Response:
def _tls_auth_encrypt(self, s):
"""
Return the TLSCiphertext.fragment for AE... |
def encode_unicode(f):
"""Cerberus error messages expect regular binary strings.
If unicode is used in a ValidationError message can't be printed.
This decorator ensures that if legacy Python is used unicode
strings are encoded before passing to a function.
"""
@wraps(f)
def wrapped(obj, er... | Cerberus error messages expect regular binary strings.
If unicode is used in a ValidationError message can't be printed.
This decorator ensures that if legacy Python is used unicode
strings are encoded before passing to a function. | Below is the the instruction that describes the task:
### Input:
Cerberus error messages expect regular binary strings.
If unicode is used in a ValidationError message can't be printed.
This decorator ensures that if legacy Python is used unicode
strings are encoded before passing to a function.
### Re... |
async def _replace(self, key: Text, data: Dict[Text, Any]) -> None:
"""
Replace the register with a new value.
"""
with await self.pool as r:
await r.set(self.register_key(key), ujson.dumps(data)) | Replace the register with a new value. | Below is the the instruction that describes the task:
### Input:
Replace the register with a new value.
### Response:
async def _replace(self, key: Text, data: Dict[Text, Any]) -> None:
"""
Replace the register with a new value.
"""
with await self.pool as r:
await r.se... |
def main_generate(table_names, stream):
"""This will print out valid prom python code for given tables that already exist
in a database.
This is really handy when you want to bootstrap an existing database to work
with prom and don't want to manually create Orm objects for the tables you want
to us... | This will print out valid prom python code for given tables that already exist
in a database.
This is really handy when you want to bootstrap an existing database to work
with prom and don't want to manually create Orm objects for the tables you want
to use, let `generate` do it for you | Below is the the instruction that describes the task:
### Input:
This will print out valid prom python code for given tables that already exist
in a database.
This is really handy when you want to bootstrap an existing database to work
with prom and don't want to manually create Orm objects for the tab... |
def search(table: LdapObjectClass, query: Optional[Q] = None,
database: Optional[Database] = None, base_dn: Optional[str] = None) -> Iterator[LdapObject]:
""" Search for a object of given type in the database. """
fields = table.get_fields()
db_fields = {
name: field
for name, fie... | Search for a object of given type in the database. | Below is the the instruction that describes the task:
### Input:
Search for a object of given type in the database.
### Response:
def search(table: LdapObjectClass, query: Optional[Q] = None,
database: Optional[Database] = None, base_dn: Optional[str] = None) -> Iterator[LdapObject]:
""" Search for ... |
def add_meta_to_nii(nii_file, dicom_file, dcm_tags=''):
""" Add slice duration and acquisition times to the headers of the nifit1 files in `nii_file`.
It will add the repetition time of the DICOM file (field: {0x0018, 0x0080, DS, Repetition Time})
to the NifTI file as well as any other tag in `dcm_tags`.
... | Add slice duration and acquisition times to the headers of the nifit1 files in `nii_file`.
It will add the repetition time of the DICOM file (field: {0x0018, 0x0080, DS, Repetition Time})
to the NifTI file as well as any other tag in `dcm_tags`.
All selected DICOM tags values are set in the `descrip` nifti ... | Below is the the instruction that describes the task:
### Input:
Add slice duration and acquisition times to the headers of the nifit1 files in `nii_file`.
It will add the repetition time of the DICOM file (field: {0x0018, 0x0080, DS, Repetition Time})
to the NifTI file as well as any other tag in `dcm_tags... |
def push_note(device=None, title=None, body=None):
'''
Pushing a text note.
:param device: Pushbullet target device
:param title: Note title
:param body: Note body
:return: Boolean if message was sent successfully.
CLI Example:
.. code-block:: bash
salt "... | Pushing a text note.
:param device: Pushbullet target device
:param title: Note title
:param body: Note body
:return: Boolean if message was sent successfully.
CLI Example:
.. code-block:: bash
salt "*" pushbullet.push_note device="Chrome" title="Example title" b... | Below is the the instruction that describes the task:
### Input:
Pushing a text note.
:param device: Pushbullet target device
:param title: Note title
:param body: Note body
:return: Boolean if message was sent successfully.
CLI Example:
.. code-block:: bash
... |
def save(self) -> None:
"""
Saves all changed values to the database.
"""
for name, field in self.fields.items():
value = self.cleaned_data[name]
if isinstance(value, UploadedFile):
# Delete old file
fname = self._s.get(name, as_typ... | Saves all changed values to the database. | Below is the the instruction that describes the task:
### Input:
Saves all changed values to the database.
### Response:
def save(self) -> None:
"""
Saves all changed values to the database.
"""
for name, field in self.fields.items():
value = self.cleaned_data[name]
... |
def set_terminal_width(self, command="", delay_factor=1):
"""CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the output to get distorted when accessed programmatically.
Set terminal width to 511 which works on a broad set of devices.
:... | CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the output to get distorted when accessed programmatically.
Set terminal width to 511 which works on a broad set of devices.
:param command: Command string to send to the device
:type com... | Below is the the instruction that describes the task:
### Input:
CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the output to get distorted when accessed programmatically.
Set terminal width to 511 which works on a broad set of devices.
:... |
def condition_input(args, kwargs):
'''
Return a single arg structure for the publisher to safely use
'''
ret = []
for arg in args:
if (six.PY3 and isinstance(arg, six.integer_types) and salt.utils.jid.is_jid(six.text_type(arg))) or \
(six.PY2 and isinstance(arg, long)): # pylint: di... | Return a single arg structure for the publisher to safely use | Below is the the instruction that describes the task:
### Input:
Return a single arg structure for the publisher to safely use
### Response:
def condition_input(args, kwargs):
'''
Return a single arg structure for the publisher to safely use
'''
ret = []
for arg in args:
if (six.PY3 and... |
def get_instance(self, payload):
"""
Build an instance of WorkflowCumulativeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance
:rtype: t... | Build an instance of WorkflowCumulativeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_... | Below is the the instruction that describes the task:
### Input:
Build an instance of WorkflowCumulativeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance
... |
def confd_state_internal_callpoints_validationpoint_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
internal = ET.SubElement(confd_state, "internal")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def confd_state_internal_callpoints_validationpoint_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmln... |
def _paint_margin(self, event):
""" Paints the right margin after editor paint event. """
font = QtGui.QFont(self.editor.font_name, self.editor.font_size +
self.editor.zoom_level)
metrics = QtGui.QFontMetricsF(font)
pos = self._margin_pos
offset = self.... | Paints the right margin after editor paint event. | Below is the the instruction that describes the task:
### Input:
Paints the right margin after editor paint event.
### Response:
def _paint_margin(self, event):
""" Paints the right margin after editor paint event. """
font = QtGui.QFont(self.editor.font_name, self.editor.font_size +
... |
def save(self):
"""
Saves or updates the current tailored audience permission.
"""
if self.id:
method = 'put'
resource = self.RESOURCE.format(
account_id=self.account.id,
tailored_audience_id=self.tailored_audience_id,
... | Saves or updates the current tailored audience permission. | Below is the the instruction that describes the task:
### Input:
Saves or updates the current tailored audience permission.
### Response:
def save(self):
"""
Saves or updates the current tailored audience permission.
"""
if self.id:
method = 'put'
resource = ... |
def id(self):
"""
Computes the signature of the record, a SHA-512 of significant values
:return: SHa-512 Hex string
"""
h = hashlib.new('sha512')
for value in (self.machine.name, self.machine.os, self.user, self.application.name,
self.application.pa... | Computes the signature of the record, a SHA-512 of significant values
:return: SHa-512 Hex string | Below is the the instruction that describes the task:
### Input:
Computes the signature of the record, a SHA-512 of significant values
:return: SHa-512 Hex string
### Response:
def id(self):
"""
Computes the signature of the record, a SHA-512 of significant values
:return: SHa-512... |
def patch(self, force=False):
"""Patch local_settings.py.example with local_settings.diff.
The patch application generates the local_settings.py file (the
local_settings.py.example remains unchanged).
http://github.com/sitkatech/pypatch fails if the
local_settings.py.example fi... | Patch local_settings.py.example with local_settings.diff.
The patch application generates the local_settings.py file (the
local_settings.py.example remains unchanged).
http://github.com/sitkatech/pypatch fails if the
local_settings.py.example file is not 100% identical to the one used ... | Below is the the instruction that describes the task:
### Input:
Patch local_settings.py.example with local_settings.diff.
The patch application generates the local_settings.py file (the
local_settings.py.example remains unchanged).
http://github.com/sitkatech/pypatch fails if the
... |
def total_return(self):
"""http://en.wikipedia.org/wiki/Total_shareholder_return - mimics bloomberg total return"""
pxend = self.close
pxstart = pxend.shift(1).bfill()
return (1. + (pxend - pxstart + self.dvds.fillna(0)) / pxstart).cumprod() - 1 | http://en.wikipedia.org/wiki/Total_shareholder_return - mimics bloomberg total return | Below is the the instruction that describes the task:
### Input:
http://en.wikipedia.org/wiki/Total_shareholder_return - mimics bloomberg total return
### Response:
def total_return(self):
"""http://en.wikipedia.org/wiki/Total_shareholder_return - mimics bloomberg total return"""
pxend = self.close... |
def get_all_names() -> Tuple[str]:
""" Retrieve a tuple of all known color names, basic and 'known names'.
"""
names = list(basic_names)
names.extend(name_data)
return tuple(sorted(set(names))) | Retrieve a tuple of all known color names, basic and 'known names'. | Below is the the instruction that describes the task:
### Input:
Retrieve a tuple of all known color names, basic and 'known names'.
### Response:
def get_all_names() -> Tuple[str]:
""" Retrieve a tuple of all known color names, basic and 'known names'.
"""
names = list(basic_names)
names.extend(na... |
def CreateSmartShoppingAdGroup(client, campaign_id):
"""Adds a new Smart Shopping ad group.
Args:
client: an AdWordsClient instance.
campaign_id: the str ID of a Smart Shopping campaign.
Returns:
An ad group ID.
"""
ad_group_service = client.GetService('AdGroupService', version='v201809')
# Cre... | Adds a new Smart Shopping ad group.
Args:
client: an AdWordsClient instance.
campaign_id: the str ID of a Smart Shopping campaign.
Returns:
An ad group ID. | Below is the the instruction that describes the task:
### Input:
Adds a new Smart Shopping ad group.
Args:
client: an AdWordsClient instance.
campaign_id: the str ID of a Smart Shopping campaign.
Returns:
An ad group ID.
### Response:
def CreateSmartShoppingAdGroup(client, campaign_id):
"""Adds ... |
def do_heavy_work(self, block):
"""
Note: Expects Compressor Block like objects
"""
src_file_path = block.latest_file_info.path
img_path = src_file_path + self.get_extension()
self.log.debug("Converting file '%s' to image '%s'", src_file_path, img_path)
from_file_... | Note: Expects Compressor Block like objects | Below is the the instruction that describes the task:
### Input:
Note: Expects Compressor Block like objects
### Response:
def do_heavy_work(self, block):
"""
Note: Expects Compressor Block like objects
"""
src_file_path = block.latest_file_info.path
img_path = src_file_path... |
def get_categories(self, app_name):
"""
Returns a list of the categories for an app name.
"""
cat_nums = self.apps.get(app_name, {}).get("cats", [])
cat_names = [self.categories.get("%s" % cat_num, "")
for cat_num in cat_nums]
return cat_names | Returns a list of the categories for an app name. | Below is the the instruction that describes the task:
### Input:
Returns a list of the categories for an app name.
### Response:
def get_categories(self, app_name):
"""
Returns a list of the categories for an app name.
"""
cat_nums = self.apps.get(app_name, {}).get("cats", [])
... |
def _extend_with_api(test_dict, api_def_dict):
""" extend test with api definition, test will merge and override api definition.
Args:
test_dict (dict): test block, this will override api_def_dict
api_def_dict (dict): api definition
Examples:
>>> api_def_dict = {
"n... | extend test with api definition, test will merge and override api definition.
Args:
test_dict (dict): test block, this will override api_def_dict
api_def_dict (dict): api definition
Examples:
>>> api_def_dict = {
"name": "get token 1",
"request": {...},
... | Below is the the instruction that describes the task:
### Input:
extend test with api definition, test will merge and override api definition.
Args:
test_dict (dict): test block, this will override api_def_dict
api_def_dict (dict): api definition
Examples:
>>> api_def_dict = {
... |
def get_episode_name(self, series, episode_numbers, season_number):
"""Perform lookup for name of episode numbers for a given series.
:param object series: instance of a series
:param list episode_numbers: the episode sequence number
:param int season_number: numeric season of series
... | Perform lookup for name of episode numbers for a given series.
:param object series: instance of a series
:param list episode_numbers: the episode sequence number
:param int season_number: numeric season of series
:returns: list of episode name
:rtype: list(str) | Below is the the instruction that describes the task:
### Input:
Perform lookup for name of episode numbers for a given series.
:param object series: instance of a series
:param list episode_numbers: the episode sequence number
:param int season_number: numeric season of series
:ret... |
def close(self):
""" if this was a zip'd distribution, any introspection
may have resulted in opening or creating temporary files.
Call close in order to clean up. """
if self.tmpdir:
rmtree(self.tmpdir)
self.tmpdir = None
self._contents = None | if this was a zip'd distribution, any introspection
may have resulted in opening or creating temporary files.
Call close in order to clean up. | Below is the the instruction that describes the task:
### Input:
if this was a zip'd distribution, any introspection
may have resulted in opening or creating temporary files.
Call close in order to clean up.
### Response:
def close(self):
""" if this was a zip'd distribution, any introspect... |
def delete_gauge(self, slug):
"""Removes all gauges with the given ``slug``."""
key = self._gauge_key(slug)
self.r.delete(key) # Remove the Gauge
self.r.srem(self._gauge_slugs_key, slug) | Removes all gauges with the given ``slug``. | Below is the the instruction that describes the task:
### Input:
Removes all gauges with the given ``slug``.
### Response:
def delete_gauge(self, slug):
"""Removes all gauges with the given ``slug``."""
key = self._gauge_key(slug)
self.r.delete(key) # Remove the Gauge
self.r.srem(s... |
def ToJSonResponse(self, columns_order=None, order_by=(), req_id=0,
response_handler="google.visualization.Query.setResponse"):
"""Writes a table as a JSON response that can be returned as-is to a client.
This method writes a JSON response to return to a client in response to a
Google ... | Writes a table as a JSON response that can be returned as-is to a client.
This method writes a JSON response to return to a client in response to a
Google Visualization API query. This string can be processed by the calling
page, and is used to deliver a data table to a visualization hosted on
a differ... | Below is the the instruction that describes the task:
### Input:
Writes a table as a JSON response that can be returned as-is to a client.
This method writes a JSON response to return to a client in response to a
Google Visualization API query. This string can be processed by the calling
page, and is u... |
def chunks(l, n):
"""
Yields successive n-sized chunks from l.
"""
for i in _range(0, len(l), n):
yield l[i:i + n] | Yields successive n-sized chunks from l. | Below is the the instruction that describes the task:
### Input:
Yields successive n-sized chunks from l.
### Response:
def chunks(l, n):
"""
Yields successive n-sized chunks from l.
"""
for i in _range(0, len(l), n):
yield l[i:i + n] |
def debug(self, nest_level=1):
"""
Show the binary data and parsed data in a tree structure
"""
prefix = ' ' * nest_level
print('%s%s Object #%s' % (prefix, type_name(self), id(self)))
print('%s Children:' % (prefix,))
for child in self._children:
c... | Show the binary data and parsed data in a tree structure | Below is the the instruction that describes the task:
### Input:
Show the binary data and parsed data in a tree structure
### Response:
def debug(self, nest_level=1):
"""
Show the binary data and parsed data in a tree structure
"""
prefix = ' ' * nest_level
print('%s%s Obj... |
def injector_gear_2_json(self):
"""
transform this local object to JSON.
:return: the JSON from this local object
"""
LOGGER.debug("InjectorCachedGear.injector_gear_2_json")
json_obj = {
'gearId': self.id,
'gearName': self.name,
'gearAd... | transform this local object to JSON.
:return: the JSON from this local object | Below is the the instruction that describes the task:
### Input:
transform this local object to JSON.
:return: the JSON from this local object
### Response:
def injector_gear_2_json(self):
"""
transform this local object to JSON.
:return: the JSON from this local object
"""
... |
def h2o_mean_squared_error(y_actual, y_predicted, weights=None):
"""
Mean squared error regression loss
:param y_actual: H2OFrame of actual response.
:param y_predicted: H2OFrame of predicted response.
:param weights: (Optional) sample weights
:returns: mean squared error loss (best is 0.0).
... | Mean squared error regression loss
:param y_actual: H2OFrame of actual response.
:param y_predicted: H2OFrame of predicted response.
:param weights: (Optional) sample weights
:returns: mean squared error loss (best is 0.0). | Below is the the instruction that describes the task:
### Input:
Mean squared error regression loss
:param y_actual: H2OFrame of actual response.
:param y_predicted: H2OFrame of predicted response.
:param weights: (Optional) sample weights
:returns: mean squared error loss (best is 0.0).
### Respon... |
def truncated_normal_expval(mu, tau, a, b):
"""Expected value of the truncated normal distribution.
.. math::
E(X) =\mu + \frac{\sigma(\varphi_1-\varphi_2)}{T}
where
.. math::
T & =\Phi\left(\frac{B-\mu}{\sigma}\right)-\Phi
\left(\frac{A-\mu}{\sigma}\right)\text \\
\varph... | Expected value of the truncated normal distribution.
.. math::
E(X) =\mu + \frac{\sigma(\varphi_1-\varphi_2)}{T}
where
.. math::
T & =\Phi\left(\frac{B-\mu}{\sigma}\right)-\Phi
\left(\frac{A-\mu}{\sigma}\right)\text \\
\varphi_1 &=
\varphi\left(\frac{A-\mu}{\sigma}\rig... | Below is the the instruction that describes the task:
### Input:
Expected value of the truncated normal distribution.
.. math::
E(X) =\mu + \frac{\sigma(\varphi_1-\varphi_2)}{T}
where
.. math::
T & =\Phi\left(\frac{B-\mu}{\sigma}\right)-\Phi
\left(\frac{A-\mu}{\sigma}\right)\tex... |
def get_ports_alert(self, port, header="", log=False):
"""Return the alert status relative to the port scan return value."""
ret = 'OK'
if port['status'] is None:
ret = 'CAREFUL'
elif port['status'] == 0:
ret = 'CRITICAL'
elif (isinstance(port['status'], (... | Return the alert status relative to the port scan return value. | Below is the the instruction that describes the task:
### Input:
Return the alert status relative to the port scan return value.
### Response:
def get_ports_alert(self, port, header="", log=False):
"""Return the alert status relative to the port scan return value."""
ret = 'OK'
if port['sta... |
def _special_method_cache(method, cache_wrapper):
"""
Because Python treats special methods differently, it's not
possible to use instance attributes to implement the cached
methods.
Instead, install the wrapper method under a different name
and return a simple proxy to that wrapper.
https://github.com/jaraco/... | Because Python treats special methods differently, it's not
possible to use instance attributes to implement the cached
methods.
Instead, install the wrapper method under a different name
and return a simple proxy to that wrapper.
https://github.com/jaraco/jaraco.functools/issues/5 | Below is the the instruction that describes the task:
### Input:
Because Python treats special methods differently, it's not
possible to use instance attributes to implement the cached
methods.
Instead, install the wrapper method under a different name
and return a simple proxy to that wrapper.
https://githu... |
def configure(self, options, config):
"""Configures the test timer plugin."""
super(TimerPlugin, self).configure(options, config)
self.config = config
if self.enabled:
self.timer_top_n = int(options.timer_top_n)
self.timer_ok = self._parse_time(options.timer_ok)
... | Configures the test timer plugin. | Below is the the instruction that describes the task:
### Input:
Configures the test timer plugin.
### Response:
def configure(self, options, config):
"""Configures the test timer plugin."""
super(TimerPlugin, self).configure(options, config)
self.config = config
if self.enabled:
... |
def run_check(self, check, argument_names):
"""Run a check plugin."""
arguments = []
for name in argument_names:
arguments.append(getattr(self, name))
return check(*arguments) | Run a check plugin. | Below is the the instruction that describes the task:
### Input:
Run a check plugin.
### Response:
def run_check(self, check, argument_names):
"""Run a check plugin."""
arguments = []
for name in argument_names:
arguments.append(getattr(self, name))
return check(*argumen... |
def verbose(self, msg, *args, **kw):
"""Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`."""
if self.isEnabledFor(VERBOSE):
self._log(VERBOSE, msg, args, **kw) | Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`. | Below is the the instruction that describes the task:
### Input:
Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`.
### Response:
def verbose(self, msg, *args, **kw):
"""Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func... |
def im_watermark(im, inputtext, font=None, color=None, opacity=.6, margin=(30, 30)):
"""imprints a PIL image with the indicated text in lower-right corner"""
if im.mode != "RGBA":
im = im.convert("RGBA")
textlayer = Image.new("RGBA", im.size, (0, 0, 0, 0))
textdraw = ImageDraw.Draw(textlayer)
... | imprints a PIL image with the indicated text in lower-right corner | Below is the the instruction that describes the task:
### Input:
imprints a PIL image with the indicated text in lower-right corner
### Response:
def im_watermark(im, inputtext, font=None, color=None, opacity=.6, margin=(30, 30)):
"""imprints a PIL image with the indicated text in lower-right corner"""
if ... |
def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]:
"""
Wraps jsonschema.validate, returning the same object passed in.
Args:
request: The deserialized-from-json request.
schema: The jsonschema schema to validate against.
Raises:
jsonschema.ValidationEr... | Wraps jsonschema.validate, returning the same object passed in.
Args:
request: The deserialized-from-json request.
schema: The jsonschema schema to validate against.
Raises:
jsonschema.ValidationError | Below is the the instruction that describes the task:
### Input:
Wraps jsonschema.validate, returning the same object passed in.
Args:
request: The deserialized-from-json request.
schema: The jsonschema schema to validate against.
Raises:
jsonschema.ValidationError
### Response:
d... |
def __execute_bisz(self, instr):
"""Execute BISZ instruction.
"""
op0_val = self.read_operand(instr.operands[0])
op2_val = 1 if op0_val == 0 else 0
self.write_operand(instr.operands[2], op2_val)
return None | Execute BISZ instruction. | Below is the the instruction that describes the task:
### Input:
Execute BISZ instruction.
### Response:
def __execute_bisz(self, instr):
"""Execute BISZ instruction.
"""
op0_val = self.read_operand(instr.operands[0])
op2_val = 1 if op0_val == 0 else 0
self.write_operand(i... |
def _set_state(self, state):
"""Set `_state` and notify any threads waiting for the change.
"""
logger.debug(" _set_state({0!r})".format(state))
self._state = state
self._state_cond.notify() | Set `_state` and notify any threads waiting for the change. | Below is the the instruction that describes the task:
### Input:
Set `_state` and notify any threads waiting for the change.
### Response:
def _set_state(self, state):
"""Set `_state` and notify any threads waiting for the change.
"""
logger.debug(" _set_state({0!r})".format(state))
... |
def call(cmd,
timeout=None,
signum=signal.SIGKILL,
keep_rc=False,
encoding="utf-8",
env=os.environ):
"""
Execute a cmd or list of commands with an optional timeout in seconds.
If `timeout` is supplied and expires, the process is killed with
SIGKILL (kill -9)... | Execute a cmd or list of commands with an optional timeout in seconds.
If `timeout` is supplied and expires, the process is killed with
SIGKILL (kill -9) and an exception is raised. Otherwise, the command
output is returned.
Parameters
----------
cmd: str or [[str]]
The command(s) to e... | Below is the the instruction that describes the task:
### Input:
Execute a cmd or list of commands with an optional timeout in seconds.
If `timeout` is supplied and expires, the process is killed with
SIGKILL (kill -9) and an exception is raised. Otherwise, the command
output is returned.
Paramete... |
def download_url(url, back_off=True, **kwargs):
"""
Get the content of a URL and return a file-like object.
back_off=True provides retry
"""
if back_off:
return _download_with_backoff(url, as_file=True, **kwargs)
else:
return _download_without_backoff(url, as_file=True, **kwargs) | Get the content of a URL and return a file-like object.
back_off=True provides retry | Below is the the instruction that describes the task:
### Input:
Get the content of a URL and return a file-like object.
back_off=True provides retry
### Response:
def download_url(url, back_off=True, **kwargs):
"""
Get the content of a URL and return a file-like object.
back_off=True provides retr... |
def create(cls, rule_entries, union_rules=None):
"""Creates a RuleIndex with tasks indexed by their output type."""
serializable_rules = OrderedDict()
serializable_roots = OrderedSet()
union_rules = OrderedDict(union_rules or ())
def add_task(product_type, rule):
# TODO(#7311): make a default... | Creates a RuleIndex with tasks indexed by their output type. | Below is the the instruction that describes the task:
### Input:
Creates a RuleIndex with tasks indexed by their output type.
### Response:
def create(cls, rule_entries, union_rules=None):
"""Creates a RuleIndex with tasks indexed by their output type."""
serializable_rules = OrderedDict()
serializable... |
def get_resource(self, request, filename):
"""Return a static resource from the shared folder."""
filename = join("shared", basename(filename))
try:
data = pkgutil.get_data(__package__, filename)
except OSError:
data = None
if data is not None:
... | Return a static resource from the shared folder. | Below is the the instruction that describes the task:
### Input:
Return a static resource from the shared folder.
### Response:
def get_resource(self, request, filename):
"""Return a static resource from the shared folder."""
filename = join("shared", basename(filename))
try:
da... |
def covariance(self):
"""
The covariance matrix of the 2D Gaussian function that has the
same second-order moments as the source.
"""
mu = self.moments_central
if mu[0, 0] != 0:
m = mu / mu[0, 0]
covariance = self._check_covariance(
... | The covariance matrix of the 2D Gaussian function that has the
same second-order moments as the source. | Below is the the instruction that describes the task:
### Input:
The covariance matrix of the 2D Gaussian function that has the
same second-order moments as the source.
### Response:
def covariance(self):
"""
The covariance matrix of the 2D Gaussian function that has the
same second... |
def get_events(self, time_period, include_archived=False) -> Optional[int]:
"""Get the number of events that have occurred on this Monitor.
Specifically only gets events that have occurred within the TimePeriod
provided.
"""
date_filter = '1%20{}'.format(time_period.period)
... | Get the number of events that have occurred on this Monitor.
Specifically only gets events that have occurred within the TimePeriod
provided. | Below is the the instruction that describes the task:
### Input:
Get the number of events that have occurred on this Monitor.
Specifically only gets events that have occurred within the TimePeriod
provided.
### Response:
def get_events(self, time_period, include_archived=False) -> Optional[int]:
... |
def getRealInterfaceNumber(self, interface):
"""
Returns the host-visible interface number, or None if there is no such
interface.
"""
try:
return self._ioctl(INTERFACE_REVMAP, interface)
except IOError as exc:
if exc.errno == errno.EDOM:
... | Returns the host-visible interface number, or None if there is no such
interface. | Below is the the instruction that describes the task:
### Input:
Returns the host-visible interface number, or None if there is no such
interface.
### Response:
def getRealInterfaceNumber(self, interface):
"""
Returns the host-visible interface number, or None if there is no such
in... |
def get_text(html_content, display_images=False, deduplicate_captions=False, display_links=False):
'''
::param: html_content
::returns:
a text representation of the html content.
'''
html_content = html_content.strip()
if not html_content:
return ""
# strip XML declaration, ... | ::param: html_content
::returns:
a text representation of the html content. | Below is the the instruction that describes the task:
### Input:
::param: html_content
::returns:
a text representation of the html content.
### Response:
def get_text(html_content, display_images=False, deduplicate_captions=False, display_links=False):
'''
::param: html_content
::returns:
... |
def cancelEdit( self ):
"""
Rejects the current edit and shows the parts widget.
"""
if ( self._partsWidget.isVisible() ):
return False
self._completerTree.hide()
self.completer().popup().hide()
self.setText(self._origina... | Rejects the current edit and shows the parts widget. | Below is the the instruction that describes the task:
### Input:
Rejects the current edit and shows the parts widget.
### Response:
def cancelEdit( self ):
"""
Rejects the current edit and shows the parts widget.
"""
if ( self._partsWidget.isVisible() ):
return ... |
def batch_get_documents(
self,
database,
documents,
mask=None,
transaction=None,
new_transaction=None,
read_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
... | Gets multiple documents.
Documents returned by this method are not guaranteed to be returned in the
same order that they were requested.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
... | Below is the the instruction that describes the task:
### Input:
Gets multiple documents.
Documents returned by this method are not guaranteed to be returned in the
same order that they were requested.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
... |
def status_search(self, status):
"""Searches for jobs matching the given ``status``."""
json = self._fetch_json()
jobs = json['response']
for job in jobs:
job_info = jobs[job]
if job_info['status'].lower() == status.lower():
yield self._build_resul... | Searches for jobs matching the given ``status``. | Below is the the instruction that describes the task:
### Input:
Searches for jobs matching the given ``status``.
### Response:
def status_search(self, status):
"""Searches for jobs matching the given ``status``."""
json = self._fetch_json()
jobs = json['response']
for job in jobs:
... |
def azlyrics(song):
"""
Returns the lyrics found in azlyrics for the specified mp3 file or an empty
string if not found.
"""
artist = song.artist.lower()
if artist[0:2] == 'a ':
artist = artist[2:]
artist = normalize(artist, URLESCAPES, '')
title = song.title.lower()
title = ... | Returns the lyrics found in azlyrics for the specified mp3 file or an empty
string if not found. | Below is the the instruction that describes the task:
### Input:
Returns the lyrics found in azlyrics for the specified mp3 file or an empty
string if not found.
### Response:
def azlyrics(song):
"""
Returns the lyrics found in azlyrics for the specified mp3 file or an empty
string if not found.
... |
async def delete_pairwise(self, their_did: str) -> None:
"""
Remove a pairwise DID record by its remote DID. Silently return if no such record is present.
Raise WalletState for closed wallet, or BadIdentifier for invalid pairwise DID.
:param their_did: remote DID marking pairwise DID to... | Remove a pairwise DID record by its remote DID. Silently return if no such record is present.
Raise WalletState for closed wallet, or BadIdentifier for invalid pairwise DID.
:param their_did: remote DID marking pairwise DID to remove | Below is the the instruction that describes the task:
### Input:
Remove a pairwise DID record by its remote DID. Silently return if no such record is present.
Raise WalletState for closed wallet, or BadIdentifier for invalid pairwise DID.
:param their_did: remote DID marking pairwise DID to remove
... |
def solve(self):
"""Solve rpn expression, return None if not valid."""
popflag = True
self.tmpopslist = []
while True:
while self.opslist and popflag:
op = self.opslist.pop()
if self.is_variable(op):
op = self.variables.get(... | Solve rpn expression, return None if not valid. | Below is the the instruction that describes the task:
### Input:
Solve rpn expression, return None if not valid.
### Response:
def solve(self):
"""Solve rpn expression, return None if not valid."""
popflag = True
self.tmpopslist = []
while True:
while self.opslist and po... |
def _ExtractPathSpecsFromFile(self, file_entry):
"""Extracts path specification from a file.
Args:
file_entry (dfvfs.FileEntry): file entry that refers to the file.
Yields:
dfvfs.PathSpec: path specification of a file entry found in the file.
"""
produced_main_path_spec = False
for... | Extracts path specification from a file.
Args:
file_entry (dfvfs.FileEntry): file entry that refers to the file.
Yields:
dfvfs.PathSpec: path specification of a file entry found in the file. | Below is the the instruction that describes the task:
### Input:
Extracts path specification from a file.
Args:
file_entry (dfvfs.FileEntry): file entry that refers to the file.
Yields:
dfvfs.PathSpec: path specification of a file entry found in the file.
### Response:
def _ExtractPathSpecsFr... |
def augpath(path, augsuf='', augext='', augpref='', augdir=None, newext=None,
newfname=None, ensure=False, prefix=None, suffix=None):
"""
augments end of path before the extension.
augpath
Args:
path (str):
augsuf (str): augment filename before extension
Returns:
... | augments end of path before the extension.
augpath
Args:
path (str):
augsuf (str): augment filename before extension
Returns:
str: newpath
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> path = 'somefile.txt'
>>> au... | Below is the the instruction that describes the task:
### Input:
augments end of path before the extension.
augpath
Args:
path (str):
augsuf (str): augment filename before extension
Returns:
str: newpath
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_p... |
def get(self, singleSnapshot=False):
"""
*geneate the pyephem positions*
**Key Arguments:**
- ``singleSnapshot`` -- just extract positions for a single pyephem snapshot (used for unit testing)
**Return:**
- ``None``
"""
self.log.info('starting t... | *geneate the pyephem positions*
**Key Arguments:**
- ``singleSnapshot`` -- just extract positions for a single pyephem snapshot (used for unit testing)
**Return:**
- ``None`` | Below is the the instruction that describes the task:
### Input:
*geneate the pyephem positions*
**Key Arguments:**
- ``singleSnapshot`` -- just extract positions for a single pyephem snapshot (used for unit testing)
**Return:**
- ``None``
### Response:
def get(self, sing... |
def parse_args(self):
"""Parse command line arguments."""
args = self.init_args().parse_args()
# Load the configuration file, if it exists
self.config = Config(args.conf_file)
# Debug mode
if args.debug:
from logging import DEBUG
logger.setLevel(... | Parse command line arguments. | Below is the the instruction that describes the task:
### Input:
Parse command line arguments.
### Response:
def parse_args(self):
"""Parse command line arguments."""
args = self.init_args().parse_args()
# Load the configuration file, if it exists
self.config = Config(args.conf_fil... |
def parse_json_qry(qry_str):
""" Parses a json query string into its parts
args:
qry_str: query string
params: variables passed into the string
"""
def param_analyzer(param_list):
rtn_list = []
for param in param_list:
parts = param.strip().split("=")
... | Parses a json query string into its parts
args:
qry_str: query string
params: variables passed into the string | Below is the the instruction that describes the task:
### Input:
Parses a json query string into its parts
args:
qry_str: query string
params: variables passed into the string
### Response:
def parse_json_qry(qry_str):
""" Parses a json query string into its parts
args:
qry_st... |
def _from_string(cls, string):
"""Create an Actor from a string.
:param string: is the string, which is expected to be in regular git format
John Doe <jdoe@example.com>
:return: Actor """
m = cls.name_email_regex.search(string)
if m:
name, email = m.... | Create an Actor from a string.
:param string: is the string, which is expected to be in regular git format
John Doe <jdoe@example.com>
:return: Actor | Below is the the instruction that describes the task:
### Input:
Create an Actor from a string.
:param string: is the string, which is expected to be in regular git format
John Doe <jdoe@example.com>
:return: Actor
### Response:
def _from_string(cls, string):
"""Create an ... |
def parse_updates(rule):
'''
Parse the updates line
'''
rules = shlex.split(rule)
rules.pop(0)
return {'url': rules[0]} if rules else True | Parse the updates line | Below is the the instruction that describes the task:
### Input:
Parse the updates line
### Response:
def parse_updates(rule):
'''
Parse the updates line
'''
rules = shlex.split(rule)
rules.pop(0)
return {'url': rules[0]} if rules else True |
def from_shortcode(cls, context: InstaloaderContext, shortcode: str):
"""Create a post object from a given shortcode"""
# pylint:disable=protected-access
post = cls(context, {'shortcode': shortcode})
post._node = post._full_metadata
return post | Create a post object from a given shortcode | Below is the the instruction that describes the task:
### Input:
Create a post object from a given shortcode
### Response:
def from_shortcode(cls, context: InstaloaderContext, shortcode: str):
"""Create a post object from a given shortcode"""
# pylint:disable=protected-access
post = cls(con... |
def _process_queue_tasks(self, queue, queue_lock, task_ids, now, log):
"""Process tasks in queue."""
processed_count = 0
# Get all tasks
serialized_tasks = self.connection.mget([
self._key('task', task_id) for task_id in task_ids
])
# Parse tasks
ta... | Process tasks in queue. | Below is the the instruction that describes the task:
### Input:
Process tasks in queue.
### Response:
def _process_queue_tasks(self, queue, queue_lock, task_ids, now, log):
"""Process tasks in queue."""
processed_count = 0
# Get all tasks
serialized_tasks = self.connection.mget([... |
def write_register(self, registeraddress, value, numberOfDecimals=0, functioncode=16, signed=False):
"""Write an integer to one 16-bit register in the slave, possibly scaling it.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Args:
* register... | Write an integer to one 16-bit register in the slave, possibly scaling it.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* value (int or float): T... | Below is the the instruction that describes the task:
### Input:
Write an integer to one 16-bit register in the slave, possibly scaling it.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Args:
* registeraddress (int): The slave register address ... |
def add(self, command): # type: (BaseCommand) -> Application
"""
Adds a command object.
"""
self.add_command(command.config)
command.set_application(self)
return self | Adds a command object. | Below is the the instruction that describes the task:
### Input:
Adds a command object.
### Response:
def add(self, command): # type: (BaseCommand) -> Application
"""
Adds a command object.
"""
self.add_command(command.config)
command.set_application(self)
return s... |
def to_dataframe(self, start_row=0, max_rows=None):
""" Exports the table to a Pandas dataframe.
Args:
start_row: the row of the table at which to start the export (default 0)
max_rows: an upper limit on the number of rows to export (default None)
Returns:
A Pandas dataframe containing th... | Exports the table to a Pandas dataframe.
Args:
start_row: the row of the table at which to start the export (default 0)
max_rows: an upper limit on the number of rows to export (default None)
Returns:
A Pandas dataframe containing the table data. | Below is the the instruction that describes the task:
### Input:
Exports the table to a Pandas dataframe.
Args:
start_row: the row of the table at which to start the export (default 0)
max_rows: an upper limit on the number of rows to export (default None)
Returns:
A Pandas dataframe cont... |
def register_bootstrap_options(cls, register):
"""Register bootstrap options.
"Bootstrap options" are a small set of options whose values are useful when registering other
options. Therefore we must bootstrap them early, before other options are registered, let
alone parsed.
Bootstrap option value... | Register bootstrap options.
"Bootstrap options" are a small set of options whose values are useful when registering other
options. Therefore we must bootstrap them early, before other options are registered, let
alone parsed.
Bootstrap option values can be interpolated into the config file, and can be... | Below is the the instruction that describes the task:
### Input:
Register bootstrap options.
"Bootstrap options" are a small set of options whose values are useful when registering other
options. Therefore we must bootstrap them early, before other options are registered, let
alone parsed.
Bootstr... |
def extract_function_metadata(wrapped, instance, args, kwargs, return_value):
"""Stash the `args` and `kwargs` into the metadata of the subsegment."""
LOGGER.debug(
'Extracting function call metadata',
args=args,
kwargs=kwargs,
)
return {
'metadata': {
'args':... | Stash the `args` and `kwargs` into the metadata of the subsegment. | Below is the the instruction that describes the task:
### Input:
Stash the `args` and `kwargs` into the metadata of the subsegment.
### Response:
def extract_function_metadata(wrapped, instance, args, kwargs, return_value):
"""Stash the `args` and `kwargs` into the metadata of the subsegment."""
LOGGER.deb... |
def is_member(self, m):
"""Check if a user is a member of the chatroom"""
if not m:
return False
elif isinstance(m, basestring):
jid = m
else:
jid = m['JID']
is_member = len(filter(lambda m: m['JID'] == jid and m.get('STATUS') in ('ACTIVE', 'I... | Check if a user is a member of the chatroom | Below is the the instruction that describes the task:
### Input:
Check if a user is a member of the chatroom
### Response:
def is_member(self, m):
"""Check if a user is a member of the chatroom"""
if not m:
return False
elif isinstance(m, basestring):
jid = m
... |
def of_type(self, *kinds):
"""Selects documents if a field is of the correct type.
Document.field.of_type()
Document.field.of_type('string')
Element operator: {$type: self.__foreign__}
Documentation: https://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type
"""
if self._combinin... | Selects documents if a field is of the correct type.
Document.field.of_type()
Document.field.of_type('string')
Element operator: {$type: self.__foreign__}
Documentation: https://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type | Below is the the instruction that describes the task:
### Input:
Selects documents if a field is of the correct type.
Document.field.of_type()
Document.field.of_type('string')
Element operator: {$type: self.__foreign__}
Documentation: https://docs.mongodb.org/manual/reference/operator/query/type/#op... |
def extract_subset(self, subset):
"""
Find all nodes in a subset.
We assume the oboInOwl encoding of subsets, and subset IDs are IRIs
"""
# note subsets have an unusual encoding
query = """
prefix oboInOwl: <http://www.geneontology.org/formats/oboInOwl#>... | Find all nodes in a subset.
We assume the oboInOwl encoding of subsets, and subset IDs are IRIs | Below is the the instruction that describes the task:
### Input:
Find all nodes in a subset.
We assume the oboInOwl encoding of subsets, and subset IDs are IRIs
### Response:
def extract_subset(self, subset):
"""
Find all nodes in a subset.
We assume the oboInOwl encoding ... |
def formatted(self):
# pylint: disable=line-too-long
"""
Return a human readable string with the statistics for this container.
The operations are sorted by decreasing average time.
The three columns for `ServerTime` are included only if the WBEM server
has returned WBEM... | Return a human readable string with the statistics for this container.
The operations are sorted by decreasing average time.
The three columns for `ServerTime` are included only if the WBEM server
has returned WBEM server response times.
Example if statistics are enabled::
... | Below is the the instruction that describes the task:
### Input:
Return a human readable string with the statistics for this container.
The operations are sorted by decreasing average time.
The three columns for `ServerTime` are included only if the WBEM server
has returned WBEM server resp... |
def inject_coordinates(self,
x_coords,
y_coords,
rescale_x=None,
rescale_y=None,
original_x=None,
original_y=None):
'''
Inject custom x and y ... | Inject custom x and y coordinates for each term into chart.
Parameters
----------
x_coords: array-like
positions on x-axis \in [0,1]
y_coords: array-like
positions on y-axis \in [0,1]
rescale_x: lambda list[0,1]: list[0,1], default identity
Re... | Below is the the instruction that describes the task:
### Input:
Inject custom x and y coordinates for each term into chart.
Parameters
----------
x_coords: array-like
positions on x-axis \in [0,1]
y_coords: array-like
positions on y-axis \in [0,1]
re... |
def res_from_en(pst,enfile):
"""load ensemble file for residual into a pandas.DataFrame
Parameters
----------
enfile : str
ensemble file name
Returns
-------
pandas.DataFrame : pandas.DataFrame
"""
converters = {"name": str_con, "group": str... | load ensemble file for residual into a pandas.DataFrame
Parameters
----------
enfile : str
ensemble file name
Returns
-------
pandas.DataFrame : pandas.DataFrame | Below is the the instruction that describes the task:
### Input:
load ensemble file for residual into a pandas.DataFrame
Parameters
----------
enfile : str
ensemble file name
Returns
-------
pandas.DataFrame : pandas.DataFrame
### Response:
def res_from... |
def serialize_object(self, attr, **kwargs):
"""Serialize a generic object.
This will be handled as a dictionary. If object passed in is not
a basic type (str, int, float, dict, list) it will simply be
cast to str.
:param dict attr: Object to be serialized.
:rtype: dict o... | Serialize a generic object.
This will be handled as a dictionary. If object passed in is not
a basic type (str, int, float, dict, list) it will simply be
cast to str.
:param dict attr: Object to be serialized.
:rtype: dict or str | Below is the the instruction that describes the task:
### Input:
Serialize a generic object.
This will be handled as a dictionary. If object passed in is not
a basic type (str, int, float, dict, list) it will simply be
cast to str.
:param dict attr: Object to be serialized.
... |
def make_tar(tfn, source_dirs, ignore_path=[], optimize_python=True):
'''
Make a zip file `fn` from the contents of source_dis.
'''
# selector function
def select(fn):
rfn = realpath(fn)
for p in ignore_path:
if p.endswith('/'):
p = p[:-1]
if ... | Make a zip file `fn` from the contents of source_dis. | Below is the the instruction that describes the task:
### Input:
Make a zip file `fn` from the contents of source_dis.
### Response:
def make_tar(tfn, source_dirs, ignore_path=[], optimize_python=True):
'''
Make a zip file `fn` from the contents of source_dis.
'''
# selector function
def selec... |
def rebin(d, n_x, n_y=None):
""" Rebin data by averaging bins together
Args:
d (np.array): data
n_x (int): number of bins in x dir to rebin into one
n_y (int): number of bins in y dir to rebin into one
Returns:
d: rebinned data with shape (n_x, n_y)
"""
if d.ndim == 2:
if ... | Rebin data by averaging bins together
Args:
d (np.array): data
n_x (int): number of bins in x dir to rebin into one
n_y (int): number of bins in y dir to rebin into one
Returns:
d: rebinned data with shape (n_x, n_y) | Below is the the instruction that describes the task:
### Input:
Rebin data by averaging bins together
Args:
d (np.array): data
n_x (int): number of bins in x dir to rebin into one
n_y (int): number of bins in y dir to rebin into one
Returns:
d: rebinned data with shape (n_x, n_y)
### Resp... |
def forget_canvas(canvas):
""" Forget about the given canvas. Used by the canvas when closed.
"""
cc = [c() for c in canvasses if c() is not None]
while canvas in cc:
cc.remove(canvas)
canvasses[:] = [weakref.ref(c) for c in cc] | Forget about the given canvas. Used by the canvas when closed. | Below is the the instruction that describes the task:
### Input:
Forget about the given canvas. Used by the canvas when closed.
### Response:
def forget_canvas(canvas):
""" Forget about the given canvas. Used by the canvas when closed.
"""
cc = [c() for c in canvasses if c() is not None]
while canv... |
def disable_active_checks(self, checks):
"""Disable active checks for this host/service
Update check in progress with current object information
:param checks: Checks object, to change all checks in progress
:type checks: alignak.objects.check.Checks
:return: None
"""
... | Disable active checks for this host/service
Update check in progress with current object information
:param checks: Checks object, to change all checks in progress
:type checks: alignak.objects.check.Checks
:return: None | Below is the the instruction that describes the task:
### Input:
Disable active checks for this host/service
Update check in progress with current object information
:param checks: Checks object, to change all checks in progress
:type checks: alignak.objects.check.Checks
:return: No... |
def hooks_setup(trun, parent, hnames=None):
"""
Setup test-hooks
@returns dict of hook filepaths {"enter": [], "exit": []}
"""
hooks = {
"enter": [],
"exit": []
}
if hnames is None: # Nothing to do, just return the struct
return hooks
for hname in hnames:... | Setup test-hooks
@returns dict of hook filepaths {"enter": [], "exit": []} | Below is the the instruction that describes the task:
### Input:
Setup test-hooks
@returns dict of hook filepaths {"enter": [], "exit": []}
### Response:
def hooks_setup(trun, parent, hnames=None):
"""
Setup test-hooks
@returns dict of hook filepaths {"enter": [], "exit": []}
"""
hooks = {... |
def GroupSensorsFind(self, group_id, parameters, filters, namespace = None):
"""
Find sensors in a group based on a number of filters on metatags
@param group_id (int) - Id of the group in which to find sensors
@param namespace (string) - Namespace to use in... | Find sensors in a group based on a number of filters on metatags
@param group_id (int) - Id of the group in which to find sensors
@param namespace (string) - Namespace to use in filtering on metatags
@param parameters (dictionary) - Dictionary containing additional p... | Below is the the instruction that describes the task:
### Input:
Find sensors in a group based on a number of filters on metatags
@param group_id (int) - Id of the group in which to find sensors
@param namespace (string) - Namespace to use in filtering on metatags
... |
def _generate_grid(self):
"""Get the all possible values for each of the tunables."""
grid_axes = []
for _, param in self.tunables:
grid_axes.append(param.get_grid_axis(self.grid_width))
return grid_axes | Get the all possible values for each of the tunables. | Below is the the instruction that describes the task:
### Input:
Get the all possible values for each of the tunables.
### Response:
def _generate_grid(self):
"""Get the all possible values for each of the tunables."""
grid_axes = []
for _, param in self.tunables:
grid_axes.appe... |
def column_print(fmt, rows, print_func):
"""Prints a formatted list, adjusting the width so everything fits.
fmt contains a single character for each column. < indicates that the
column should be left justified, > indicates that the column should
be right justified. The last column may be a space which ... | Prints a formatted list, adjusting the width so everything fits.
fmt contains a single character for each column. < indicates that the
column should be left justified, > indicates that the column should
be right justified. The last column may be a space which implies left
justification and no padding. | Below is the the instruction that describes the task:
### Input:
Prints a formatted list, adjusting the width so everything fits.
fmt contains a single character for each column. < indicates that the
column should be left justified, > indicates that the column should
be right justified. The last column ... |
def xml_to_dict(raw_xml):
"""Convert a XML stream into a dictionary.
This function transforms a xml stream into a dictionary. The
attributes are stored as single elements while child nodes are
stored into lists. The text node is stored using the special
key '__text__'.
This code is based on Wi... | Convert a XML stream into a dictionary.
This function transforms a xml stream into a dictionary. The
attributes are stored as single elements while child nodes are
stored into lists. The text node is stored using the special
key '__text__'.
This code is based on Winston Ewert's solution to this pr... | Below is the the instruction that describes the task:
### Input:
Convert a XML stream into a dictionary.
This function transforms a xml stream into a dictionary. The
attributes are stored as single elements while child nodes are
stored into lists. The text node is stored using the special
key '__te... |
def negotiate_header(url):
"""
Return the "Authorization" HTTP header value to use for this URL.
"""
hostname = urlparse(url).hostname
_, krb_context = kerberos.authGSSClientInit('HTTP@%s' % hostname)
# authGSSClientStep goes over the network to the KDC (ie blocking).
yield threads.deferToTh... | Return the "Authorization" HTTP header value to use for this URL. | Below is the the instruction that describes the task:
### Input:
Return the "Authorization" HTTP header value to use for this URL.
### Response:
def negotiate_header(url):
"""
Return the "Authorization" HTTP header value to use for this URL.
"""
hostname = urlparse(url).hostname
_, krb_context ... |
def Rx_matrix(theta):
"""Rotation matrix around the X axis"""
return np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
]) | Rotation matrix around the X axis | Below is the the instruction that describes the task:
### Input:
Rotation matrix around the X axis
### Response:
def Rx_matrix(theta):
"""Rotation matrix around the X axis"""
return np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
]) |
def decrypt(self, encryption_key, iv, encrypted_data):
"""Decrypt encrypted subtitle data
@param int subtitle_id
@param str iv
@param str encrypted_data
@return str
"""
logger.info('Decrypting subtitles with length (%d bytes), key=%r',
len(encrypted_... | Decrypt encrypted subtitle data
@param int subtitle_id
@param str iv
@param str encrypted_data
@return str | Below is the the instruction that describes the task:
### Input:
Decrypt encrypted subtitle data
@param int subtitle_id
@param str iv
@param str encrypted_data
@return str
### Response:
def decrypt(self, encryption_key, iv, encrypted_data):
"""Decrypt encrypted subtitle dat... |
def _pre_delete_hook(cls, key):
"""
Removes instance from index.
"""
if cls.searching_enabled:
doc_id = cls.search_get_document_id(key)
index = cls.search_get_index()
index.delete(doc_id) | Removes instance from index. | Below is the the instruction that describes the task:
### Input:
Removes instance from index.
### Response:
def _pre_delete_hook(cls, key):
"""
Removes instance from index.
"""
if cls.searching_enabled:
doc_id = cls.search_get_document_id(key)
index = cls.sea... |
def create(self, collector, tryImport=True):
""" Creates an inspector of the registered and passes the collector to the constructor.
Tries to import the class if tryImport is True.
Raises ImportError if the class could not be imported.
"""
cls = self.getClass(tryImport=tr... | Creates an inspector of the registered and passes the collector to the constructor.
Tries to import the class if tryImport is True.
Raises ImportError if the class could not be imported. | Below is the the instruction that describes the task:
### Input:
Creates an inspector of the registered and passes the collector to the constructor.
Tries to import the class if tryImport is True.
Raises ImportError if the class could not be imported.
### Response:
def create(self, collecto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.