code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _normpath(self, pathname):
"Return path normalized for duscan usage: no trailing slash."
if pathname == '/':
pathname = ''
elif pathname.endswith('/'):
pathname = pathname[:-1]
assert not pathname.endswith('/'), pathname
return pathname | Return path normalized for duscan usage: no trailing slash. | Below is the the instruction that describes the task:
### Input:
Return path normalized for duscan usage: no trailing slash.
### Response:
def _normpath(self, pathname):
"Return path normalized for duscan usage: no trailing slash."
if pathname == '/':
pathname = ''
elif pathname... |
def _displayattrs(attrib, expandattrs):
"""
Helper function to display the attributes of a Node object in lexicographic
order.
:param attrib: dictionary with the attributes
:param expandattrs: if True also displays the value of the attributes
"""
if not attrib:
return ''
if expa... | Helper function to display the attributes of a Node object in lexicographic
order.
:param attrib: dictionary with the attributes
:param expandattrs: if True also displays the value of the attributes | Below is the the instruction that describes the task:
### Input:
Helper function to display the attributes of a Node object in lexicographic
order.
:param attrib: dictionary with the attributes
:param expandattrs: if True also displays the value of the attributes
### Response:
def _displayattrs(attrib... |
def parse_placeholder(parser, token):
"""Parse the `PlaceholderNode` parameters.
Return a tuple with the name and parameters."""
bits = token.split_contents()
count = len(bits)
error_string = '%r tag requires at least one argument' % bits[0]
if count <= 1:
raise TemplateSyntaxError(erro... | Parse the `PlaceholderNode` parameters.
Return a tuple with the name and parameters. | Below is the the instruction that describes the task:
### Input:
Parse the `PlaceholderNode` parameters.
Return a tuple with the name and parameters.
### Response:
def parse_placeholder(parser, token):
"""Parse the `PlaceholderNode` parameters.
Return a tuple with the name and parameters."""
bits... |
def write_fits(self, data, outfile, extname="SKYMAP", clobber=True):
""" Write input data to a FITS file
data : The data begin stored
outfile : The name of the output file
extname : The HDU extension name
clobber : True -> overwrite existing files
"""
... | Write input data to a FITS file
data : The data begin stored
outfile : The name of the output file
extname : The HDU extension name
clobber : True -> overwrite existing files | Below is the the instruction that describes the task:
### Input:
Write input data to a FITS file
data : The data begin stored
outfile : The name of the output file
extname : The HDU extension name
clobber : True -> overwrite existing files
### Response:
def write... |
def _fullqualname_builtin_py2(obj):
"""Fully qualified name for 'builtin_function_or_method' objects
in Python 2.
"""
if obj.__self__ is None:
# built-in functions
module = obj.__module__
qualname = obj.__name__
else:
# built-in methods
if inspect.isclass(obj... | Fully qualified name for 'builtin_function_or_method' objects
in Python 2. | Below is the the instruction that describes the task:
### Input:
Fully qualified name for 'builtin_function_or_method' objects
in Python 2.
### Response:
def _fullqualname_builtin_py2(obj):
"""Fully qualified name for 'builtin_function_or_method' objects
in Python 2.
"""
if obj.__self__ is Non... |
def reply(
self,
text: str,
quote: bool = None,
parse_mode: str = "",
disable_web_page_preview: bool = None,
disable_notification: bool = None,
reply_to_message_id: int = None,
reply_markup=None
) -> "Message":
"""Bound method *reply* of :obj:`... | Bound method *reply* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_message(
chat_id=message.chat.id,
text="hello",
reply_to_message_id=message.message_id
)
Example:
... | Below is the the instruction that describes the task:
### Input:
Bound method *reply* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_message(
chat_id=message.chat.id,
text="hello",
reply_t... |
def sendmail_proxy(subject, email, template, **context):
"""Cast the lazy_gettext'ed subject to string before passing to Celery"""
sendmail.delay(subject.value, email, template, **context) | Cast the lazy_gettext'ed subject to string before passing to Celery | Below is the the instruction that describes the task:
### Input:
Cast the lazy_gettext'ed subject to string before passing to Celery
### Response:
def sendmail_proxy(subject, email, template, **context):
"""Cast the lazy_gettext'ed subject to string before passing to Celery"""
sendmail.delay(subject.value,... |
def extract_references_from_fulltext(fulltext):
"""Locate and extract the reference section from a fulltext document.
Return the extracted reference section as a list of strings, whereby each
string in the list is considered to be a single reference line.
E.g. a string could be something like:... | Locate and extract the reference section from a fulltext document.
Return the extracted reference section as a list of strings, whereby each
string in the list is considered to be a single reference line.
E.g. a string could be something like:
'[19] Wilson, A. Unpublished (1986).
@p... | Below is the the instruction that describes the task:
### Input:
Locate and extract the reference section from a fulltext document.
Return the extracted reference section as a list of strings, whereby each
string in the list is considered to be a single reference line.
E.g. a string could be s... |
def pvpc_calc_tcu_cp_feu_d(df, verbose=True, convert_kwh=True):
"""Procesa TCU, CP, FEU diario.
:param df:
:param verbose:
:param convert_kwh:
:return:
"""
if 'TCU' + TARIFAS[0] not in df.columns:
# Pasa de €/MWh a €/kWh:
if convert_kwh:
cols_mwh = [c + t for c i... | Procesa TCU, CP, FEU diario.
:param df:
:param verbose:
:param convert_kwh:
:return: | Below is the the instruction that describes the task:
### Input:
Procesa TCU, CP, FEU diario.
:param df:
:param verbose:
:param convert_kwh:
:return:
### Response:
def pvpc_calc_tcu_cp_feu_d(df, verbose=True, convert_kwh=True):
"""Procesa TCU, CP, FEU diario.
:param df:
:param verbose... |
async def async_set_config(self, data):
"""Set config of thermostat.
{
"mode": "auto",
"heatsetpoint": 180,
}
"""
field = self.deconz_id + '/config'
await self._async_set_state_callback(field, data) | Set config of thermostat.
{
"mode": "auto",
"heatsetpoint": 180,
} | Below is the the instruction that describes the task:
### Input:
Set config of thermostat.
{
"mode": "auto",
"heatsetpoint": 180,
}
### Response:
async def async_set_config(self, data):
"""Set config of thermostat.
{
"mode": "auto",
... |
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.messa... | Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`. | Below is the the instruction that describes the task:
### Input:
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
### Response:
... |
def restore_region(self, region, bbox=None, xy=None):
"""
Restore the saved region. If bbox (instance of BboxBase, or
its extents) is given, only the region specified by the bbox
will be restored. *xy* (a tuple of two floasts) optionally
specifies the new position (the LLC of the... | Restore the saved region. If bbox (instance of BboxBase, or
its extents) is given, only the region specified by the bbox
will be restored. *xy* (a tuple of two floasts) optionally
specifies the new position (the LLC of the original region,
not the LLC of the bbox) where the region will b... | Below is the the instruction that describes the task:
### Input:
Restore the saved region. If bbox (instance of BboxBase, or
its extents) is given, only the region specified by the bbox
will be restored. *xy* (a tuple of two floasts) optionally
specifies the new position (the LLC of the orig... |
def _pfp__build(self, stream=None, save_offset=False):
"""Build the union and write the result into the stream.
:stream: None
:returns: None
"""
max_size = -1
if stream is None:
core_stream = six.BytesIO()
new_stream = bitwrap.BitwrappedStream(cor... | Build the union and write the result into the stream.
:stream: None
:returns: None | Below is the the instruction that describes the task:
### Input:
Build the union and write the result into the stream.
:stream: None
:returns: None
### Response:
def _pfp__build(self, stream=None, save_offset=False):
"""Build the union and write the result into the stream.
:stream... |
def degrade_to_order(self, new_order):
"""
Degrades the MOC instance to a new, less precise, MOC.
The maximum depth (i.e. the depth of the smallest HEALPix cells that can be found in the MOC) of the
degraded MOC is set to ``new_order``.
Parameters
----------
ne... | Degrades the MOC instance to a new, less precise, MOC.
The maximum depth (i.e. the depth of the smallest HEALPix cells that can be found in the MOC) of the
degraded MOC is set to ``new_order``.
Parameters
----------
new_order : int
Maximum depth of the output degra... | Below is the the instruction that describes the task:
### Input:
Degrades the MOC instance to a new, less precise, MOC.
The maximum depth (i.e. the depth of the smallest HEALPix cells that can be found in the MOC) of the
degraded MOC is set to ``new_order``.
Parameters
----------
... |
def parse(self, xml_file):
"Get a list of parsed recipes from BeerXML input"
recipes = []
with open(xml_file, "rt") as f:
tree = ElementTree.parse(f)
for recipeNode in tree.iter():
if self.to_lower(recipeNode.tag) != "recipe":
continue
... | Get a list of parsed recipes from BeerXML input | Below is the the instruction that describes the task:
### Input:
Get a list of parsed recipes from BeerXML input
### Response:
def parse(self, xml_file):
"Get a list of parsed recipes from BeerXML input"
recipes = []
with open(xml_file, "rt") as f:
tree = ElementTree.parse(f)
... |
def getAllExportsAsDict(self, plugin_list=None):
"""
Return all the stats to be exported (list).
Default behavor is to export all the stat
if plugin_list is provided, only export stats of given plugin (list)
"""
if plugin_list is None:
# All plugins should be ... | Return all the stats to be exported (list).
Default behavor is to export all the stat
if plugin_list is provided, only export stats of given plugin (list) | Below is the the instruction that describes the task:
### Input:
Return all the stats to be exported (list).
Default behavor is to export all the stat
if plugin_list is provided, only export stats of given plugin (list)
### Response:
def getAllExportsAsDict(self, plugin_list=None):
"""
... |
def insert_permission(
self,
file_id,
value,
perm_type,
role,
notify=True,
email_message=None,
with_link=False
):
"""Creates a new permission for a file.
:param file_id: a spreadsheet ID (aka file ID.)
:type file_id: str
... | Creates a new permission for a file.
:param file_id: a spreadsheet ID (aka file ID.)
:type file_id: str
:param value: user or group e-mail address, domain name
or None for 'default' type.
:type value: str, None
:param perm_type: (optional) The account type.... | Below is the the instruction that describes the task:
### Input:
Creates a new permission for a file.
:param file_id: a spreadsheet ID (aka file ID.)
:type file_id: str
:param value: user or group e-mail address, domain name
or None for 'default' type.
:type va... |
def write_bus_data(self, file):
""" Writes bus data to a ReST table.
"""
report = CaseReport(self.case)
buses = self.case.buses
col_width = 8
col_width_2 = col_width * 2 + 1
col1_width = 6
sep = "=" * 6 + " " + ("=" * col_width + " ") * 6 + "\n"
... | Writes bus data to a ReST table. | Below is the the instruction that describes the task:
### Input:
Writes bus data to a ReST table.
### Response:
def write_bus_data(self, file):
""" Writes bus data to a ReST table.
"""
report = CaseReport(self.case)
buses = self.case.buses
col_width = 8
col_width_2 ... |
def http_post(self, path, query_data={}, post_data={}, files=None,
**kwargs):
"""Make a POST request to the Gitlab server.
Args:
path (str): Path or full URL to query ('/projects' or
'http://whatever/v4/api/projecs')
query_data (dict): D... | Make a POST request to the Gitlab server.
Args:
path (str): Path or full URL to query ('/projects' or
'http://whatever/v4/api/projecs')
query_data (dict): Data to send as query parameters
post_data (dict): Data to send in the body (will be converted t... | Below is the the instruction that describes the task:
### Input:
Make a POST request to the Gitlab server.
Args:
path (str): Path or full URL to query ('/projects' or
'http://whatever/v4/api/projecs')
query_data (dict): Data to send as query parameters
... |
def apply(self, configuration, schema, args):
"""
Apply the plugin to the configuration.
Inheriting plugins should implement this method to add additional functionality.
Parameters
----------
configuration : dict
configuration
schema : dict
... | Apply the plugin to the configuration.
Inheriting plugins should implement this method to add additional functionality.
Parameters
----------
configuration : dict
configuration
schema : dict
JSON schema
args : argparse.NameSpace
parse... | Below is the the instruction that describes the task:
### Input:
Apply the plugin to the configuration.
Inheriting plugins should implement this method to add additional functionality.
Parameters
----------
configuration : dict
configuration
schema : dict
... |
def chunkify(iterable, chunksize):
"""
Splits an iterable into chunks of size ``chunksize``. The last chunk may be smaller than ``chunksize``.
"""
from .queryset import QuerySet
if hasattr(iterable, '__getitem__') and not isinstance(iterable, QuerySet):
# tuple, list. QuerySet has __getitem_... | Splits an iterable into chunks of size ``chunksize``. The last chunk may be smaller than ``chunksize``. | Below is the the instruction that describes the task:
### Input:
Splits an iterable into chunks of size ``chunksize``. The last chunk may be smaller than ``chunksize``.
### Response:
def chunkify(iterable, chunksize):
"""
Splits an iterable into chunks of size ``chunksize``. The last chunk may be smaller t... |
def find_hosts_that_use_template(self, tpl_name):
"""Find hosts that use the template defined in argument tpl_name
:param tpl_name: the template name we filter or
:type tpl_name: str
:return: list of the host_name of the hosts that got the template tpl_name in tags
:rtype: list[... | Find hosts that use the template defined in argument tpl_name
:param tpl_name: the template name we filter or
:type tpl_name: str
:return: list of the host_name of the hosts that got the template tpl_name in tags
:rtype: list[str] | Below is the the instruction that describes the task:
### Input:
Find hosts that use the template defined in argument tpl_name
:param tpl_name: the template name we filter or
:type tpl_name: str
:return: list of the host_name of the hosts that got the template tpl_name in tags
:rtyp... |
def _execute(self, connection, query, fetch=True):
""" Executes given query using given connection.
Args:
connection (apsw.Connection): connection to the sqlite db who stores mpr data.
query (str): sql query
fetch (boolean, optional): if True, fetch query result and ... | Executes given query using given connection.
Args:
connection (apsw.Connection): connection to the sqlite db who stores mpr data.
query (str): sql query
fetch (boolean, optional): if True, fetch query result and return it. If False, do not fetch.
Returns:
... | Below is the the instruction that describes the task:
### Input:
Executes given query using given connection.
Args:
connection (apsw.Connection): connection to the sqlite db who stores mpr data.
query (str): sql query
fetch (boolean, optional): if True, fetch query resul... |
def screenshot(self, viewID, filename):
"""screenshot(string, string) -> None
Save a screenshot for the given view to the given filename.
The fileformat is guessed from the extension, the available
formats differ from platform to platform but should at least
include ps, svg and ... | screenshot(string, string) -> None
Save a screenshot for the given view to the given filename.
The fileformat is guessed from the extension, the available
formats differ from platform to platform but should at least
include ps, svg and pdf, on linux probably gif, png and jpg as well. | Below is the the instruction that describes the task:
### Input:
screenshot(string, string) -> None
Save a screenshot for the given view to the given filename.
The fileformat is guessed from the extension, the available
formats differ from platform to platform but should at least
in... |
def get_period_seconds(period):
"""
return the number of seconds in the specified period
>>> get_period_seconds('day')
86400
>>> get_period_seconds(86400)
86400
>>> get_period_seconds(datetime.timedelta(hours=24))
86400
>>> get_period_seconds('day + os.system("rm -Rf *")')
Traceback (most recent call last):
... | return the number of seconds in the specified period
>>> get_period_seconds('day')
86400
>>> get_period_seconds(86400)
86400
>>> get_period_seconds(datetime.timedelta(hours=24))
86400
>>> get_period_seconds('day + os.system("rm -Rf *")')
Traceback (most recent call last):
...
ValueError: period not in (secon... | Below is the the instruction that describes the task:
### Input:
return the number of seconds in the specified period
>>> get_period_seconds('day')
86400
>>> get_period_seconds(86400)
86400
>>> get_period_seconds(datetime.timedelta(hours=24))
86400
>>> get_period_seconds('day + os.system("rm -Rf *")')
Trac... |
def parse_json_feed_bytes(data: bytes) -> JSONFeed:
"""Parse a JSON feed from a byte-string containing JSON data."""
try:
root = json.loads(data)
except json.decoder.JSONDecodeError:
raise FeedJSONError('Not a valid JSON document')
return parse_json_feed(root) | Parse a JSON feed from a byte-string containing JSON data. | Below is the the instruction that describes the task:
### Input:
Parse a JSON feed from a byte-string containing JSON data.
### Response:
def parse_json_feed_bytes(data: bytes) -> JSONFeed:
"""Parse a JSON feed from a byte-string containing JSON data."""
try:
root = json.loads(data)
except json... |
def receive_trial_result(self, parameter_id, parameters, value):
"""Tuner receive result from trial.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
"""
value = extr... | Tuner receive result from trial.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key. | Below is the the instruction that describes the task:
### Input:
Tuner receive result from trial.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
### Response:
def receive_trial_result... |
def get_config(self, config_filename):
"""
Collection all config file in all available apps, and merge them into ini object
:return: ini object
"""
x = pyini.Ini(lazy=True, basepath=os.path.join(self.project_dir, 'apps'))
for p in reversed(self.apps):
app_path... | Collection all config file in all available apps, and merge them into ini object
:return: ini object | Below is the the instruction that describes the task:
### Input:
Collection all config file in all available apps, and merge them into ini object
:return: ini object
### Response:
def get_config(self, config_filename):
"""
Collection all config file in all available apps, and merge them int... |
def parse_opml_bytes(data: bytes) -> OPML:
"""Parse an OPML document from a byte-string containing XML data."""
root = parse_xml(BytesIO(data)).getroot()
return _parse_opml(root) | Parse an OPML document from a byte-string containing XML data. | Below is the the instruction that describes the task:
### Input:
Parse an OPML document from a byte-string containing XML data.
### Response:
def parse_opml_bytes(data: bytes) -> OPML:
"""Parse an OPML document from a byte-string containing XML data."""
root = parse_xml(BytesIO(data)).getroot()
return ... |
def transformer_ffn_layer(x,
hparams,
pad_remover=None,
conv_padding="LEFT",
nonpadding_mask=None,
losses=None,
cache=None,
decode_loop_st... | Feed-forward layer in the transformer.
Args:
x: a Tensor of shape [batch_size, length, hparams.hidden_size]
hparams: hyperparameters for model
pad_remover: an expert_utils.PadRemover object tracking the padding
positions. If provided, when using convolutional settings, the padding
is removed ... | Below is the the instruction that describes the task:
### Input:
Feed-forward layer in the transformer.
Args:
x: a Tensor of shape [batch_size, length, hparams.hidden_size]
hparams: hyperparameters for model
pad_remover: an expert_utils.PadRemover object tracking the padding
positions. If provi... |
def is_changed(self, start, end):
"""Tell whether any of start till end lines have changed
The end points are inclusive and indices start from 1.
"""
left, right = self._get_changed(start, end)
if left < right:
return True
return False | Tell whether any of start till end lines have changed
The end points are inclusive and indices start from 1. | Below is the the instruction that describes the task:
### Input:
Tell whether any of start till end lines have changed
The end points are inclusive and indices start from 1.
### Response:
def is_changed(self, start, end):
"""Tell whether any of start till end lines have changed
The end po... |
def get_best_fit_parameters_translated_grouped(self):
"""Returns the parameters as a dictionary of the 'real units' for the best fit."""
result_dict = dict()
result_dict['ocv'] = [parameters['ocv'] for parameters in
self.best_fit_parameters_translated]
resul... | Returns the parameters as a dictionary of the 'real units' for the best fit. | Below is the the instruction that describes the task:
### Input:
Returns the parameters as a dictionary of the 'real units' for the best fit.
### Response:
def get_best_fit_parameters_translated_grouped(self):
"""Returns the parameters as a dictionary of the 'real units' for the best fit."""
result... |
def to_dict(self):
"""Convert this object into a dictionary.
Returns:
dict: A dict with the same information as this object.
"""
out_dict = {}
out_dict['commands'] = self.commands
out_dict['configs'] = self.configs
out_dict['short_name'] = self.name... | Convert this object into a dictionary.
Returns:
dict: A dict with the same information as this object. | Below is the the instruction that describes the task:
### Input:
Convert this object into a dictionary.
Returns:
dict: A dict with the same information as this object.
### Response:
def to_dict(self):
"""Convert this object into a dictionary.
Returns:
dict: A dict ... |
def powerset(iterable):
"""Calculate the powerset of any iterable.
For a range of integers up to the length of the given list,
make all possible combinations and chain them together as one object.
From https://docs.python.org/3/library/itertools.html#itertools-recipes
"""
"list(powerset([1,2,3]... | Calculate the powerset of any iterable.
For a range of integers up to the length of the given list,
make all possible combinations and chain them together as one object.
From https://docs.python.org/3/library/itertools.html#itertools-recipes | Below is the the instruction that describes the task:
### Input:
Calculate the powerset of any iterable.
For a range of integers up to the length of the given list,
make all possible combinations and chain them together as one object.
From https://docs.python.org/3/library/itertools.html#itertools-reci... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | Below is the the instruction that describes the task:
### Input:
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
### Response:
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :m... |
def update_state_changes(self, state_changes_data: List[Tuple[str, int]]) -> None:
"""Given a list of identifier/data state tuples update them in the DB"""
cursor = self.conn.cursor()
cursor.executemany(
'UPDATE state_changes SET data=? WHERE identifier=?',
state_changes_... | Given a list of identifier/data state tuples update them in the DB | Below is the the instruction that describes the task:
### Input:
Given a list of identifier/data state tuples update them in the DB
### Response:
def update_state_changes(self, state_changes_data: List[Tuple[str, int]]) -> None:
"""Given a list of identifier/data state tuples update them in the DB"""
... |
def get_form_errors(form):
"""
Django form errors do not obey natural field order,
this template tag returns non-field and field-specific errors
:param form: the form instance
"""
return {
'non_field': form.non_field_errors(),
'field_specific': OrderedDict(
(field, fo... | Django form errors do not obey natural field order,
this template tag returns non-field and field-specific errors
:param form: the form instance | Below is the the instruction that describes the task:
### Input:
Django form errors do not obey natural field order,
this template tag returns non-field and field-specific errors
:param form: the form instance
### Response:
def get_form_errors(form):
"""
Django form errors do not obey natural field... |
def target_query(plugin, port, location):
"""
prepared ReQL for target
"""
return ((r.row[PLUGIN_NAME_KEY] == plugin) &
(r.row[PORT_FIELD] == port) &
(r.row[LOCATION_FIELD] == location)) | prepared ReQL for target | Below is the the instruction that describes the task:
### Input:
prepared ReQL for target
### Response:
def target_query(plugin, port, location):
"""
prepared ReQL for target
"""
return ((r.row[PLUGIN_NAME_KEY] == plugin) &
(r.row[PORT_FIELD] == port) &
(r.row[LOCATION_FIELD... |
def _Open(self, path_spec=None, mode='rb'):
"""Opens the file-like object defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the file-like... | Opens the file-like object defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the file-like object could not be opened.
OSError: if the ... | Below is the the instruction that describes the task:
### Input:
Opens the file-like object defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError... |
def _auto_positive_symbol(tokens, local_dict, global_dict):
"""
Inserts calls to ``Symbol`` for undefined variables.
Passes in positive=True as a keyword argument.
Adapted from sympy.sympy.parsing.sympy_parser.auto_symbol
"""
result = []
tokens.append((None, None)) # so zip traverses all t... | Inserts calls to ``Symbol`` for undefined variables.
Passes in positive=True as a keyword argument.
Adapted from sympy.sympy.parsing.sympy_parser.auto_symbol | Below is the the instruction that describes the task:
### Input:
Inserts calls to ``Symbol`` for undefined variables.
Passes in positive=True as a keyword argument.
Adapted from sympy.sympy.parsing.sympy_parser.auto_symbol
### Response:
def _auto_positive_symbol(tokens, local_dict, global_dict):
"""
... |
def normalize_to_range(
values,
minimum = 0.0,
maximum = 1.0
):
"""
This function normalizes values of a list to a specified range and returns
the original object if the values are not of the types integer or float.
"""
normalized_values = []
minimum_value = min(values)
max... | This function normalizes values of a list to a specified range and returns
the original object if the values are not of the types integer or float. | Below is the the instruction that describes the task:
### Input:
This function normalizes values of a list to a specified range and returns
the original object if the values are not of the types integer or float.
### Response:
def normalize_to_range(
values,
minimum = 0.0,
maximum = 1.0
):
... |
def _parse(self):
'''parse is the base function for parsing the Dockerfile, and extracting
elements into the correct data structures. Everything is parsed into
lists or dictionaries that can be assembled again on demand.
Environment: Since Docker also exports environment as we... | parse is the base function for parsing the Dockerfile, and extracting
elements into the correct data structures. Everything is parsed into
lists or dictionaries that can be assembled again on demand.
Environment: Since Docker also exports environment as we go,
... | Below is the the instruction that describes the task:
### Input:
parse is the base function for parsing the Dockerfile, and extracting
elements into the correct data structures. Everything is parsed into
lists or dictionaries that can be assembled again on demand.
Environment: Sin... |
def share_file(comm, path):
"""
Copies the file from rank 0 to all other ranks
Puts it in the same place on all machines
"""
localrank, _ = get_local_rank_size(comm)
if comm.Get_rank() == 0:
with open(path, 'rb') as fh:
data = fh.read()
comm.bcast(data)
else:
... | Copies the file from rank 0 to all other ranks
Puts it in the same place on all machines | Below is the the instruction that describes the task:
### Input:
Copies the file from rank 0 to all other ranks
Puts it in the same place on all machines
### Response:
def share_file(comm, path):
"""
Copies the file from rank 0 to all other ranks
Puts it in the same place on all machines
"""
... |
def update_model_cache(table_name):
"""
Updates model cache by generating a new key for the model
"""
model_cache_info = ModelCacheInfo(table_name, uuid.uuid4().hex)
model_cache_backend.share_model_cache_info(model_cache_info) | Updates model cache by generating a new key for the model | Below is the the instruction that describes the task:
### Input:
Updates model cache by generating a new key for the model
### Response:
def update_model_cache(table_name):
"""
Updates model cache by generating a new key for the model
"""
model_cache_info = ModelCacheInfo(table_name, uuid.uuid4().h... |
def plot(self, series, series_diff=None, label='', color=None, style=None):
'''
:param pandas.Series series:
The series to be plotted, all values must be positive if stacked
is True.
:param pandas.Series series_diff:
The series representing the diff that will ... | :param pandas.Series series:
The series to be plotted, all values must be positive if stacked
is True.
:param pandas.Series series_diff:
The series representing the diff that will be plotted in the
bottom part.
:param string label:
The label fo... | Below is the the instruction that describes the task:
### Input:
:param pandas.Series series:
The series to be plotted, all values must be positive if stacked
is True.
:param pandas.Series series_diff:
The series representing the diff that will be plotted in the
... |
def apply_cmap(zs, cmap, vmin=None, vmax=None):
'''
apply_cmap(z, cmap) applies the given cmap to the values in z; if vmin and/or vmad are passed,
they are used to scale z.
'''
if vmin is None: vmin = np.min(zs)
if vmax is None: vmax = np.max(zs)
if pimms.is_str(cmap): cmap = matplotlib.cm... | apply_cmap(z, cmap) applies the given cmap to the values in z; if vmin and/or vmad are passed,
they are used to scale z. | Below is the the instruction that describes the task:
### Input:
apply_cmap(z, cmap) applies the given cmap to the values in z; if vmin and/or vmad are passed,
they are used to scale z.
### Response:
def apply_cmap(zs, cmap, vmin=None, vmax=None):
'''
apply_cmap(z, cmap) applies the given cmap to the... |
def add_log_file(logger, log_file, global_log_file=False):
"""
Add a log file to this logger. If global_log_file is true, log_file will be handed the root logger, otherwise it will only be used by this particular logger.
Parameters
----------
logger :obj:`logging.Logger`
... | Add a log file to this logger. If global_log_file is true, log_file will be handed the root logger, otherwise it will only be used by this particular logger.
Parameters
----------
logger :obj:`logging.Logger`
The logger.
log_file :obj:`str`
The path to the log fi... | Below is the the instruction that describes the task:
### Input:
Add a log file to this logger. If global_log_file is true, log_file will be handed the root logger, otherwise it will only be used by this particular logger.
Parameters
----------
logger :obj:`logging.Logger`
The l... |
def run_hooks(self, name, event=None, context=None):
"""
Runs plugin hooks for each registered plugin.
"""
hooks = {
"pre:setup": lambda p: p.pre_setup(self),
"post:setup": lambda p: p.post_setup(self),
"pre:invoke": lambda p: p.pre_invoke(event, conte... | Runs plugin hooks for each registered plugin. | Below is the the instruction that describes the task:
### Input:
Runs plugin hooks for each registered plugin.
### Response:
def run_hooks(self, name, event=None, context=None):
"""
Runs plugin hooks for each registered plugin.
"""
hooks = {
"pre:setup": lambda p: p.pre_... |
def get_next_rngruns(self):
"""
Yield the next RngRun values that can be used in this campaign.
"""
available_runs = [result['params']['RngRun'] for result in
self.get_results()]
yield from DatabaseManager.get_next_values(available_runs) | Yield the next RngRun values that can be used in this campaign. | Below is the the instruction that describes the task:
### Input:
Yield the next RngRun values that can be used in this campaign.
### Response:
def get_next_rngruns(self):
"""
Yield the next RngRun values that can be used in this campaign.
"""
available_runs = [result['params']['RngR... |
def _set_vlan_and_bd(self, v, load=False):
"""
Setter method for vlan_and_bd, mapped from YANG variable /overlay_gateway/map/vlan_and_bd (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlan_and_bd is considered as a private
method. Backends looking to pop... | Setter method for vlan_and_bd, mapped from YANG variable /overlay_gateway/map/vlan_and_bd (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlan_and_bd is considered as a private
method. Backends looking to populate this variable should
do so via calling thisOb... | Below is the the instruction that describes the task:
### Input:
Setter method for vlan_and_bd, mapped from YANG variable /overlay_gateway/map/vlan_and_bd (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlan_and_bd is considered as a private
method. Backends ... |
def _cleanRecursive(self, subSelf):
"""
Delete all NestedOrderedDict that haven't any entries.
"""
for key, item in list(subSelf.items()):
if self.isNestedDict(item):
if not item:
subSelf.pop(key)
else:
s... | Delete all NestedOrderedDict that haven't any entries. | Below is the the instruction that describes the task:
### Input:
Delete all NestedOrderedDict that haven't any entries.
### Response:
def _cleanRecursive(self, subSelf):
"""
Delete all NestedOrderedDict that haven't any entries.
"""
for key, item in list(subSelf.items()):
... |
def resize_pty(self, width=80, height=24):
"""
Resize the pseudo-terminal. This can be used to change the width and
height of the terminal emulation created in a previous L{get_pty} call.
@param width: new width (in characters) of the terminal screen
@type width: int
@p... | Resize the pseudo-terminal. This can be used to change the width and
height of the terminal emulation created in a previous L{get_pty} call.
@param width: new width (in characters) of the terminal screen
@type width: int
@param height: new height (in characters) of the terminal screen
... | Below is the the instruction that describes the task:
### Input:
Resize the pseudo-terminal. This can be used to change the width and
height of the terminal emulation created in a previous L{get_pty} call.
@param width: new width (in characters) of the terminal screen
@type width: int
... |
def region_est_hull(self, level=0.95, modelparam_slice=None):
"""
Estimates a credible region over models by taking the convex hull of
a credible subset of particles.
:param float level: The desired crediblity level (see
:meth:`SMCUpdater.est_credible_region`).
:para... | Estimates a credible region over models by taking the convex hull of
a credible subset of particles.
:param float level: The desired crediblity level (see
:meth:`SMCUpdater.est_credible_region`).
:param slice modelparam_slice: Slice over which model parameters
to conside... | Below is the the instruction that describes the task:
### Input:
Estimates a credible region over models by taking the convex hull of
a credible subset of particles.
:param float level: The desired crediblity level (see
:meth:`SMCUpdater.est_credible_region`).
:param slice model... |
def _split_path(xj_path):
"""Extract the last piece of XJPath.
:param str xj_path: A XJPath expression.
:rtype: tuple[str|None, str]
:return: A tuple where first element is a root XJPath and the second is
a last piece of key.
"""
res = xj_path.rsplit('.', 1)
root_key = res[0]
... | Extract the last piece of XJPath.
:param str xj_path: A XJPath expression.
:rtype: tuple[str|None, str]
:return: A tuple where first element is a root XJPath and the second is
a last piece of key. | Below is the the instruction that describes the task:
### Input:
Extract the last piece of XJPath.
:param str xj_path: A XJPath expression.
:rtype: tuple[str|None, str]
:return: A tuple where first element is a root XJPath and the second is
a last piece of key.
### Response:
def _split_pa... |
def _configure_pool(kwargs):
"""Configures the pool and keeps the storage service"""
_pool_single_run.storage_service = kwargs['storage_service']
_configure_niceness(kwargs)
_configure_logging(kwargs, extract=False) | Configures the pool and keeps the storage service | Below is the the instruction that describes the task:
### Input:
Configures the pool and keeps the storage service
### Response:
def _configure_pool(kwargs):
"""Configures the pool and keeps the storage service"""
_pool_single_run.storage_service = kwargs['storage_service']
_configure_niceness(kwargs)
... |
def _numeric_coercion(value,
coercion_function = None,
allow_empty = False,
minimum = None,
maximum = None):
"""Validate that ``value`` is numeric and coerce using ``coercion_function``.
:param value: The value to validate.... | Validate that ``value`` is numeric and coerce using ``coercion_function``.
:param value: The value to validate.
:param coercion_function: The function to use to coerce ``value`` to the desired
type.
:type coercion_function: callable
:param allow_empty: If ``True``, returns :obj:`None <python:No... | Below is the the instruction that describes the task:
### Input:
Validate that ``value`` is numeric and coerce using ``coercion_function``.
:param value: The value to validate.
:param coercion_function: The function to use to coerce ``value`` to the desired
type.
:type coercion_function: callabl... |
def removeUnreferencedIDs(referencedIDs, identifiedElements):
"""
Removes the unreferenced ID attributes.
Returns the number of ID attributes removed
"""
global _num_ids_removed
keepTags = ['font']
num = 0
for id in identifiedElements:
node = identifiedElements[id]
if id... | Removes the unreferenced ID attributes.
Returns the number of ID attributes removed | Below is the the instruction that describes the task:
### Input:
Removes the unreferenced ID attributes.
Returns the number of ID attributes removed
### Response:
def removeUnreferencedIDs(referencedIDs, identifiedElements):
"""
Removes the unreferenced ID attributes.
Returns the number of ID att... |
def _load(self):
"""
Function load.
:return: file contents
:raises: NotFoundError if file not found
"""
if self.is_exists():
return open(self._ref, "rb").read()
raise NotFoundError("File %s not found" % self._ref) | Function load.
:return: file contents
:raises: NotFoundError if file not found | Below is the the instruction that describes the task:
### Input:
Function load.
:return: file contents
:raises: NotFoundError if file not found
### Response:
def _load(self):
"""
Function load.
:return: file contents
:raises: NotFoundError if file not found
... |
def do_your_job(self):
"""
the goal of the explore agent is to move to the
target while avoiding blockages on the grid.
This function is messy and needs to be looked at.
It currently has a bug in that the backtrack oscillates
so need a new method of doing this - probably... | the goal of the explore agent is to move to the
target while avoiding blockages on the grid.
This function is messy and needs to be looked at.
It currently has a bug in that the backtrack oscillates
so need a new method of doing this - probably checking if
previously backtracked... | Below is the the instruction that describes the task:
### Input:
the goal of the explore agent is to move to the
target while avoiding blockages on the grid.
This function is messy and needs to be looked at.
It currently has a bug in that the backtrack oscillates
so need a new metho... |
def delete_payment_card_by_id(cls, payment_card_id, **kwargs):
"""Delete PaymentCard
Delete an instance of PaymentCard by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_payment... | Delete PaymentCard
Delete an instance of PaymentCard by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_payment_card_by_id(payment_card_id, async=True)
>>> result = thread.get()... | Below is the the instruction that describes the task:
### Input:
Delete PaymentCard
Delete an instance of PaymentCard by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_payment_card... |
def set_account_username(self, account, old_username, new_username):
""" Account's username was changed. """
self._delete_account(account, old_username)
self._save_account(account, new_username) | Account's username was changed. | Below is the the instruction that describes the task:
### Input:
Account's username was changed.
### Response:
def set_account_username(self, account, old_username, new_username):
""" Account's username was changed. """
self._delete_account(account, old_username)
self._save_account(account,... |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
options = super(Fil... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
### Response:
def fi... |
def fix_path(path):
"""
Fix windows path's. Linux path's will remain unaltered
:param str path: The path to be fixed
:return: The fixed path
:rtype: str
"""
if '\\' in path:
path = path.replace('\\', '/')
path = os.path.normpath(path)
return path | Fix windows path's. Linux path's will remain unaltered
:param str path: The path to be fixed
:return: The fixed path
:rtype: str | Below is the the instruction that describes the task:
### Input:
Fix windows path's. Linux path's will remain unaltered
:param str path: The path to be fixed
:return: The fixed path
:rtype: str
### Response:
def fix_path(path):
"""
Fix windows path's. Linux path's will remain unaltered
:p... |
def getPluginActions(self, index):
"""Return actions from plug-in at `index`
Arguments:
index (int): Index at which item is located in model
"""
index = self.data["proxies"]["plugin"].mapToSource(
self.data["proxies"]["plugin"].index(
index, 0, ... | Return actions from plug-in at `index`
Arguments:
index (int): Index at which item is located in model | Below is the the instruction that describes the task:
### Input:
Return actions from plug-in at `index`
Arguments:
index (int): Index at which item is located in model
### Response:
def getPluginActions(self, index):
"""Return actions from plug-in at `index`
Arguments:
... |
def transitivity_wu(W):
'''
Transitivity is the ratio of 'triangles to triplets' in the network.
(A classical version of the clustering coefficient).
Parameters
----------
W : NxN np.ndarray
weighted undirected connection matrix
Returns
-------
T : int
transitivity ... | Transitivity is the ratio of 'triangles to triplets' in the network.
(A classical version of the clustering coefficient).
Parameters
----------
W : NxN np.ndarray
weighted undirected connection matrix
Returns
-------
T : int
transitivity scalar | Below is the the instruction that describes the task:
### Input:
Transitivity is the ratio of 'triangles to triplets' in the network.
(A classical version of the clustering coefficient).
Parameters
----------
W : NxN np.ndarray
weighted undirected connection matrix
Returns
-------
... |
def pressure_series(self):
"""Returns the atmospheric pressure time series relative to the
meteostation, in the form of a list of tuples, each one containing the
couple timestamp-value
:returns: a list of tuples
"""
return [(tstamp, \
self._station_histor... | Returns the atmospheric pressure time series relative to the
meteostation, in the form of a list of tuples, each one containing the
couple timestamp-value
:returns: a list of tuples | Below is the the instruction that describes the task:
### Input:
Returns the atmospheric pressure time series relative to the
meteostation, in the form of a list of tuples, each one containing the
couple timestamp-value
:returns: a list of tuples
### Response:
def pressure_series(self):
... |
def string_to_datetime(self, obj):
"""
Decode a datetime string to a datetime object
"""
if isinstance(obj, six.string_types) and len(obj) == 19:
try:
return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S")
except ValueError:
pass
... | Decode a datetime string to a datetime object | Below is the the instruction that describes the task:
### Input:
Decode a datetime string to a datetime object
### Response:
def string_to_datetime(self, obj):
"""
Decode a datetime string to a datetime object
"""
if isinstance(obj, six.string_types) and len(obj) == 19:
... |
def union_q(token):
"""
Appends all the Q() objects.
"""
query = Q()
operation = 'and'
negation = False
for t in token:
if type(t) is ParseResults: # See tokens recursively
query &= union_q(t)
else:
if t in ('or', 'and'): # Set the new op and go to ... | Appends all the Q() objects. | Below is the the instruction that describes the task:
### Input:
Appends all the Q() objects.
### Response:
def union_q(token):
"""
Appends all the Q() objects.
"""
query = Q()
operation = 'and'
negation = False
for t in token:
if type(t) is ParseResults: # See tokens recursiv... |
def is_closed(self):
"""
_check if the observation table is closed.
Args:
None
Returns:
tuple (bool, str): True if the observation table is closed and false otherwise.
If the table is not closed the escaping string is returned.
... | _check if the observation table is closed.
Args:
None
Returns:
tuple (bool, str): True if the observation table is closed and false otherwise.
If the table is not closed the escaping string is returned. | Below is the the instruction that describes the task:
### Input:
_check if the observation table is closed.
Args:
None
Returns:
tuple (bool, str): True if the observation table is closed and false otherwise.
If the table is not closed the escapi... |
def add_answer_for_student(student_item, vote, rationale):
"""
Add an answer for a student to the backend
Args:
student_item (dict): The location of the problem this submission is
associated with, as defined by a course, student, and item.
vote (int): the option that student vot... | Add an answer for a student to the backend
Args:
student_item (dict): The location of the problem this submission is
associated with, as defined by a course, student, and item.
vote (int): the option that student voted for
rationale (str): the reason why the student vote for the... | Below is the the instruction that describes the task:
### Input:
Add an answer for a student to the backend
Args:
student_item (dict): The location of the problem this submission is
associated with, as defined by a course, student, and item.
vote (int): the option that student voted... |
def handle_flush_error(cls, exception):
"""Handle flush error exceptions."""
trace = exception.args[0]
m = re.match(cls.MYSQL_FLUSH_ERROR_REGEX, trace)
if not m:
raise exception
entity = m.group('entity')
eid = m.group('eid')
raise AlreadyExistsErr... | Handle flush error exceptions. | Below is the the instruction that describes the task:
### Input:
Handle flush error exceptions.
### Response:
def handle_flush_error(cls, exception):
"""Handle flush error exceptions."""
trace = exception.args[0]
m = re.match(cls.MYSQL_FLUSH_ERROR_REGEX, trace)
if not m:
... |
def _decade_ranges_in_date_range(self, begin_date, end_date):
"""Return a list of decades which is covered by date range."""
begin_dated = begin_date.year / 10
end_dated = end_date.year / 10
decades = []
for d in range(begin_dated, end_dated + 1):
decades.append('{}-{... | Return a list of decades which is covered by date range. | Below is the the instruction that describes the task:
### Input:
Return a list of decades which is covered by date range.
### Response:
def _decade_ranges_in_date_range(self, begin_date, end_date):
"""Return a list of decades which is covered by date range."""
begin_dated = begin_date.year / 10
... |
def cv_precompute(self, mask, b):
'''
Pre-compute the matrices :py:obj:`A` and :py:obj:`B`
(cross-validation step only)
for chunk :py:obj:`b`.
'''
# Get current chunk and mask outliers
m1 = self.get_masked_chunk(b)
flux = self.fraw[m1]
K = GetCov... | Pre-compute the matrices :py:obj:`A` and :py:obj:`B`
(cross-validation step only)
for chunk :py:obj:`b`. | Below is the the instruction that describes the task:
### Input:
Pre-compute the matrices :py:obj:`A` and :py:obj:`B`
(cross-validation step only)
for chunk :py:obj:`b`.
### Response:
def cv_precompute(self, mask, b):
'''
Pre-compute the matrices :py:obj:`A` and :py:obj:`B`
... |
def _get_output_nodes(self, output_path, error_path):
"""
Extracts output nodes from the standard output and standard error
files.
"""
from pymatgen.io.nwchem import NwOutput
from aiida.orm.data.structure import StructureData
from aiida.orm.data.array.trajectory i... | Extracts output nodes from the standard output and standard error
files. | Below is the the instruction that describes the task:
### Input:
Extracts output nodes from the standard output and standard error
files.
### Response:
def _get_output_nodes(self, output_path, error_path):
"""
Extracts output nodes from the standard output and standard error
files.
... |
def Negative(other_param, mode="invert", reroll_count_max=2):
"""
Converts another parameter's results to negative values.
Parameters
----------
other_param : imgaug.parameters.StochasticParameter
Other parameter which's sampled values are to be
modified.
mode : {'invert', 'rer... | Converts another parameter's results to negative values.
Parameters
----------
other_param : imgaug.parameters.StochasticParameter
Other parameter which's sampled values are to be
modified.
mode : {'invert', 'reroll'}, optional
How to change the signs. Valid values are ``invert... | Below is the the instruction that describes the task:
### Input:
Converts another parameter's results to negative values.
Parameters
----------
other_param : imgaug.parameters.StochasticParameter
Other parameter which's sampled values are to be
modified.
mode : {'invert', 'reroll'}... |
def step(self):
# type: () -> bool
"""
Decreases the internal counter. Raises an error if the counter goes
below 0
:return: True if this step was the final one, else False
:raise ValueError: The counter has gone below 0
"""
with self.__lock:
s... | Decreases the internal counter. Raises an error if the counter goes
below 0
:return: True if this step was the final one, else False
:raise ValueError: The counter has gone below 0 | Below is the the instruction that describes the task:
### Input:
Decreases the internal counter. Raises an error if the counter goes
below 0
:return: True if this step was the final one, else False
:raise ValueError: The counter has gone below 0
### Response:
def step(self):
# type... |
def write(self, filename):
"""Save detx file."""
with open(filename, 'w') as f:
f.write(self.ascii)
self.print("Detector file saved as '{0}'".format(filename)) | Save detx file. | Below is the the instruction that describes the task:
### Input:
Save detx file.
### Response:
def write(self, filename):
"""Save detx file."""
with open(filename, 'w') as f:
f.write(self.ascii)
self.print("Detector file saved as '{0}'".format(filename)) |
def follower_ids(self, user):
"""
Returns Twitter user id lists for the specified user's followers.
A user can be a specific using their screen_name or user_id
"""
user = str(user)
user = user.lstrip('@')
url = 'https://api.twitter.com/1.1/followers/ids.json'
... | Returns Twitter user id lists for the specified user's followers.
A user can be a specific using their screen_name or user_id | Below is the the instruction that describes the task:
### Input:
Returns Twitter user id lists for the specified user's followers.
A user can be a specific using their screen_name or user_id
### Response:
def follower_ids(self, user):
"""
Returns Twitter user id lists for the specified user... |
def main():
"""Create an organization, print out its attributes and delete it."""
org = Organization(name='junk org').create()
pprint(org.get_values()) # e.g. {'name': 'junk org', …}
org.delete() | Create an organization, print out its attributes and delete it. | Below is the the instruction that describes the task:
### Input:
Create an organization, print out its attributes and delete it.
### Response:
def main():
"""Create an organization, print out its attributes and delete it."""
org = Organization(name='junk org').create()
pprint(org.get_values()) # e.g. ... |
def from_pdb(cls, path, forcefield=None, loader=PDBFile, strict=True, **kwargs):
"""
Loads topology, positions and, potentially, velocities and vectors,
from a PDB or PDBx file
Parameters
----------
path : str
Path to PDB/PDBx file
forcefields : list ... | Loads topology, positions and, potentially, velocities and vectors,
from a PDB or PDBx file
Parameters
----------
path : str
Path to PDB/PDBx file
forcefields : list of str
Paths to FFXML and/or FRCMOD forcefields. REQUIRED.
Returns
-----... | Below is the the instruction that describes the task:
### Input:
Loads topology, positions and, potentially, velocities and vectors,
from a PDB or PDBx file
Parameters
----------
path : str
Path to PDB/PDBx file
forcefields : list of str
Paths to FFXM... |
def normalize_scientific_notation(s, ignore_commas=True, verbosity=1):
"""Produce a string convertable with float(s), if possible, fixing some common scientific notations
Deletes commas and allows addition.
>>> normalize_scientific_notation(' -123 x 10^-45 ')
'-123e-45'
>>> normalize_scientific_not... | Produce a string convertable with float(s), if possible, fixing some common scientific notations
Deletes commas and allows addition.
>>> normalize_scientific_notation(' -123 x 10^-45 ')
'-123e-45'
>>> normalize_scientific_notation(' -1+1,234 x 10^-5,678 ')
'1233e-5678'
>>> normalize_scientific_... | Below is the the instruction that describes the task:
### Input:
Produce a string convertable with float(s), if possible, fixing some common scientific notations
Deletes commas and allows addition.
>>> normalize_scientific_notation(' -123 x 10^-45 ')
'-123e-45'
>>> normalize_scientific_notation(' -... |
def mutable(function):
'''Add the instance internal state as the second parameter
of the decorated function.'''
def wrapper(self, *args, **kwargs):
state = self._get_state()
return function(self, state, *args, **kwargs)
return wrapper | Add the instance internal state as the second parameter
of the decorated function. | Below is the the instruction that describes the task:
### Input:
Add the instance internal state as the second parameter
of the decorated function.
### Response:
def mutable(function):
'''Add the instance internal state as the second parameter
of the decorated function.'''
def wrapper(self, *args,... |
def dict_to_serialized_dict(ref, the_dict):
"""Serialize the list of elements to a dictionary
Used for the retention store
:param ref: Not used
:type ref:
:param the_dict: dictionary to convert
:type the_dict: dict
:return: dict of serialized
:rtype: dict
"""
result = {}
fo... | Serialize the list of elements to a dictionary
Used for the retention store
:param ref: Not used
:type ref:
:param the_dict: dictionary to convert
:type the_dict: dict
:return: dict of serialized
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Serialize the list of elements to a dictionary
Used for the retention store
:param ref: Not used
:type ref:
:param the_dict: dictionary to convert
:type the_dict: dict
:return: dict of serialized
:rtype: dict
### Response... |
def loads(cls, pickle_string):
"""
Equivalent to pickle.loads except that the HoloViews trees is
restored appropriately.
"""
cls.load_counter_offset = StoreOptions.id_offset()
val = pickle.loads(pickle_string)
cls.load_counter_offset = None
return val | Equivalent to pickle.loads except that the HoloViews trees is
restored appropriately. | Below is the the instruction that describes the task:
### Input:
Equivalent to pickle.loads except that the HoloViews trees is
restored appropriately.
### Response:
def loads(cls, pickle_string):
"""
Equivalent to pickle.loads except that the HoloViews trees is
restored appropriatel... |
def start(self, request: Request) -> Response:
'''Start a file or directory listing download.
Args:
request: Request.
Returns:
A Response populated with the initial data connection reply.
Once the response is received, call :meth:`download`.
Coroutine.... | Start a file or directory listing download.
Args:
request: Request.
Returns:
A Response populated with the initial data connection reply.
Once the response is received, call :meth:`download`.
Coroutine. | Below is the the instruction that describes the task:
### Input:
Start a file or directory listing download.
Args:
request: Request.
Returns:
A Response populated with the initial data connection reply.
Once the response is received, call :meth:`download`.
... |
def _parse_status(self, status):
"""Parses the house's state description and applies the corresponding values
Parameters
----------
status: :class:`str`
Plain text string containing the current renting state of the house.
"""
m = rented_regex.search(status)
... | Parses the house's state description and applies the corresponding values
Parameters
----------
status: :class:`str`
Plain text string containing the current renting state of the house. | Below is the the instruction that describes the task:
### Input:
Parses the house's state description and applies the corresponding values
Parameters
----------
status: :class:`str`
Plain text string containing the current renting state of the house.
### Response:
def _parse_st... |
def getmembers_runtime(self):
"""Gets members (vars) from all scopes using ONLY runtime information.
You most likely want to use ScopeStack.getmembers instead.
Returns:
Set of available vars.
Raises:
NotImplementedError if any scope fails to implement 'getmembe... | Gets members (vars) from all scopes using ONLY runtime information.
You most likely want to use ScopeStack.getmembers instead.
Returns:
Set of available vars.
Raises:
NotImplementedError if any scope fails to implement 'getmembers'. | Below is the the instruction that describes the task:
### Input:
Gets members (vars) from all scopes using ONLY runtime information.
You most likely want to use ScopeStack.getmembers instead.
Returns:
Set of available vars.
Raises:
NotImplementedError if any scope ... |
def findAttr(self, svgNode, name):
"""Search an attribute with some name in some node or above.
First the node is searched, then its style attribute, then
the search continues in the node's parent node. If no such
attribute is found, '' is returned.
"""
# This needs als... | Search an attribute with some name in some node or above.
First the node is searched, then its style attribute, then
the search continues in the node's parent node. If no such
attribute is found, '' is returned. | Below is the the instruction that describes the task:
### Input:
Search an attribute with some name in some node or above.
First the node is searched, then its style attribute, then
the search continues in the node's parent node. If no such
attribute is found, '' is returned.
### Response: ... |
def _consolidate_elemental_array_(elemental_array):
"""
Accounts for non-empirical chemical formulas by taking in the compositional array generated by _create_compositional_array_() and returning a consolidated array of dictionaries with no repeating elements
:param elemental_array: an elemental array gene... | Accounts for non-empirical chemical formulas by taking in the compositional array generated by _create_compositional_array_() and returning a consolidated array of dictionaries with no repeating elements
:param elemental_array: an elemental array generated from _create_compositional_array_()
:return: an array ... | Below is the the instruction that describes the task:
### Input:
Accounts for non-empirical chemical formulas by taking in the compositional array generated by _create_compositional_array_() and returning a consolidated array of dictionaries with no repeating elements
:param elemental_array: an elemental array... |
def parse_annotation(obj: dict) -> BioCAnnotation:
"""Deserialize a dict obj to a BioCAnnotation object"""
ann = BioCAnnotation()
ann.id = obj['id']
ann.infons = obj['infons']
ann.text = obj['text']
for loc in obj['locations']:
ann.add_location(BioCLocation(loc['offset'], loc['len... | Deserialize a dict obj to a BioCAnnotation object | Below is the the instruction that describes the task:
### Input:
Deserialize a dict obj to a BioCAnnotation object
### Response:
def parse_annotation(obj: dict) -> BioCAnnotation:
"""Deserialize a dict obj to a BioCAnnotation object"""
ann = BioCAnnotation()
ann.id = obj['id']
ann.infons = obj[... |
def update_experiments(self):
"""Experiment mapping."""
# 693 Remove if 'not applicable'
for field in record_get_field_instances(self.record, '693'):
subs = field_get_subfields(field)
acc_experiment = subs.get("e", [])
if not acc_experiment:
ac... | Experiment mapping. | Below is the the instruction that describes the task:
### Input:
Experiment mapping.
### Response:
def update_experiments(self):
"""Experiment mapping."""
# 693 Remove if 'not applicable'
for field in record_get_field_instances(self.record, '693'):
subs = field_get_subfields(fie... |
def lines(self):
"""
:return: list containing lines (unicode) from Dockerfile
"""
if self.cache_content and self.cached_content:
return self.cached_content.splitlines(True)
try:
with self._open_dockerfile('rb') as dockerfile:
lines = [b2u(... | :return: list containing lines (unicode) from Dockerfile | Below is the the instruction that describes the task:
### Input:
:return: list containing lines (unicode) from Dockerfile
### Response:
def lines(self):
"""
:return: list containing lines (unicode) from Dockerfile
"""
if self.cache_content and self.cached_content:
return... |
def set_chat_description(self, *args, **kwargs):
"""See :func:`set_chat_description`"""
return set_chat_description(*args, **self._merge_overrides(**kwargs)).run() | See :func:`set_chat_description` | Below is the the instruction that describes the task:
### Input:
See :func:`set_chat_description`
### Response:
def set_chat_description(self, *args, **kwargs):
"""See :func:`set_chat_description`"""
return set_chat_description(*args, **self._merge_overrides(**kwargs)).run() |
def dispatch(self, request, environ):
"""
Checks which Grant supports the current request and dispatches to it.
:param request: The incoming request.
:type request: :class:`oauth2.web.Request`
:param environ: Dict containing variables of the environment.
:type environ: d... | Checks which Grant supports the current request and dispatches to it.
:param request: The incoming request.
:type request: :class:`oauth2.web.Request`
:param environ: Dict containing variables of the environment.
:type environ: dict
:return: An instance of ``oauth2.web.Response... | Below is the the instruction that describes the task:
### Input:
Checks which Grant supports the current request and dispatches to it.
:param request: The incoming request.
:type request: :class:`oauth2.web.Request`
:param environ: Dict containing variables of the environment.
:type... |
def get_position(self):
''' Read chuck position (x, y, z)'''
reply = self._intf.query('ReadChuckPosition Y H')[2:]
return [float(i) for i in reply.split()] | Read chuck position (x, y, z) | Below is the the instruction that describes the task:
### Input:
Read chuck position (x, y, z)
### Response:
def get_position(self):
''' Read chuck position (x, y, z)'''
reply = self._intf.query('ReadChuckPosition Y H')[2:]
return [float(i) for i in reply.split()] |
def get_connections(app):
"""
Return all Heroku Connect connections setup with the given application.
For more details check the link -
https://devcenter.heroku.com/articles/heroku-connect-api#step-4-retrieve-the-new-connection-s-id
Sample response from the API call is below::
{
... | Return all Heroku Connect connections setup with the given application.
For more details check the link -
https://devcenter.heroku.com/articles/heroku-connect-api#step-4-retrieve-the-new-connection-s-id
Sample response from the API call is below::
{
"count": 1,
"results":[... | Below is the the instruction that describes the task:
### Input:
Return all Heroku Connect connections setup with the given application.
For more details check the link -
https://devcenter.heroku.com/articles/heroku-connect-api#step-4-retrieve-the-new-connection-s-id
Sample response from the API call ... |
def _on_new_data_received(self, data: bytes):
"""
Gets called whenever we get a whole new XML element from kik's servers.
:param data: The data received (bytes)
"""
if data == b' ':
# Happens every half hour. Disconnect after 10th time. Some kind of keep-alive? Let's ... | Gets called whenever we get a whole new XML element from kik's servers.
:param data: The data received (bytes) | Below is the the instruction that describes the task:
### Input:
Gets called whenever we get a whole new XML element from kik's servers.
:param data: The data received (bytes)
### Response:
def _on_new_data_received(self, data: bytes):
"""
Gets called whenever we get a whole new XML element... |
def dragTo(x=None, y=None, duration=0.0, tween=linear, button='left', pause=None, _pause=True, mouseDownUp=True):
"""Performs a mouse drag (mouse movement while a button is held down) to a
point on the screen.
The x and y parameters detail where the mouse event happens. If None, the
current mouse posit... | Performs a mouse drag (mouse movement while a button is held down) to a
point on the screen.
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down. If
outside the boundaries of the screen, the event happens at edge... | Below is the the instruction that describes the task:
### Input:
Performs a mouse drag (mouse movement while a button is held down) to a
point on the screen.
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down. I... |
def CopyToDateTimeString(self):
"""Copies the FILETIME timestamp to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#######" or
None if the timestamp is missing or invalid.
"""
if (self._timestamp is None or self._timestamp < 0 or
sel... | Copies the FILETIME timestamp to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#######" or
None if the timestamp is missing or invalid. | Below is the the instruction that describes the task:
### Input:
Copies the FILETIME timestamp to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#######" or
None if the timestamp is missing or invalid.
### Response:
def CopyToDateTimeString(self):
... |
def add_service(self, service):
"""Add a service description.
Handles transition from self.service=None, self.service=dict for a
single service, and then self.service=[dict,dict,...] for multiple
"""
if (self.service is None):
self.service = service
elif (isi... | Add a service description.
Handles transition from self.service=None, self.service=dict for a
single service, and then self.service=[dict,dict,...] for multiple | Below is the the instruction that describes the task:
### Input:
Add a service description.
Handles transition from self.service=None, self.service=dict for a
single service, and then self.service=[dict,dict,...] for multiple
### Response:
def add_service(self, service):
"""Add a service d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.