code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def processAndSetDefaults(self):
"""
The heart of the 'Instruction' object. This method will make sure that
all fields not entered will be defaulted to a correct value. Also
checks for incongruities in the data entered, if it was by the user.
"""
# INPUT, OUTPUT, GIVEN + ... | The heart of the 'Instruction' object. This method will make sure that
all fields not entered will be defaulted to a correct value. Also
checks for incongruities in the data entered, if it was by the user. | Below is the the instruction that describes the task:
### Input:
The heart of the 'Instruction' object. This method will make sure that
all fields not entered will be defaulted to a correct value. Also
checks for incongruities in the data entered, if it was by the user.
### Response:
def processAnd... |
def GetATR(self, reader):
"""Return the ATR of the card inserted into the reader."""
atr = "no card inserted"
try:
if not type(reader) is str:
connection = reader.createConnection()
connection.connect()
atr = toHexString(connection.getA... | Return the ATR of the card inserted into the reader. | Below is the the instruction that describes the task:
### Input:
Return the ATR of the card inserted into the reader.
### Response:
def GetATR(self, reader):
"""Return the ATR of the card inserted into the reader."""
atr = "no card inserted"
try:
if not type(reader) is str:
... |
def process_dataset(dataset, models, **kargs):
""" Convert ``dataset`` to processed data using ``models``.
:class:`gvar.dataset.Dataset` (or similar dictionary) object
``dataset`` is processed by each model in list ``models``,
and the results collected into a new dictionary ``pdata`` fo... | Convert ``dataset`` to processed data using ``models``.
:class:`gvar.dataset.Dataset` (or similar dictionary) object
``dataset`` is processed by each model in list ``models``,
and the results collected into a new dictionary ``pdata`` for use in
:meth:`MultiFitter.lsqfit` and :meth:`Mult... | Below is the the instruction that describes the task:
### Input:
Convert ``dataset`` to processed data using ``models``.
:class:`gvar.dataset.Dataset` (or similar dictionary) object
``dataset`` is processed by each model in list ``models``,
and the results collected into a new dictionary ``... |
def _add_open_file(self, file_obj):
"""Add file_obj to the list of open files on the filesystem.
Used internally to manage open files.
The position in the open_files array is the file descriptor number.
Args:
file_obj: File object to be added to open files list.
Re... | Add file_obj to the list of open files on the filesystem.
Used internally to manage open files.
The position in the open_files array is the file descriptor number.
Args:
file_obj: File object to be added to open files list.
Returns:
File descriptor number for t... | Below is the the instruction that describes the task:
### Input:
Add file_obj to the list of open files on the filesystem.
Used internally to manage open files.
The position in the open_files array is the file descriptor number.
Args:
file_obj: File object to be added to open f... |
def Handle(self, unused_args, token=None):
"""Build the data structure representing the config."""
sections = {}
for descriptor in config.CONFIG.type_infos:
if descriptor.section in sections:
continue
section_data = {}
for parameter in self._ListParametersInSection(descriptor.sec... | Build the data structure representing the config. | Below is the the instruction that describes the task:
### Input:
Build the data structure representing the config.
### Response:
def Handle(self, unused_args, token=None):
"""Build the data structure representing the config."""
sections = {}
for descriptor in config.CONFIG.type_infos:
if descrip... |
def update_range(self, share_name, directory_name, file_name, data,
start_range, end_range, validate_content=False, timeout=None):
'''
Writes the bytes specified by the request body into the specified range.
:param str share_name:
Name of existing share... | Writes the bytes specified by the request body into the specified range.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the directory.
:param str file_name:
Name of existing file.
:param bytes data:
... | Below is the the instruction that describes the task:
### Input:
Writes the bytes specified by the request body into the specified range.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the directory.
:param str file_nam... |
def config(*args, **attrs):
"""Override configuration"""
attrs.setdefault("metavar", "KEY=VALUE")
attrs.setdefault("multiple", True)
return option(config, *args, **attrs) | Override configuration | Below is the the instruction that describes the task:
### Input:
Override configuration
### Response:
def config(*args, **attrs):
"""Override configuration"""
attrs.setdefault("metavar", "KEY=VALUE")
attrs.setdefault("multiple", True)
return option(config, *args, **attrs) |
def descr2tabledef(descr, table_type='binary', write_bitcols=False):
"""
Create a FITS table def from the input numpy descriptor.
parameters
----------
descr: list
A numpy recarray type descriptor array.dtype.descr
returns
-------
names, formats, dims: tuple of lists
T... | Create a FITS table def from the input numpy descriptor.
parameters
----------
descr: list
A numpy recarray type descriptor array.dtype.descr
returns
-------
names, formats, dims: tuple of lists
These are the ttyp, tform and tdim header entries
for each field. dim ent... | Below is the the instruction that describes the task:
### Input:
Create a FITS table def from the input numpy descriptor.
parameters
----------
descr: list
A numpy recarray type descriptor array.dtype.descr
returns
-------
names, formats, dims: tuple of lists
These are the... |
def parse_firefox (url_data):
"""Parse a Firefox3 bookmark file."""
filename = url_data.get_os_filename()
for url, name in firefox.parse_bookmark_file(filename):
url_data.add_url(url, name=name) | Parse a Firefox3 bookmark file. | Below is the the instruction that describes the task:
### Input:
Parse a Firefox3 bookmark file.
### Response:
def parse_firefox (url_data):
"""Parse a Firefox3 bookmark file."""
filename = url_data.get_os_filename()
for url, name in firefox.parse_bookmark_file(filename):
url_data.add_url(url, ... |
def reset(self, addresses):
"""
Remove all PTR records from the given address
:type addresses: List[str]
:param addresses: (List[str]) The IP Address to reset
:return: (bool) True in case of success, False in case of failure
"""
request = self._call(SetEnqueueRese... | Remove all PTR records from the given address
:type addresses: List[str]
:param addresses: (List[str]) The IP Address to reset
:return: (bool) True in case of success, False in case of failure | Below is the the instruction that describes the task:
### Input:
Remove all PTR records from the given address
:type addresses: List[str]
:param addresses: (List[str]) The IP Address to reset
:return: (bool) True in case of success, False in case of failure
### Response:
def reset(self, add... |
def _yield_spatial_table(patch, div, spp_col, count_col, x_col, y_col):
"""
Calculates an empirical spatial table
Yields
-------
DataFrame
Spatial table for each division. See Notes.
Notes
-----
The spatial table is the precursor to the SAR, EAR, and grid-based
commonality ... | Calculates an empirical spatial table
Yields
-------
DataFrame
Spatial table for each division. See Notes.
Notes
-----
The spatial table is the precursor to the SAR, EAR, and grid-based
commonality metrics. Each row in the table corresponds to a cell created by
a given division... | Below is the the instruction that describes the task:
### Input:
Calculates an empirical spatial table
Yields
-------
DataFrame
Spatial table for each division. See Notes.
Notes
-----
The spatial table is the precursor to the SAR, EAR, and grid-based
commonality metrics. Each r... |
def checkJobGraphAcylic(self):
"""
:raises toil.job.JobGraphDeadlockException: if the connected component \
of jobs containing this job contains any cycles of child/followOn dependencies \
in the *augmented job graph* (see below). Such cycles are not allowed \
in valid job graphs... | :raises toil.job.JobGraphDeadlockException: if the connected component \
of jobs containing this job contains any cycles of child/followOn dependencies \
in the *augmented job graph* (see below). Such cycles are not allowed \
in valid job graphs.
A follow-on edge (A, B) between two jobs... | Below is the the instruction that describes the task:
### Input:
:raises toil.job.JobGraphDeadlockException: if the connected component \
of jobs containing this job contains any cycles of child/followOn dependencies \
in the *augmented job graph* (see below). Such cycles are not allowed \
i... |
def CreateMenuItem(self, MenuItemId, PluginContext, CaptionText, HintText=u'', IconPath='', Enabled=True,
ContactType=pluginContactTypeAll, MultipleContacts=False):
"""Creates custom menu item in Skype client's "Do More" menus.
:Parameters:
MenuItemId : unicode
... | Creates custom menu item in Skype client's "Do More" menus.
:Parameters:
MenuItemId : unicode
Unique identifier for the menu item.
PluginContext : `enums`.pluginContext*
Menu item context. Allows to choose in which client windows will the menu item appear.
... | Below is the the instruction that describes the task:
### Input:
Creates custom menu item in Skype client's "Do More" menus.
:Parameters:
MenuItemId : unicode
Unique identifier for the menu item.
PluginContext : `enums`.pluginContext*
Menu item context. Allows to... |
def network_security_groups_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all network security groups within a resource group.
:param resource_group: The resource group name to list network security \
groups within.
CLI Example:
.. code-block:: bash
sal... | .. versionadded:: 2019.2.0
List all network security groups within a resource group.
:param resource_group: The resource group name to list network security \
groups within.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.network_security_groups_list testgroup | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2019.2.0
List all network security groups within a resource group.
:param resource_group: The resource group name to list network security \
groups within.
CLI Example:
.. code-block:: bash
salt-c... |
def ip_geoloc(ip, hit_api=True):
"""
Get IP geolocation.
Args:
ip (str): IP address to use if no data provided.
hit_api (bool): whether to hit api if info not found.
Returns:
str: latitude and longitude, comma-separated.
"""
from ..logs.models import IPInfoCheck
try... | Get IP geolocation.
Args:
ip (str): IP address to use if no data provided.
hit_api (bool): whether to hit api if info not found.
Returns:
str: latitude and longitude, comma-separated. | Below is the the instruction that describes the task:
### Input:
Get IP geolocation.
Args:
ip (str): IP address to use if no data provided.
hit_api (bool): whether to hit api if info not found.
Returns:
str: latitude and longitude, comma-separated.
### Response:
def ip_geoloc(ip, ... |
def process_url(self, url, retrieve=False):
"""Evaluate a URL as a possible download, and maybe retrieve it"""
if url in self.scanned_urls and not retrieve:
return
self.scanned_urls[url] = True
if not URL_SCHEME(url):
self.process_filename(url)
return
... | Evaluate a URL as a possible download, and maybe retrieve it | Below is the the instruction that describes the task:
### Input:
Evaluate a URL as a possible download, and maybe retrieve it
### Response:
def process_url(self, url, retrieve=False):
"""Evaluate a URL as a possible download, and maybe retrieve it"""
if url in self.scanned_urls and not retrieve:
... |
def sink_path(cls, project, sink):
"""Return a fully-qualified sink string."""
return google.api_core.path_template.expand(
"projects/{project}/sinks/{sink}", project=project, sink=sink
) | Return a fully-qualified sink string. | Below is the the instruction that describes the task:
### Input:
Return a fully-qualified sink string.
### Response:
def sink_path(cls, project, sink):
"""Return a fully-qualified sink string."""
return google.api_core.path_template.expand(
"projects/{project}/sinks/{sink}", project=pro... |
def set_logger(self):
"""Method to build the base logging system. By default, logging level
is set to INFO."""
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
logger_file = os.path.join(self.logs_path, 'dingtalk_sdk.logs')
logger_handler = l... | Method to build the base logging system. By default, logging level
is set to INFO. | Below is the the instruction that describes the task:
### Input:
Method to build the base logging system. By default, logging level
is set to INFO.
### Response:
def set_logger(self):
"""Method to build the base logging system. By default, logging level
is set to INFO."""
logger... |
def send(self, data):
"""
Send encoded instructions to Guacamole guacd server.
"""
self.logger.debug('Sending data: %s' % data)
self.client.sendall(data.encode()) | Send encoded instructions to Guacamole guacd server. | Below is the the instruction that describes the task:
### Input:
Send encoded instructions to Guacamole guacd server.
### Response:
def send(self, data):
"""
Send encoded instructions to Guacamole guacd server.
"""
self.logger.debug('Sending data: %s' % data)
self.client.sen... |
def _stripStrList(self, raw_str, stop_strs):
'''
去除字符串中的所有指定字符串
args:
raw_str 源字符串
stop_strs 指定字符串 列表
return
str 筛选后的字符串
'''
if type(stop_strs) == list:
for word in stop_strs:
raw_str = self._stripStr(raw_str... | 去除字符串中的所有指定字符串
args:
raw_str 源字符串
stop_strs 指定字符串 列表
return
str 筛选后的字符串 | Below is the the instruction that describes the task:
### Input:
去除字符串中的所有指定字符串
args:
raw_str 源字符串
stop_strs 指定字符串 列表
return
str 筛选后的字符串
### Response:
def _stripStrList(self, raw_str, stop_strs):
'''
去除字符串中的所有指定字符串
args:
raw_st... |
def generate_random_string(length=6):
'''
Returns a random string of a specified length.
>>> len(generate_random_string(length=25))
25
Test randomness. Try N times and observe no duplicaton
>>> N = 100
>>> len(set(generate_random_string(10) for i in range(N))) == N
True
'''
n =... | Returns a random string of a specified length.
>>> len(generate_random_string(length=25))
25
Test randomness. Try N times and observe no duplicaton
>>> N = 100
>>> len(set(generate_random_string(10) for i in range(N))) == N
True | Below is the the instruction that describes the task:
### Input:
Returns a random string of a specified length.
>>> len(generate_random_string(length=25))
25
Test randomness. Try N times and observe no duplicaton
>>> N = 100
>>> len(set(generate_random_string(10) for i in range(N))) == N
T... |
def getCountGT(self, item):
"""Return number of elements greater than *item*."""
index = bisect.bisect_right(self._list, item)
return len(self._list) - index | Return number of elements greater than *item*. | Below is the the instruction that describes the task:
### Input:
Return number of elements greater than *item*.
### Response:
def getCountGT(self, item):
"""Return number of elements greater than *item*."""
index = bisect.bisect_right(self._list, item)
return len(self._list) - index |
def user_set_avatar(self, action=None, quick_key=None, url=None):
"""user/set_avatar
http://www.mediafire.com/developers/core_api/1.3/user/#set_avatar
"""
return self.request("user/set_avatar", QueryParams({
"action": action,
"quick_key": quick_key,
"... | user/set_avatar
http://www.mediafire.com/developers/core_api/1.3/user/#set_avatar | Below is the the instruction that describes the task:
### Input:
user/set_avatar
http://www.mediafire.com/developers/core_api/1.3/user/#set_avatar
### Response:
def user_set_avatar(self, action=None, quick_key=None, url=None):
"""user/set_avatar
http://www.mediafire.com/developers/core_ap... |
def elements(compounds):
"""
Determine the set of elements present in a list of chemical compounds.
The list of elements is sorted alphabetically.
:param compounds: List of compound formulas and phases, e.g.
['Fe2O3[S1]', 'Al2O3[S1]'].
:returns: List of elements.
"""
elementlist = ... | Determine the set of elements present in a list of chemical compounds.
The list of elements is sorted alphabetically.
:param compounds: List of compound formulas and phases, e.g.
['Fe2O3[S1]', 'Al2O3[S1]'].
:returns: List of elements. | Below is the the instruction that describes the task:
### Input:
Determine the set of elements present in a list of chemical compounds.
The list of elements is sorted alphabetically.
:param compounds: List of compound formulas and phases, e.g.
['Fe2O3[S1]', 'Al2O3[S1]'].
:returns: List of eleme... |
def find_external_links(url, page):
"""Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
for match in REL.finditer(page):
tag, rel = match.groups()
rels = set(map(str.strip, rel.lower().split(',')))
if 'homepage' in rels or 'download' in rels:
for matc... | Find rel="homepage" and rel="download" links in `page`, yielding URLs | Below is the the instruction that describes the task:
### Input:
Find rel="homepage" and rel="download" links in `page`, yielding URLs
### Response:
def find_external_links(url, page):
"""Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
for match in REL.finditer(page):
tag,... |
def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir,
jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, module_name):
"""Ensures all the training, testing, and validation bottlenecks are cached.
Because we're likely to read th... | Ensures all the training, testing, and validation bottlenecks are cached.
Because we're likely to read the same image multiple times (if there are no
distortions applied during training) it can speed things up a lot if we
calculate the bottleneck layer values once for each image during
preprocessing, and then ... | Below is the the instruction that describes the task:
### Input:
Ensures all the training, testing, and validation bottlenecks are cached.
Because we're likely to read the same image multiple times (if there are no
distortions applied during training) it can speed things up a lot if we
calculate the bottlene... |
def fit(self,
data: List[str],
return_tokenized_data: bool = False) -> Union[None, List[List[str]]]:
"""
TODO: update docs
Apply cleaner and tokenzier to raw data and build vocabulary.
Parameters
----------
data : List[str]
These are ... | TODO: update docs
Apply cleaner and tokenzier to raw data and build vocabulary.
Parameters
----------
data : List[str]
These are raw documents, which are a list of strings. ex:
[["The quick brown fox"], ["jumps over the lazy dog"]]
return_tokenized_data ... | Below is the the instruction that describes the task:
### Input:
TODO: update docs
Apply cleaner and tokenzier to raw data and build vocabulary.
Parameters
----------
data : List[str]
These are raw documents, which are a list of strings. ex:
[["The quick bro... |
def json_file_response(obj=None, pid=None, record=None, status=None):
"""JSON Files/File serializer.
:param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance or
a :class:`invenio_records_files.api.FilesIterator` if it's a list of
files.
:param pid: PID value. (not used)
:... | JSON Files/File serializer.
:param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance or
a :class:`invenio_records_files.api.FilesIterator` if it's a list of
files.
:param pid: PID value. (not used)
:param record: The record metadata. (not used)
:param status: The HTTP sta... | Below is the the instruction that describes the task:
### Input:
JSON Files/File serializer.
:param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance or
a :class:`invenio_records_files.api.FilesIterator` if it's a list of
files.
:param pid: PID value. (not used)
:param re... |
def play_sound(self, subject='Find My iPhone Alert'):
""" Send a request to the device to play a sound.
It's possible to pass a custom message by changing the `subject`.
"""
data = json.dumps({
'device': self.content['id'],
'subject': subject,
'client... | Send a request to the device to play a sound.
It's possible to pass a custom message by changing the `subject`. | Below is the the instruction that describes the task:
### Input:
Send a request to the device to play a sound.
It's possible to pass a custom message by changing the `subject`.
### Response:
def play_sound(self, subject='Find My iPhone Alert'):
""" Send a request to the device to play a sound.
... |
def infer_unaryop(self, context=None):
"""Infer what an UnaryOp should return when evaluated."""
yield from _filter_operation_errors(
self, _infer_unaryop, context, util.BadUnaryOperationMessage
)
return dict(node=self, context=context) | Infer what an UnaryOp should return when evaluated. | Below is the the instruction that describes the task:
### Input:
Infer what an UnaryOp should return when evaluated.
### Response:
def infer_unaryop(self, context=None):
"""Infer what an UnaryOp should return when evaluated."""
yield from _filter_operation_errors(
self, _infer_unaryop, context, uti... |
def parseEntityRef(self):
"""parse ENTITY references declarations [68] EntityRef ::=
'&' Name ';' [ WFC: Entity Declared ] In a document
without any DTD, a document with only an internal DTD
subset which contains no parameter entity references, or a
document with "stand... | parse ENTITY references declarations [68] EntityRef ::=
'&' Name ';' [ WFC: Entity Declared ] In a document
without any DTD, a document with only an internal DTD
subset which contains no parameter entity references, or a
document with "standalone='yes'", the Name given in the
... | Below is the the instruction that describes the task:
### Input:
parse ENTITY references declarations [68] EntityRef ::=
'&' Name ';' [ WFC: Entity Declared ] In a document
without any DTD, a document with only an internal DTD
subset which contains no parameter entity references, or ... |
def resize(self, size=None):
"""
Resize the container's PTY.
If `size` is not None, it must be a tuple of (height,width), otherwise
it will be determined by the size of the current TTY.
"""
if not self.israw():
return
size = size or tty.size(self.st... | Resize the container's PTY.
If `size` is not None, it must be a tuple of (height,width), otherwise
it will be determined by the size of the current TTY. | Below is the the instruction that describes the task:
### Input:
Resize the container's PTY.
If `size` is not None, it must be a tuple of (height,width), otherwise
it will be determined by the size of the current TTY.
### Response:
def resize(self, size=None):
"""
Resize the contai... |
def _fix_squeeze(self, inputs, new_attr):
"""
MXNet doesnt have a squeeze operator.
Using "split" to perform similar operation.
"split" can be slower compared to "reshape".
This can have performance impact.
TODO: Remove this implementation once mxnet adds the support.
... | MXNet doesnt have a squeeze operator.
Using "split" to perform similar operation.
"split" can be slower compared to "reshape".
This can have performance impact.
TODO: Remove this implementation once mxnet adds the support. | Below is the the instruction that describes the task:
### Input:
MXNet doesnt have a squeeze operator.
Using "split" to perform similar operation.
"split" can be slower compared to "reshape".
This can have performance impact.
TODO: Remove this implementation once mxnet adds the sup... |
def parse_assertion(self, keys=None):
""" Parse the assertions for a saml response.
:param keys: A string representing a RSA key or a list of strings
containing RSA keys.
:return: True if the assertions are parsed otherwise False.
"""
if self.context == "AuthnQuery":
... | Parse the assertions for a saml response.
:param keys: A string representing a RSA key or a list of strings
containing RSA keys.
:return: True if the assertions are parsed otherwise False. | Below is the the instruction that describes the task:
### Input:
Parse the assertions for a saml response.
:param keys: A string representing a RSA key or a list of strings
containing RSA keys.
:return: True if the assertions are parsed otherwise False.
### Response:
def parse_assertion(se... |
def deprecated(func, *args, **kwargs):
''' Marks a function as deprecated. '''
warnings.warn(
'{} is deprecated and should no longer be used.'.format(func),
DeprecationWarning,
stacklevel=3
)
return func(*args, **kwargs) | Marks a function as deprecated. | Below is the the instruction that describes the task:
### Input:
Marks a function as deprecated.
### Response:
def deprecated(func, *args, **kwargs):
''' Marks a function as deprecated. '''
warnings.warn(
'{} is deprecated and should no longer be used.'.format(func),
DeprecationWarning,
... |
def AgregarCalidad(self, analisis_muestra=None, nro_boletin=None,
cod_grado=None, valor_grado=None,
valor_contenido_proteico=None, valor_factor=None,
**kwargs):
"Agrega la información sobre la calidad, al autorizar o poster... | Agrega la información sobre la calidad, al autorizar o posteriormente | Below is the the instruction that describes the task:
### Input:
Agrega la información sobre la calidad, al autorizar o posteriormente
### Response:
def AgregarCalidad(self, analisis_muestra=None, nro_boletin=None,
cod_grado=None, valor_grado=None,
valor_c... |
def _impl(lexer):
"""Return an Implies expression."""
p = _sumterm(lexer)
tok = next(lexer)
# SUMTERM '=>' IMPL
if isinstance(tok, OP_rarrow):
q = _impl(lexer)
return ('implies', p, q)
# SUMTERM '<=>' IMPL
elif isinstance(tok, OP_lrarrow):
q = _impl(lexer)
re... | Return an Implies expression. | Below is the the instruction that describes the task:
### Input:
Return an Implies expression.
### Response:
def _impl(lexer):
"""Return an Implies expression."""
p = _sumterm(lexer)
tok = next(lexer)
# SUMTERM '=>' IMPL
if isinstance(tok, OP_rarrow):
q = _impl(lexer)
return ('... |
def has_api_scopes(self, *api_scopes):
"""
Test if all given API scopes are authorized.
:type api_scopes: list[str]
:param api_scopes: The API scopes to test
:rtype: bool|None
:return:
True or False, if the API Token has the API scopes field set,
oth... | Test if all given API scopes are authorized.
:type api_scopes: list[str]
:param api_scopes: The API scopes to test
:rtype: bool|None
:return:
True or False, if the API Token has the API scopes field set,
otherwise None | Below is the the instruction that describes the task:
### Input:
Test if all given API scopes are authorized.
:type api_scopes: list[str]
:param api_scopes: The API scopes to test
:rtype: bool|None
:return:
True or False, if the API Token has the API scopes field set,
... |
def dumps(obj, preserve=False):
"""Stringifies a dict as toml
:param obj: the object to be dumped into toml
:param preserve: optional flag to preserve the inline table in result
"""
f = StringIO()
dump(obj, f, preserve)
return f.getvalue() | Stringifies a dict as toml
:param obj: the object to be dumped into toml
:param preserve: optional flag to preserve the inline table in result | Below is the the instruction that describes the task:
### Input:
Stringifies a dict as toml
:param obj: the object to be dumped into toml
:param preserve: optional flag to preserve the inline table in result
### Response:
def dumps(obj, preserve=False):
"""Stringifies a dict as toml
:param obj: t... |
def get_entry_point(key, value):
"""Check if registered entry point is available for a given name and
load it. Otherwise, return None.
key (unicode): Entry point name.
value (unicode): Name of entry point to load.
RETURNS: The loaded entry point or None.
"""
for entry_point in pkg_resources... | Check if registered entry point is available for a given name and
load it. Otherwise, return None.
key (unicode): Entry point name.
value (unicode): Name of entry point to load.
RETURNS: The loaded entry point or None. | Below is the the instruction that describes the task:
### Input:
Check if registered entry point is available for a given name and
load it. Otherwise, return None.
key (unicode): Entry point name.
value (unicode): Name of entry point to load.
RETURNS: The loaded entry point or None.
### Response:
... |
def open_file(filepath):
"""
Open file with the default system app.
Copied from https://stackoverflow.com/a/435669/1224456
"""
if sys.platform.startswith('darwin'):
subprocess.Popen(('open', filepath))
elif os.name == 'nt':
os.startfile(filepath)
elif os.name == 'posix':
... | Open file with the default system app.
Copied from https://stackoverflow.com/a/435669/1224456 | Below is the the instruction that describes the task:
### Input:
Open file with the default system app.
Copied from https://stackoverflow.com/a/435669/1224456
### Response:
def open_file(filepath):
"""
Open file with the default system app.
Copied from https://stackoverflow.com/a/435669/1224456
... |
def clean(self, value):
"""Cleans and returns the given value, or raises a ParameterNotValidError exception"""
if isinstance(value, six.string_types) and value.lower() == 'false':
return False
return bool(value) | Cleans and returns the given value, or raises a ParameterNotValidError exception | Below is the the instruction that describes the task:
### Input:
Cleans and returns the given value, or raises a ParameterNotValidError exception
### Response:
def clean(self, value):
"""Cleans and returns the given value, or raises a ParameterNotValidError exception"""
if isinstance(value, six.st... |
def create(self, unique_name, friendly_name=values.unset, actions=values.unset,
actions_url=values.unset):
"""
Create a new TaskInstance
:param unicode unique_name: An application-defined string that uniquely identifies the resource
:param unicode friendly_name: descript... | Create a new TaskInstance
:param unicode unique_name: An application-defined string that uniquely identifies the resource
:param unicode friendly_name: descriptive string that you create to describe the new resource
:param dict actions: The JSON string that specifies the actions that instruct ... | Below is the the instruction that describes the task:
### Input:
Create a new TaskInstance
:param unicode unique_name: An application-defined string that uniquely identifies the resource
:param unicode friendly_name: descriptive string that you create to describe the new resource
:param di... |
def order_assimilation(args):
"""
Internal helper method for BorgQueen to process assimilation
"""
(path, drone, data, status) = args
newdata = drone.assimilate(path)
if newdata:
data.append(json.dumps(newdata, cls=MontyEncoder))
status['count'] += 1
count = status['count']
t... | Internal helper method for BorgQueen to process assimilation | Below is the the instruction that describes the task:
### Input:
Internal helper method for BorgQueen to process assimilation
### Response:
def order_assimilation(args):
"""
Internal helper method for BorgQueen to process assimilation
"""
(path, drone, data, status) = args
newdata = drone.assim... |
def order(self, order):
"""Returns name order key.
Returns tuple with two strings that can be compared to other such
tuple obtained from different name. Note that if you want
locale-dependent ordering then you need to compare strings using
locale-aware method (e.g. ``locale.strx... | Returns name order key.
Returns tuple with two strings that can be compared to other such
tuple obtained from different name. Note that if you want
locale-dependent ordering then you need to compare strings using
locale-aware method (e.g. ``locale.strxfrm``).
:param order: One ... | Below is the the instruction that describes the task:
### Input:
Returns name order key.
Returns tuple with two strings that can be compared to other such
tuple obtained from different name. Note that if you want
locale-dependent ordering then you need to compare strings using
local... |
def logged_delete(self, user):
"""Delete the document and log the event in the change log"""
self.delete()
# Log the change
entry = ChangeLogEntry({
'type': 'DELETED',
'documents': [self],
'user': user
})
entry.insert()
r... | Delete the document and log the event in the change log | Below is the the instruction that describes the task:
### Input:
Delete the document and log the event in the change log
### Response:
def logged_delete(self, user):
"""Delete the document and log the event in the change log"""
self.delete()
# Log the change
entry = ChangeLogEntry... |
def sign(self, signer: Signer):
"""This method signs twice:
- the `non_closing_signature` for the balance proof update
- the `reward_proof_signature` for the monitoring request
"""
self.non_closing_signature = self.balance_proof._sign(signer)
message_data = self._... | This method signs twice:
- the `non_closing_signature` for the balance proof update
- the `reward_proof_signature` for the monitoring request | Below is the the instruction that describes the task:
### Input:
This method signs twice:
- the `non_closing_signature` for the balance proof update
- the `reward_proof_signature` for the monitoring request
### Response:
def sign(self, signer: Signer):
"""This method signs twice:
... |
def get_source_id(self):
"""Gets the ``Resource Id`` of the source of this asset.
The source is the original owner of the copyright of this asset
and may differ from the creator of this asset. The source for a
published book written by Margaret Mitchell would be Macmillan.
The s... | Gets the ``Resource Id`` of the source of this asset.
The source is the original owner of the copyright of this asset
and may differ from the creator of this asset. The source for a
published book written by Margaret Mitchell would be Macmillan.
The source for an unpublished painting by... | Below is the the instruction that describes the task:
### Input:
Gets the ``Resource Id`` of the source of this asset.
The source is the original owner of the copyright of this asset
and may differ from the creator of this asset. The source for a
published book written by Margaret Mitchell ... |
def predicates_overlap(tags1: List[str], tags2: List[str]) -> bool:
"""
Tests whether the predicate in BIO tags1 overlap
with those of tags2.
"""
# Get predicate word indices from both predictions
pred_ind1 = get_predicate_indices(tags1)
pred_ind2 = get_predicate_indices(tags2)
# Return... | Tests whether the predicate in BIO tags1 overlap
with those of tags2. | Below is the the instruction that describes the task:
### Input:
Tests whether the predicate in BIO tags1 overlap
with those of tags2.
### Response:
def predicates_overlap(tags1: List[str], tags2: List[str]) -> bool:
"""
Tests whether the predicate in BIO tags1 overlap
with those of tags2.
"""
... |
def email(value, whitelist=None):
"""
Validate an email address.
This validator is based on `Django's email validator`_. Returns
``True`` on success and :class:`~validators.utils.ValidationFailure`
when validation fails.
Examples::
>>> email('someone@example.com')
True
... | Validate an email address.
This validator is based on `Django's email validator`_. Returns
``True`` on success and :class:`~validators.utils.ValidationFailure`
when validation fails.
Examples::
>>> email('someone@example.com')
True
>>> email('bogus@@')
ValidationFailu... | Below is the the instruction that describes the task:
### Input:
Validate an email address.
This validator is based on `Django's email validator`_. Returns
``True`` on success and :class:`~validators.utils.ValidationFailure`
when validation fails.
Examples::
>>> email('someone@example.com... |
def screenshots_done(self, jobid):
"""
Return true if the screenshots job is done
"""
resp = self.session.get(os.path.join(self.api_url, '{0}.json'.format(jobid)))
resp = self._process_response(resp)
return True if resp.json()['state'] == 'done' else False | Return true if the screenshots job is done | Below is the the instruction that describes the task:
### Input:
Return true if the screenshots job is done
### Response:
def screenshots_done(self, jobid):
"""
Return true if the screenshots job is done
"""
resp = self.session.get(os.path.join(self.api_url, '{0}.json'.format(jobid)... |
def _strip_scope(msg):
'''
Strip unnecessary message about running the command with --scope from
stderr so that we can raise an exception with the remaining stderr text.
'''
ret = []
for line in msg.splitlines():
if not line.endswith('.scope'):
ret.append(line)
return '\n... | Strip unnecessary message about running the command with --scope from
stderr so that we can raise an exception with the remaining stderr text. | Below is the the instruction that describes the task:
### Input:
Strip unnecessary message about running the command with --scope from
stderr so that we can raise an exception with the remaining stderr text.
### Response:
def _strip_scope(msg):
'''
Strip unnecessary message about running the command wi... |
def add_user(self, uid, nodes, weights):
"""Add a user."""
for i, node in enumerate(nodes):
self.file.write("{},{},{}\n".format(uid, node, weights[i])) | Add a user. | Below is the the instruction that describes the task:
### Input:
Add a user.
### Response:
def add_user(self, uid, nodes, weights):
"""Add a user."""
for i, node in enumerate(nodes):
self.file.write("{},{},{}\n".format(uid, node, weights[i])) |
def dehydrate_time(value):
""" Dehydrator for `time` values.
:param value:
:type value: Time
:return:
"""
if isinstance(value, Time):
nanoseconds = int(value.ticks * 1000000000)
elif isinstance(value, time):
nanoseconds = (3600000000000 * value.hour + 60000000000 * value.min... | Dehydrator for `time` values.
:param value:
:type value: Time
:return: | Below is the the instruction that describes the task:
### Input:
Dehydrator for `time` values.
:param value:
:type value: Time
:return:
### Response:
def dehydrate_time(value):
""" Dehydrator for `time` values.
:param value:
:type value: Time
:return:
"""
if isinstance(value, ... |
def plot_heatmap(fig, ax, data,
xaxislabel=None, yaxislabel=None,
xticklabels=None, yticklabels=None,
title=None, grid=True,
values_in_cells=True, round_values_in_cells=2,
legend=False,
fontsize_axislabel=None,
... | helper function to plot a heatmap for a 2D matrix `data` using matplotlib's "matshow" function | Below is the the instruction that describes the task:
### Input:
helper function to plot a heatmap for a 2D matrix `data` using matplotlib's "matshow" function
### Response:
def plot_heatmap(fig, ax, data,
xaxislabel=None, yaxislabel=None,
xticklabels=None, yticklabels=None,
... |
def help(self, error=None, topic=None, parser=None):
"""Display an error message, or the named topic."""
assert error or topic or parser
if error:
print(error)
print("Use 'coverage help' for help.")
elif parser:
print(parser.format_help().strip())
... | Display an error message, or the named topic. | Below is the the instruction that describes the task:
### Input:
Display an error message, or the named topic.
### Response:
def help(self, error=None, topic=None, parser=None):
"""Display an error message, or the named topic."""
assert error or topic or parser
if error:
print(e... |
def setHandler(self, event_name, callback):
"""Set an handler for given event."""
if event_name not in self.handlers:
raise ValueError('{} is not a valid event'.format(event_name))
if callable(event_name):
raise TypeError('{} is not callable'.format(callback))
sel... | Set an handler for given event. | Below is the the instruction that describes the task:
### Input:
Set an handler for given event.
### Response:
def setHandler(self, event_name, callback):
"""Set an handler for given event."""
if event_name not in self.handlers:
raise ValueError('{} is not a valid event'.format(event_na... |
def _del(self, command, *args, **kwargs):
"""
Shortcut for commands that remove all values of the field.
All will be deindexed.
"""
if self.indexable:
self.deindex()
return self._traverse_command(command, *args, **kwargs) | Shortcut for commands that remove all values of the field.
All will be deindexed. | Below is the the instruction that describes the task:
### Input:
Shortcut for commands that remove all values of the field.
All will be deindexed.
### Response:
def _del(self, command, *args, **kwargs):
"""
Shortcut for commands that remove all values of the field.
All will be deind... |
def run(host: Optional[str] = None, port: Optional[int] = None,
*args, **kwargs) -> None:
"""Run the NoneBot instance."""
get_bot().run(host=host, port=port, *args, **kwargs) | Run the NoneBot instance. | Below is the the instruction that describes the task:
### Input:
Run the NoneBot instance.
### Response:
def run(host: Optional[str] = None, port: Optional[int] = None,
*args, **kwargs) -> None:
"""Run the NoneBot instance."""
get_bot().run(host=host, port=port, *args, **kwargs) |
def _take_action(self):
"""Determines whether to perform the action or not.
Checks whether or not an action should be taken. This is determined by
the truthy value for the unless parameter. If unless is a callback
method, it will be invoked with no parameters in order to determine
... | Determines whether to perform the action or not.
Checks whether or not an action should be taken. This is determined by
the truthy value for the unless parameter. If unless is a callback
method, it will be invoked with no parameters in order to determine
whether or not the action should... | Below is the the instruction that describes the task:
### Input:
Determines whether to perform the action or not.
Checks whether or not an action should be taken. This is determined by
the truthy value for the unless parameter. If unless is a callback
method, it will be invoked with no para... |
def is_valid_input_array(x, ndim=None):
"""Test if ``x`` is a correctly shaped point array in R^d."""
x = np.asarray(x)
if ndim is None or ndim == 1:
return x.ndim == 1 and x.size > 1 or x.ndim == 2 and x.shape[0] == 1
else:
return x.ndim == 2 and x.shape[0] == ndim | Test if ``x`` is a correctly shaped point array in R^d. | Below is the the instruction that describes the task:
### Input:
Test if ``x`` is a correctly shaped point array in R^d.
### Response:
def is_valid_input_array(x, ndim=None):
"""Test if ``x`` is a correctly shaped point array in R^d."""
x = np.asarray(x)
if ndim is None or ndim == 1:
return x.... |
def add_put(self, *args, **kwargs):
"""
Shortcut for add_route with method PUT
"""
return self.add_route(hdrs.METH_PUT, *args, **kwargs) | Shortcut for add_route with method PUT | Below is the the instruction that describes the task:
### Input:
Shortcut for add_route with method PUT
### Response:
def add_put(self, *args, **kwargs):
"""
Shortcut for add_route with method PUT
"""
return self.add_route(hdrs.METH_PUT, *args, **kwargs) |
def do_levmarq_all_particle_groups(s, region_size=40, max_iter=2, damping=1.0,
decrease_damp_factor=10., run_length=4, collect_stats=False, **kwargs):
"""
Levenberg-Marquardt optimization for every particle in the state.
Convenience wrapper for LMParticleGroupCollection. Same keyword args,
but ... | Levenberg-Marquardt optimization for every particle in the state.
Convenience wrapper for LMParticleGroupCollection. Same keyword args,
but I've set the defaults to what I've found to be useful values for
optimizing particles. See LMParticleGroupCollection for documentation.
See Also
--------
... | Below is the the instruction that describes the task:
### Input:
Levenberg-Marquardt optimization for every particle in the state.
Convenience wrapper for LMParticleGroupCollection. Same keyword args,
but I've set the defaults to what I've found to be useful values for
optimizing particles. See LMParti... |
def get_page_id(name, space):
"""Return id of a page based on passed page name and space.
Parameters:
- name: name of a Confluence page.
- space: space the Confluence page is in.
"""
data = _json.loads(_api.rest("?title=" + name.replace(" ", "%20") + "&"
"spaceKey=" + spac... | Return id of a page based on passed page name and space.
Parameters:
- name: name of a Confluence page.
- space: space the Confluence page is in. | Below is the the instruction that describes the task:
### Input:
Return id of a page based on passed page name and space.
Parameters:
- name: name of a Confluence page.
- space: space the Confluence page is in.
### Response:
def get_page_id(name, space):
"""Return id of a page based on passed page ... |
def snapshot(self, target=None, defer=None, autonumber=False):
'''Save the contents of current surface into a file or cairo surface/context
:param filename: Can be a filename or a Cairo surface.
:param defer: If true, buffering/threading may be employed however output will not be immediate.
... | Save the contents of current surface into a file or cairo surface/context
:param filename: Can be a filename or a Cairo surface.
:param defer: If true, buffering/threading may be employed however output will not be immediate.
:param autonumber: If true then a number will be appended to the file... | Below is the the instruction that describes the task:
### Input:
Save the contents of current surface into a file or cairo surface/context
:param filename: Can be a filename or a Cairo surface.
:param defer: If true, buffering/threading may be employed however output will not be immediate.
... |
def read_accpro20(infile):
"""Read the accpro20 output (.acc20) and return the parsed FASTA records.
Keeps the spaces between the accessibility numbers.
Args:
infile: Path to .acc20 file
Returns:
dict: Dictionary of accessibilities with keys as the ID
"""
with open(infile) as... | Read the accpro20 output (.acc20) and return the parsed FASTA records.
Keeps the spaces between the accessibility numbers.
Args:
infile: Path to .acc20 file
Returns:
dict: Dictionary of accessibilities with keys as the ID | Below is the the instruction that describes the task:
### Input:
Read the accpro20 output (.acc20) and return the parsed FASTA records.
Keeps the spaces between the accessibility numbers.
Args:
infile: Path to .acc20 file
Returns:
dict: Dictionary of accessibilities with keys as the I... |
def session_path(cls, project, instance, database, session):
"""Return a fully-qualified session string."""
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}/databases/{database}/sessions/{session}",
project=project,
instance=instan... | Return a fully-qualified session string. | Below is the the instruction that describes the task:
### Input:
Return a fully-qualified session string.
### Response:
def session_path(cls, project, instance, database, session):
"""Return a fully-qualified session string."""
return google.api_core.path_template.expand(
"projects/{pro... |
def get_resource(self, service_name, resource_name, base_class=None):
"""
Returns a ``Resource`` **class** for a given service.
:param service_name: A string that specifies the name of the desired
service. Ex. ``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
... | Returns a ``Resource`` **class** for a given service.
:param service_name: A string that specifies the name of the desired
service. Ex. ``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param resource_name: A string that specifies the name of the desired
... | Below is the the instruction that describes the task:
### Input:
Returns a ``Resource`` **class** for a given service.
:param service_name: A string that specifies the name of the desired
service. Ex. ``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param resour... |
def index_labels(labels, case_sensitive=False):
"""Convert a list of string identifiers into numerical indices.
Parameters
----------
labels : list of strings, shape=(n,)
A list of annotations, e.g., segment or chord labels from an
annotation file.
case_sensitive : bool
Set... | Convert a list of string identifiers into numerical indices.
Parameters
----------
labels : list of strings, shape=(n,)
A list of annotations, e.g., segment or chord labels from an
annotation file.
case_sensitive : bool
Set to True to enable case-sensitive label indexing
... | Below is the the instruction that describes the task:
### Input:
Convert a list of string identifiers into numerical indices.
Parameters
----------
labels : list of strings, shape=(n,)
A list of annotations, e.g., segment or chord labels from an
annotation file.
case_sensitive : bo... |
def _indent(stream, indent, *msgs):
""" write a message to a text stream, with indentation. Also ensures that
the output encoding of the messages is safe for writing. """
for x in range(0, indent):
stream.write(" ")
for x in msgs:
# Any nicer way? In Py2 x can be 'str' or 'unicode'.
... | write a message to a text stream, with indentation. Also ensures that
the output encoding of the messages is safe for writing. | Below is the the instruction that describes the task:
### Input:
write a message to a text stream, with indentation. Also ensures that
the output encoding of the messages is safe for writing.
### Response:
def _indent(stream, indent, *msgs):
""" write a message to a text stream, with indentation. Also ens... |
def set_widgets(self):
"""Set widgets on the Classify tab."""
purpose = self.parent.step_kw_purpose.selected_purpose()
subcategory = self.parent.step_kw_subcategory.selected_subcategory()
classification = self.parent.step_kw_classification.\
selected_classification()
... | Set widgets on the Classify tab. | Below is the the instruction that describes the task:
### Input:
Set widgets on the Classify tab.
### Response:
def set_widgets(self):
"""Set widgets on the Classify tab."""
purpose = self.parent.step_kw_purpose.selected_purpose()
subcategory = self.parent.step_kw_subcategory.selected_subca... |
def get_clear_pin(pinblock, account_number):
"""
Calculate the clear PIN from provided PIN block and account_number, which is the 12 right-most digits of card account number, excluding check digit
"""
raw_pinblock = bytes.fromhex(pinblock.decode('utf-8'))
raw_acct_num = bytes.fromhex((b'0000' + acco... | Calculate the clear PIN from provided PIN block and account_number, which is the 12 right-most digits of card account number, excluding check digit | Below is the the instruction that describes the task:
### Input:
Calculate the clear PIN from provided PIN block and account_number, which is the 12 right-most digits of card account number, excluding check digit
### Response:
def get_clear_pin(pinblock, account_number):
"""
Calculate the clear PIN from pr... |
def process_raw(self, raw: dict) -> None:
"""Pre-process raw dict.
Prepare parameters to work with APIItems.
"""
raw_ports = {}
for param in raw:
port_index = REGEX_PORT_INDEX.search(param).group(0)
if port_index not in raw_ports:
raw_po... | Pre-process raw dict.
Prepare parameters to work with APIItems. | Below is the the instruction that describes the task:
### Input:
Pre-process raw dict.
Prepare parameters to work with APIItems.
### Response:
def process_raw(self, raw: dict) -> None:
"""Pre-process raw dict.
Prepare parameters to work with APIItems.
"""
raw_ports = {}
... |
def create_api_ipv4(self):
"""Get an instance of Api IPv4 services facade."""
return ApiIPv4(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | Get an instance of Api IPv4 services facade. | Below is the the instruction that describes the task:
### Input:
Get an instance of Api IPv4 services facade.
### Response:
def create_api_ipv4(self):
"""Get an instance of Api IPv4 services facade."""
return ApiIPv4(
self.networkapi_url,
self.user,
self.passwor... |
def wait_for_exit(
log,
debug=False):
"""wait_for_exit
Sleep to allow the thread to pick up final messages
before exiting and stopping the Splunk HTTP publisher.
You can decrease this delay (in seconds) by reducing
the splunk_sleep_interval or by exporting the env var:
export S... | wait_for_exit
Sleep to allow the thread to pick up final messages
before exiting and stopping the Splunk HTTP publisher.
You can decrease this delay (in seconds) by reducing
the splunk_sleep_interval or by exporting the env var:
export SPLUNK_SLEEP_INTERVAL=0.5
If you set the timer to 0 then ... | Below is the the instruction that describes the task:
### Input:
wait_for_exit
Sleep to allow the thread to pick up final messages
before exiting and stopping the Splunk HTTP publisher.
You can decrease this delay (in seconds) by reducing
the splunk_sleep_interval or by exporting the env var:
... |
def _role_remove(name, user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
Removes a role from the Postgres Server
'''
# check if user exists
if not user_exists(name, user, host, port, maintenance_db,
password=password, runas... | Removes a role from the Postgres Server | Below is the the instruction that describes the task:
### Input:
Removes a role from the Postgres Server
### Response:
def _role_remove(name, user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
Removes a role from the Postgres Server
'''
# check i... |
def prepare_storage_dir(storage_directory):
"""Prepare the storage directory."""
storage_directory = os.path.expanduser(storage_directory)
if not os.path.exists(storage_directory):
os.mkdir(storage_directory)
return storage_directory | Prepare the storage directory. | Below is the the instruction that describes the task:
### Input:
Prepare the storage directory.
### Response:
def prepare_storage_dir(storage_directory):
"""Prepare the storage directory."""
storage_directory = os.path.expanduser(storage_directory)
if not os.path.exists(storage_directory):
os.m... |
def rl_cleanspaces(x):
"""
Clean double spaces, trailing spaces, heading spaces,
spaces before punctuations
"""
patterns = (
# arguments for re.sub: pattern and repl
# удаляем пробел перед знаками препинания
(r' +([\.,?!\)]+)', r'\1'),
# добавляем пробел после знака п... | Clean double spaces, trailing spaces, heading spaces,
spaces before punctuations | Below is the the instruction that describes the task:
### Input:
Clean double spaces, trailing spaces, heading spaces,
spaces before punctuations
### Response:
def rl_cleanspaces(x):
"""
Clean double spaces, trailing spaces, heading spaces,
spaces before punctuations
"""
patterns = (
... |
def resize(line, factor):
"""
factor: relative length (1->no change, 2-> double, 0.5:half)
"""
a = angle(line)
mx, my = middle(line)
d = length(line) * factor * 0.5
dx = cos(a) * d
dy = sin(a) * d
return mx - dx, my - dy, mx + dx, my + dy | factor: relative length (1->no change, 2-> double, 0.5:half) | Below is the the instruction that describes the task:
### Input:
factor: relative length (1->no change, 2-> double, 0.5:half)
### Response:
def resize(line, factor):
"""
factor: relative length (1->no change, 2-> double, 0.5:half)
"""
a = angle(line)
mx, my = middle(line)
d = length(line) *... |
def has_option(self, option):
"""
Return True if the option is included in this key.
Parameters
----------
option : str
The option.
Returns
-------
has : bool
True if the option can be found. Otherwise False will be returned.
... | Return True if the option is included in this key.
Parameters
----------
option : str
The option.
Returns
-------
has : bool
True if the option can be found. Otherwise False will be returned. | Below is the the instruction that describes the task:
### Input:
Return True if the option is included in this key.
Parameters
----------
option : str
The option.
Returns
-------
has : bool
True if the option can be found. Otherwise False wil... |
def request(self, api_query, url=None):
"""
e.g. {'action': 'query', 'meta': 'userinfo'}. format=json not required
function returns a python dict that resembles the api's json response
"""
api_query['format'] = 'json'
if url is not None:
api_url = url + "/api.... | e.g. {'action': 'query', 'meta': 'userinfo'}. format=json not required
function returns a python dict that resembles the api's json response | Below is the the instruction that describes the task:
### Input:
e.g. {'action': 'query', 'meta': 'userinfo'}. format=json not required
function returns a python dict that resembles the api's json response
### Response:
def request(self, api_query, url=None):
"""
e.g. {'action': 'query', 'm... |
def get_dbg_brk_linux64():
'''
Return the current brk value in the debugged process (only x86_64 Linux)
'''
# TODO this method is so weird, find a unused address to inject code not
# the base address
debugger = get_debugger()
code = b'\x0f\x05' # syscall
rax = debugger.get_reg("rax")... | Return the current brk value in the debugged process (only x86_64 Linux) | Below is the the instruction that describes the task:
### Input:
Return the current brk value in the debugged process (only x86_64 Linux)
### Response:
def get_dbg_brk_linux64():
'''
Return the current brk value in the debugged process (only x86_64 Linux)
'''
# TODO this method is so weird, find a ... |
def psubscribe(self, *args, **kwargs):
"""
Subscribe to channel patterns. Patterns supplied as keyword arguments
expect a pattern name as the key and a callable as the value. A
pattern's callable will be invoked automatically when a message is
received on that pattern rather than... | Subscribe to channel patterns. Patterns supplied as keyword arguments
expect a pattern name as the key and a callable as the value. A
pattern's callable will be invoked automatically when a message is
received on that pattern rather than producing a message via
``listen()``. | Below is the the instruction that describes the task:
### Input:
Subscribe to channel patterns. Patterns supplied as keyword arguments
expect a pattern name as the key and a callable as the value. A
pattern's callable will be invoked automatically when a message is
received on that pattern r... |
def get_logger(name, level=None, fmt=':%(lineno)d: %(message)s'):
"""
Return a logger.
Args:
name (str): name to pass to the logging module.
level (int): level of logging.
fmt (str): format string.
Returns:
logging.Logger: logger from ``l... | Return a logger.
Args:
name (str): name to pass to the logging module.
level (int): level of logging.
fmt (str): format string.
Returns:
logging.Logger: logger from ``logging.getLogger``. | Below is the the instruction that describes the task:
### Input:
Return a logger.
Args:
name (str): name to pass to the logging module.
level (int): level of logging.
fmt (str): format string.
Returns:
logging.Logger: logger from ``logging.getLogger`... |
def align(self, arr):
"""
Align columns, including column headers
"""
if arr is None:
return arr
c_hdrs = self._get_col_hdrs()
if self.show_col_hdr_in_cell:
for hdr in c_hdrs:
arr[hdr] = map(lambda col: ":".join([hdr, str(col)]), ... | Align columns, including column headers | Below is the the instruction that describes the task:
### Input:
Align columns, including column headers
### Response:
def align(self, arr):
"""
Align columns, including column headers
"""
if arr is None:
return arr
c_hdrs = self._get_col_hdrs()
if self... |
def translate_identifiers(self, identifiers, language):
"""
Translate a list of identifiers to item ids. Identifier is a string of
the following form:
<model_prefix>/<model_identifier>
where <model_prefix> is any suffix of database table of the given model
which uniquel... | Translate a list of identifiers to item ids. Identifier is a string of
the following form:
<model_prefix>/<model_identifier>
where <model_prefix> is any suffix of database table of the given model
which uniquely specifies the table, and <model_identifier> is
identifier of the o... | Below is the the instruction that describes the task:
### Input:
Translate a list of identifiers to item ids. Identifier is a string of
the following form:
<model_prefix>/<model_identifier>
where <model_prefix> is any suffix of database table of the given model
which uniquely speci... |
def _set_sftp(self, v, load=False):
"""
Setter method for sftp, mapped from YANG variable /brocade_firmware_rpc/firmware_download/input/sftp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_sftp is considered as a private
method. Backends looking to popula... | Setter method for sftp, mapped from YANG variable /brocade_firmware_rpc/firmware_download/input/sftp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_sftp is considered as a private
method. Backends looking to populate this variable should
do so via calling th... | Below is the the instruction that describes the task:
### Input:
Setter method for sftp, mapped from YANG variable /brocade_firmware_rpc/firmware_download/input/sftp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_sftp is considered as a private
method. Backe... |
def is_installed(self):
"""Return True if the bundle is installed."""
r = self.library.resolve(self.identity.vid)
return r is not None | Return True if the bundle is installed. | Below is the the instruction that describes the task:
### Input:
Return True if the bundle is installed.
### Response:
def is_installed(self):
"""Return True if the bundle is installed."""
r = self.library.resolve(self.identity.vid)
return r is not None |
def gru_cell(input_layer,
state,
num_units,
bias=tf.zeros_initializer(),
weights=None,
phase=prettytensor.Phase.train,
parameter_modifier=parameters.identity):
"""Gated recurrent unit memory cell (GRU).
Args:
input_layer: The input l... | Gated recurrent unit memory cell (GRU).
Args:
input_layer: The input layer.
state: The current state of the network. For GRUs, this is a list with
one element (tensor) of shape [batch, num_units].
num_units: How big is the hidden state.
bias: An initializer for the bias or a Tensor. No bias if ... | Below is the the instruction that describes the task:
### Input:
Gated recurrent unit memory cell (GRU).
Args:
input_layer: The input layer.
state: The current state of the network. For GRUs, this is a list with
one element (tensor) of shape [batch, num_units].
num_units: How big is the hidden ... |
def transpose(self, *args, **kwargs):
"""
Returns a DataFrame with the rows/columns switched.
"""
nv.validate_transpose(args, kwargs)
return self._constructor(
self.values.T, index=self.columns, columns=self.index,
default_fill_value=self._default_fill_val... | Returns a DataFrame with the rows/columns switched. | Below is the the instruction that describes the task:
### Input:
Returns a DataFrame with the rows/columns switched.
### Response:
def transpose(self, *args, **kwargs):
"""
Returns a DataFrame with the rows/columns switched.
"""
nv.validate_transpose(args, kwargs)
return sel... |
def run_as_coroutine(self, stdin, callbacks):
"""
The input 'event loop'.
"""
assert isinstance(callbacks, EventLoopCallbacks)
# Create reader class.
stdin_reader = PosixStdinReader(stdin.fileno())
if self.closed:
raise Exception('Event loop already ... | The input 'event loop'. | Below is the the instruction that describes the task:
### Input:
The input 'event loop'.
### Response:
def run_as_coroutine(self, stdin, callbacks):
"""
The input 'event loop'.
"""
assert isinstance(callbacks, EventLoopCallbacks)
# Create reader class.
stdin_reader ... |
def pprint_vector(vector, limit=False, width=None, indent=0, eng=False, frac_length=3):
r"""
Format a list of numbers (vector) or a Numpy vector for printing.
If the argument **vector** is :code:`None` the string :code:`'None'` is
returned
:param vector: Vector to pretty print or None
:type v... | r"""
Format a list of numbers (vector) or a Numpy vector for printing.
If the argument **vector** is :code:`None` the string :code:`'None'` is
returned
:param vector: Vector to pretty print or None
:type vector: list of integers or floats, Numpy vector or None
:param limit: Flag that indicat... | Below is the the instruction that describes the task:
### Input:
r"""
Format a list of numbers (vector) or a Numpy vector for printing.
If the argument **vector** is :code:`None` the string :code:`'None'` is
returned
:param vector: Vector to pretty print or None
:type vector: list of integers... |
def from_section(cls, stream, section_name='.pic'):
"""Construct a Converter object from the specified section
of the specified binary stream."""
binary = Executable(stream)
section_data = binary.get_section_data(section_name)
return cls(section_data, binary.system) | Construct a Converter object from the specified section
of the specified binary stream. | Below is the the instruction that describes the task:
### Input:
Construct a Converter object from the specified section
of the specified binary stream.
### Response:
def from_section(cls, stream, section_name='.pic'):
"""Construct a Converter object from the specified section
of the specif... |
def get_variable(self, name):
"""
Get a variable used in this tower.
The name should not contain the variable scope prefix of the tower.
When the tower has the same variable scope and name scope, this is equivalent to
:meth:`get_tensor`.
"""
name = get_op_tensor_... | Get a variable used in this tower.
The name should not contain the variable scope prefix of the tower.
When the tower has the same variable scope and name scope, this is equivalent to
:meth:`get_tensor`. | Below is the the instruction that describes the task:
### Input:
Get a variable used in this tower.
The name should not contain the variable scope prefix of the tower.
When the tower has the same variable scope and name scope, this is equivalent to
:meth:`get_tensor`.
### Response:
def get... |
def run_delete_sm(self, tenant_id, fw_dict, is_fw_virt):
"""Runs the delete State Machine.
Goes through every state function until the end or when one state
returns failure.
"""
# Read the current state from the DB
ret = True
serv_obj = self.get_service_obj(tenan... | Runs the delete State Machine.
Goes through every state function until the end or when one state
returns failure. | Below is the the instruction that describes the task:
### Input:
Runs the delete State Machine.
Goes through every state function until the end or when one state
returns failure.
### Response:
def run_delete_sm(self, tenant_id, fw_dict, is_fw_virt):
"""Runs the delete State Machine.
... |
def leave_moderator(self, subreddit):
"""Abdicate moderator status in a subreddit. Use with care.
:param subreddit: The name of the subreddit to leave `status` from.
:returns: the json response from the server.
"""
self.evict(self.config['my_mod_subreddits'])
return sel... | Abdicate moderator status in a subreddit. Use with care.
:param subreddit: The name of the subreddit to leave `status` from.
:returns: the json response from the server. | Below is the the instruction that describes the task:
### Input:
Abdicate moderator status in a subreddit. Use with care.
:param subreddit: The name of the subreddit to leave `status` from.
:returns: the json response from the server.
### Response:
def leave_moderator(self, subreddit):
""... |
def sdram_alloc_as_filelike(self, size, tag=0, x=Required, y=Required,
app_id=Required, clear=False):
"""Like :py:meth:`.sdram_alloc` but returns a :py:class:`file-like
object <.MemoryIO>` which allows safe reading and writing to the block
that is allocated.
... | Like :py:meth:`.sdram_alloc` but returns a :py:class:`file-like
object <.MemoryIO>` which allows safe reading and writing to the block
that is allocated.
Returns
-------
:py:class:`.MemoryIO`
File-like object which allows accessing the newly allocated region
... | Below is the the instruction that describes the task:
### Input:
Like :py:meth:`.sdram_alloc` but returns a :py:class:`file-like
object <.MemoryIO>` which allows safe reading and writing to the block
that is allocated.
Returns
-------
:py:class:`.MemoryIO`
File-l... |
def get_coordinator():
"""Creates a coordinator and returns it."""
workflow_queue = Queue.Queue()
complete_queue = Queue.Queue()
coordinator = WorkflowThread(workflow_queue, complete_queue)
coordinator.register(WorkflowItem, workflow_queue)
return coordinator | Creates a coordinator and returns it. | Below is the the instruction that describes the task:
### Input:
Creates a coordinator and returns it.
### Response:
def get_coordinator():
"""Creates a coordinator and returns it."""
workflow_queue = Queue.Queue()
complete_queue = Queue.Queue()
coordinator = WorkflowThread(workflow_queue, complete... |
def add_tip_labels_to_axes(self):
"""
Add text offset from tips of tree with correction for orientation,
and fixed_order which is usually used in multitree plotting.
"""
# get tip-coords and replace if using fixed_order
xpos = self.ttree.get_tip_coordinates('x')
... | Add text offset from tips of tree with correction for orientation,
and fixed_order which is usually used in multitree plotting. | Below is the the instruction that describes the task:
### Input:
Add text offset from tips of tree with correction for orientation,
and fixed_order which is usually used in multitree plotting.
### Response:
def add_tip_labels_to_axes(self):
"""
Add text offset from tips of tree with correc... |
def update(self, query_name, saved_query_attributes):
"""
Given a dict of attributes to be updated, update only those attributes
in the Saved Query at the resource given by 'query_name'. This will
perform two HTTP requests--one to fetch the query definition, and one
to set the ne... | Given a dict of attributes to be updated, update only those attributes
in the Saved Query at the resource given by 'query_name'. This will
perform two HTTP requests--one to fetch the query definition, and one
to set the new attributes. This method will intend to preserve any
other proper... | Below is the the instruction that describes the task:
### Input:
Given a dict of attributes to be updated, update only those attributes
in the Saved Query at the resource given by 'query_name'. This will
perform two HTTP requests--one to fetch the query definition, and one
to set the new att... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.