code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_minimum_size(self, data):
"""Returns the rotated minimum size."""
size = self.element.get_minimum_size(data)
if self.angle in (RotateLM.NORMAL, RotateLM.UPSIDE_DOWN):
return size
else:
return datatypes.Point(size.y, size.x) | Returns the rotated minimum size. | Below is the the instruction that describes the task:
### Input:
Returns the rotated minimum size.
### Response:
def get_minimum_size(self, data):
"""Returns the rotated minimum size."""
size = self.element.get_minimum_size(data)
if self.angle in (RotateLM.NORMAL, RotateLM.UPSIDE_DOWN):
... |
def _bind(self):
"""
Create socket and bind
"""
credentials = pika.PlainCredentials(self.user, self.password)
params = pika.ConnectionParameters(credentials=credentials,
host=self.server,
v... | Create socket and bind | Below is the the instruction that describes the task:
### Input:
Create socket and bind
### Response:
def _bind(self):
"""
Create socket and bind
"""
credentials = pika.PlainCredentials(self.user, self.password)
params = pika.ConnectionParameters(credentials=credential... |
def read_channels(self, fid):
"""Read channels from an acclaim file."""
bones = [[] for i in self.vertices]
num_channels = 0
for vertex in self.vertices:
num_channels = num_channels + len(vertex.meta['channels'])
lin = self.read_line(fid)
while lin != ':DEGRE... | Read channels from an acclaim file. | Below is the the instruction that describes the task:
### Input:
Read channels from an acclaim file.
### Response:
def read_channels(self, fid):
"""Read channels from an acclaim file."""
bones = [[] for i in self.vertices]
num_channels = 0
for vertex in self.vertices:
nu... |
def get_default_qubit_mapping(program):
"""
Takes a program which contains qubit placeholders and provides a mapping to the integers
0 through N-1.
The output of this function is suitable for input to :py:func:`address_qubits`.
:param program: A program containing qubit placeholders
:return: A... | Takes a program which contains qubit placeholders and provides a mapping to the integers
0 through N-1.
The output of this function is suitable for input to :py:func:`address_qubits`.
:param program: A program containing qubit placeholders
:return: A dictionary mapping qubit placeholder to an addresse... | Below is the the instruction that describes the task:
### Input:
Takes a program which contains qubit placeholders and provides a mapping to the integers
0 through N-1.
The output of this function is suitable for input to :py:func:`address_qubits`.
:param program: A program containing qubit placeholde... |
def parse_log(self, bowtie_log):
"""Parse a bowtie log file.
This is a bowtie log parsing method that populates the
:py:attr:`self.n_reads, self.align_0x, self.align_1x, self.align_mt1x and self.overall_rate` attributes with
data from the log file.
Disclamer: THIS METHOD IS HOR... | Parse a bowtie log file.
This is a bowtie log parsing method that populates the
:py:attr:`self.n_reads, self.align_0x, self.align_1x, self.align_mt1x and self.overall_rate` attributes with
data from the log file.
Disclamer: THIS METHOD IS HORRIBLE BECAUSE THE BOWTIE LOG IS HORRIBLE.
... | Below is the the instruction that describes the task:
### Input:
Parse a bowtie log file.
This is a bowtie log parsing method that populates the
:py:attr:`self.n_reads, self.align_0x, self.align_1x, self.align_mt1x and self.overall_rate` attributes with
data from the log file.
Disc... |
def raw_corpus_rouge1(hypotheses: Iterable[str], references: Iterable[str]) -> float:
"""
Simple wrapper around ROUGE-1 implementation.
:param hypotheses: Hypotheses stream.
:param references: Reference stream.
:return: ROUGE-1 score as float between 0 and 1.
"""
return rouge.rouge_1(hypoth... | Simple wrapper around ROUGE-1 implementation.
:param hypotheses: Hypotheses stream.
:param references: Reference stream.
:return: ROUGE-1 score as float between 0 and 1. | Below is the the instruction that describes the task:
### Input:
Simple wrapper around ROUGE-1 implementation.
:param hypotheses: Hypotheses stream.
:param references: Reference stream.
:return: ROUGE-1 score as float between 0 and 1.
### Response:
def raw_corpus_rouge1(hypotheses: Iterable[str], refe... |
def info_data(self, data_info=None, completo=True, key=None, verbose=True):
"""Show some info."""
def _info_dataframe(data_frame):
if completo:
print('\n', data_frame.info(), '\n', data_frame.describe(), '\n')
print(data_frame.head())
print(data_frame... | Show some info. | Below is the the instruction that describes the task:
### Input:
Show some info.
### Response:
def info_data(self, data_info=None, completo=True, key=None, verbose=True):
"""Show some info."""
def _info_dataframe(data_frame):
if completo:
print('\n', data_frame.info(), ... |
def import_vmdk(self):
"""
All actions necessary to import vmdk (calls s3 upload, and import to aws ec2)
:param vmdk_location: location of vmdk to import. Can be provided as a string, or the result output of fabric
execution
:return:
"""
# Set the inital upload to... | All actions necessary to import vmdk (calls s3 upload, and import to aws ec2)
:param vmdk_location: location of vmdk to import. Can be provided as a string, or the result output of fabric
execution
:return: | Below is the the instruction that describes the task:
### Input:
All actions necessary to import vmdk (calls s3 upload, and import to aws ec2)
:param vmdk_location: location of vmdk to import. Can be provided as a string, or the result output of fabric
execution
:return:
### Response:
def i... |
def topil(self):
"""Returns a PIL.Image version of this Pix"""
from PIL import Image
# Leptonica manages data in words, so it implicitly does an endian
# swap. Tell Pillow about this when it reads the data.
pix = self
if sys.byteorder == 'little':
if self.mo... | Returns a PIL.Image version of this Pix | Below is the the instruction that describes the task:
### Input:
Returns a PIL.Image version of this Pix
### Response:
def topil(self):
"""Returns a PIL.Image version of this Pix"""
from PIL import Image
# Leptonica manages data in words, so it implicitly does an endian
# swap. Te... |
def create_namespaced_ingress(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_ingress # noqa: E501
create an Ingress # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> ... | create_namespaced_ingress # noqa: E501
create an Ingress # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_ingress(namespace, body, async_req=True)
>>> resul... | Below is the the instruction that describes the task:
### Input:
create_namespaced_ingress # noqa: E501
create an Ingress # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_... |
def next_rise(self, latitude, longitude, altitude=None):
"""The next rise of the ISS.
:param latitude: latitude in degrees of location you want iss pass
above
:type latitude: float
:param longitude: longitude in degrees of location you want iss pass
above
:type l... | The next rise of the ISS.
:param latitude: latitude in degrees of location you want iss pass
above
:type latitude: float
:param longitude: longitude in degrees of location you want iss pass
above
:type longitude: float
:param altitude: altitude in meters of locat... | Below is the the instruction that describes the task:
### Input:
The next rise of the ISS.
:param latitude: latitude in degrees of location you want iss pass
above
:type latitude: float
:param longitude: longitude in degrees of location you want iss pass
above
:type ... |
def list_files_courses(self, course_id, content_types=None, include=None, only=None, order=None, search_term=None, sort=None):
"""
List files.
Returns the paginated list of files for the folder or course.
"""
path = {}
data = {}
params = {}
# R... | List files.
Returns the paginated list of files for the folder or course. | Below is the the instruction that describes the task:
### Input:
List files.
Returns the paginated list of files for the folder or course.
### Response:
def list_files_courses(self, course_id, content_types=None, include=None, only=None, order=None, search_term=None, sort=None):
"""
Li... |
def get_string_at_rva(self, rva):
"""Get an ASCII string located at the given address."""
s = self.get_section_by_rva(rva)
if not s:
return self.get_string_from_data(0, self.__data__[rva:rva+MAX_STRING_LENGTH])
return self.get_string_from_data( 0, s.get_data(rva, le... | Get an ASCII string located at the given address. | Below is the the instruction that describes the task:
### Input:
Get an ASCII string located at the given address.
### Response:
def get_string_at_rva(self, rva):
"""Get an ASCII string located at the given address."""
s = self.get_section_by_rva(rva)
if not s:
return self.get_... |
def ols_matrix(A, norm_func=None):
"""
Generate the matrix used to solve OLS regression.
Parameters
----------
A: float array
The design matrix
norm: callable, optional
A normalization function to apply to the matrix, before extracting the
OLS matrix.
Notes
--... | Generate the matrix used to solve OLS regression.
Parameters
----------
A: float array
The design matrix
norm: callable, optional
A normalization function to apply to the matrix, before extracting the
OLS matrix.
Notes
-----
The matrix needed for OLS regression f... | Below is the the instruction that describes the task:
### Input:
Generate the matrix used to solve OLS regression.
Parameters
----------
A: float array
The design matrix
norm: callable, optional
A normalization function to apply to the matrix, before extracting the
OLS mat... |
def joint_distribution(dataframe, rownames, colnames):
"""Joint Distribution Table
- The Continguency Table normalized by the total number of observations
Args:
rownames: the column name or list of columns names that make the keys of the rows
colnames: the column name or list of ... | Joint Distribution Table
- The Continguency Table normalized by the total number of observations
Args:
rownames: the column name or list of columns names that make the keys of the rows
colnames: the column name or list of columns names that make the keys of the columns | Below is the the instruction that describes the task:
### Input:
Joint Distribution Table
- The Continguency Table normalized by the total number of observations
Args:
rownames: the column name or list of columns names that make the keys of the rows
colnames: the column name or l... |
def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]:
"""
Gets column names (that is, database column names) from an SQLAlchemy
ORM class.
"""
colnames = [col.name for col in get_orm_columns(cls)]
return sorted(colnames) if sort else colnames | Gets column names (that is, database column names) from an SQLAlchemy
ORM class. | Below is the the instruction that describes the task:
### Input:
Gets column names (that is, database column names) from an SQLAlchemy
ORM class.
### Response:
def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]:
"""
Gets column names (that is, database column names) from an SQLAlchemy... |
def process_priority(self, process_priority):
"""
Sets the process priority.
:param process_priority: string
"""
log.info('QEMU VM "{name}" [{id}] has set the process priority to {priority}'.format(name=self._name,
... | Sets the process priority.
:param process_priority: string | Below is the the instruction that describes the task:
### Input:
Sets the process priority.
:param process_priority: string
### Response:
def process_priority(self, process_priority):
"""
Sets the process priority.
:param process_priority: string
"""
log.info('QEM... |
def trimsquants(self, col: str, sup: float):
"""
Remove superior quantiles from the dataframe
:param col: column name
:type col: str
:param sup: superior quantile
:type sup: float
:example: ``ds.trimsquants("Col 1", 0.99)``
"""
try:
s... | Remove superior quantiles from the dataframe
:param col: column name
:type col: str
:param sup: superior quantile
:type sup: float
:example: ``ds.trimsquants("Col 1", 0.99)`` | Below is the the instruction that describes the task:
### Input:
Remove superior quantiles from the dataframe
:param col: column name
:type col: str
:param sup: superior quantile
:type sup: float
:example: ``ds.trimsquants("Col 1", 0.99)``
### Response:
def trimsquants(sel... |
def _set_path(self, v, load=False):
"""
Setter method for path, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/path (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_path is considered as a private
method. Backends looking to populate this v... | Setter method for path, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/path (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_path is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._se... | Below is the the instruction that describes the task:
### Input:
Setter method for path, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/path (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_path is considered as a private
method. Backends looki... |
def discharge(self, username, macaroon):
"""Discharge the macarooon for the identity.
Raise a ServerError if an error occurs in the request process.
@param username The logged in user.
@param macaroon The macaroon returned from the charm store.
@return The resulting base64 enco... | Discharge the macarooon for the identity.
Raise a ServerError if an error occurs in the request process.
@param username The logged in user.
@param macaroon The macaroon returned from the charm store.
@return The resulting base64 encoded macaroon.
@raises ServerError when makin... | Below is the the instruction that describes the task:
### Input:
Discharge the macarooon for the identity.
Raise a ServerError if an error occurs in the request process.
@param username The logged in user.
@param macaroon The macaroon returned from the charm store.
@return The resu... |
def load_csv(ctx, model, path, header=None, header_exclude=None, **fmtparams):
"""Load a CSV from a file path.
:param ctx: Anthem context
:param model: Odoo model name or model klass from env
:param path: absolute or relative path to CSV file.
If a relative path is given you must provide a valu... | Load a CSV from a file path.
:param ctx: Anthem context
:param model: Odoo model name or model klass from env
:param path: absolute or relative path to CSV file.
If a relative path is given you must provide a value for
`ODOO_DATA_PATH` in your environment
or set `--odoo-data-path` o... | Below is the the instruction that describes the task:
### Input:
Load a CSV from a file path.
:param ctx: Anthem context
:param model: Odoo model name or model klass from env
:param path: absolute or relative path to CSV file.
If a relative path is given you must provide a value for
`OD... |
def create_record_sets(self, record_set_dicts):
"""Accept list of record_set dicts.
Return list of record_set objects."""
record_set_objects = []
for record_set_dict in record_set_dicts:
# pop removes the 'Enabled' key and tests if True.
if record_set_dict.pop('En... | Accept list of record_set dicts.
Return list of record_set objects. | Below is the the instruction that describes the task:
### Input:
Accept list of record_set dicts.
Return list of record_set objects.
### Response:
def create_record_sets(self, record_set_dicts):
"""Accept list of record_set dicts.
Return list of record_set objects."""
record_set_obj... |
def scopeMatch(assumedScopes, requiredScopeSets):
"""
Take a list of a assumed scopes, and a list of required scope sets on
disjunctive normal form, and check if any of the required scope sets are
satisfied.
Example:
requiredScopeSets = [
["scopeA", "sco... | Take a list of a assumed scopes, and a list of required scope sets on
disjunctive normal form, and check if any of the required scope sets are
satisfied.
Example:
requiredScopeSets = [
["scopeA", "scopeB"],
["scopeC"]
]
In this c... | Below is the the instruction that describes the task:
### Input:
Take a list of a assumed scopes, and a list of required scope sets on
disjunctive normal form, and check if any of the required scope sets are
satisfied.
Example:
requiredScopeSets = [
["scopeA", "... |
def creator(entry, config):
"""Creator function for creating an instance of an Ansible script."""
ansible_playbook = "ansible.playbook.dry.run.see.comment"
ansible_inventory = "ansible.inventory.dry.run.see.comment"
ansible_playbook_content = render(config.script, model=config.model, en... | Creator function for creating an instance of an Ansible script. | Below is the the instruction that describes the task:
### Input:
Creator function for creating an instance of an Ansible script.
### Response:
def creator(entry, config):
"""Creator function for creating an instance of an Ansible script."""
ansible_playbook = "ansible.playbook.dry.run.see.comment"
... |
def option(self, key, value=None, **kwargs):
"""Creates a new option inside a section
Args:
key (str): key of the option
value (str or None): value of the option
**kwargs: are passed to the constructor of :class:`Option`
Returns:
self for chainin... | Creates a new option inside a section
Args:
key (str): key of the option
value (str or None): value of the option
**kwargs: are passed to the constructor of :class:`Option`
Returns:
self for chaining | Below is the the instruction that describes the task:
### Input:
Creates a new option inside a section
Args:
key (str): key of the option
value (str or None): value of the option
**kwargs: are passed to the constructor of :class:`Option`
Returns:
sel... |
def smallest_signed_angle(source, target):
"""Find the smallest angle going from angle `source` to angle `target`."""
dth = target - source
dth = (dth + np.pi) % (2.0 * np.pi) - np.pi
return dth | Find the smallest angle going from angle `source` to angle `target`. | Below is the the instruction that describes the task:
### Input:
Find the smallest angle going from angle `source` to angle `target`.
### Response:
def smallest_signed_angle(source, target):
"""Find the smallest angle going from angle `source` to angle `target`."""
dth = target - source
dth = (dth + np... |
def get_file(path,
dest,
saltenv='base',
makedirs=False,
template=None,
gzip=None,
**kwargs):
'''
.. versionchanged:: 2018.3.0
``dest`` can now be a directory
Used to get a single file from the salt master
CLI Exampl... | .. versionchanged:: 2018.3.0
``dest`` can now be a directory
Used to get a single file from the salt master
CLI Example:
.. code-block:: bash
salt '*' cp.get_file salt://path/to/file /minion/dest
Template rendering can be enabled on both the source and destination file
names lik... | Below is the the instruction that describes the task:
### Input:
.. versionchanged:: 2018.3.0
``dest`` can now be a directory
Used to get a single file from the salt master
CLI Example:
.. code-block:: bash
salt '*' cp.get_file salt://path/to/file /minion/dest
Template rendering... |
def get_available_languages(self, obj):
"""
Fetching the available languages as queryset.
"""
if obj:
return obj.get_available_languages()
else:
return self.model._parler_meta.root_model.objects.none() | Fetching the available languages as queryset. | Below is the the instruction that describes the task:
### Input:
Fetching the available languages as queryset.
### Response:
def get_available_languages(self, obj):
"""
Fetching the available languages as queryset.
"""
if obj:
return obj.get_available_languages()
... |
def box_ids(creds: dict, cred_ids: list = None) -> dict:
"""
Given a credentials structure and an optional list of credential identifiers
(aka wallet cred-ids, referents; specify None to include all), return dict mapping each
credential identifier to a box ids structure (i.e., a dict specifying its corr... | Given a credentials structure and an optional list of credential identifiers
(aka wallet cred-ids, referents; specify None to include all), return dict mapping each
credential identifier to a box ids structure (i.e., a dict specifying its corresponding
schema identifier, credential definition identifier, an... | Below is the the instruction that describes the task:
### Input:
Given a credentials structure and an optional list of credential identifiers
(aka wallet cred-ids, referents; specify None to include all), return dict mapping each
credential identifier to a box ids structure (i.e., a dict specifying its corr... |
def run(self, *args):
"""Endit profile information."""
uuid, kwargs = self.__parse_arguments(*args)
code = self.edit_profile(uuid, **kwargs)
return code | Endit profile information. | Below is the the instruction that describes the task:
### Input:
Endit profile information.
### Response:
def run(self, *args):
"""Endit profile information."""
uuid, kwargs = self.__parse_arguments(*args)
code = self.edit_profile(uuid, **kwargs)
return code |
def previous(self, day_of_week=None):
"""
Modify to the previous occurrence of a given day of the week.
If no day_of_week is provided, modify to the previous occurrence
of the current day of the week. Use the supplied consts
to indicate the desired day_of_week, ex. pendulum.MOND... | Modify to the previous occurrence of a given day of the week.
If no day_of_week is provided, modify to the previous occurrence
of the current day of the week. Use the supplied consts
to indicate the desired day_of_week, ex. pendulum.MONDAY.
:param day_of_week: The previous day of week ... | Below is the the instruction that describes the task:
### Input:
Modify to the previous occurrence of a given day of the week.
If no day_of_week is provided, modify to the previous occurrence
of the current day of the week. Use the supplied consts
to indicate the desired day_of_week, ex. pe... |
def matrix_decomp(self, cache=None):
"""Compute a Hermitian eigenbasis decomposition of the matrix.
Parameters
----------
cache : bool or None, optional
If ``True``, store the decomposition internally. For None,
the ``cache_mat_decomp`` from class initialization ... | Compute a Hermitian eigenbasis decomposition of the matrix.
Parameters
----------
cache : bool or None, optional
If ``True``, store the decomposition internally. For None,
the ``cache_mat_decomp`` from class initialization is used.
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
Compute a Hermitian eigenbasis decomposition of the matrix.
Parameters
----------
cache : bool or None, optional
If ``True``, store the decomposition internally. For None,
the ``cache_mat_decomp`` from ... |
def diff_sizes(a, b, progressbar=None):
"""Return list of tuples where sizes differ.
Tuple structure:
(identifier, size in a, size in b)
Assumes list of identifiers in a and b are identical.
:param a: first :class:`dtoolcore.DataSet`
:param b: second :class:`dtoolcore.DataSet`
:returns: l... | Return list of tuples where sizes differ.
Tuple structure:
(identifier, size in a, size in b)
Assumes list of identifiers in a and b are identical.
:param a: first :class:`dtoolcore.DataSet`
:param b: second :class:`dtoolcore.DataSet`
:returns: list of tuples for all items with different size... | Below is the the instruction that describes the task:
### Input:
Return list of tuples where sizes differ.
Tuple structure:
(identifier, size in a, size in b)
Assumes list of identifiers in a and b are identical.
:param a: first :class:`dtoolcore.DataSet`
:param b: second :class:`dtoolcore.Da... |
def nearest_base(cls, bases):
'''Returns the closest ancestor to cls in bases.
'''
if cls in bases:
return cls
dists = {base: index(mro(cls), base) for base in bases}
dists2 = {dist: base for base, dist in dists.items() if dist is not None}
if not dists2:
return None
return ... | Returns the closest ancestor to cls in bases. | Below is the the instruction that describes the task:
### Input:
Returns the closest ancestor to cls in bases.
### Response:
def nearest_base(cls, bases):
'''Returns the closest ancestor to cls in bases.
'''
if cls in bases:
return cls
dists = {base: index(mro(cls), base) for base in bases... |
def _responsive_sleep(self, seconds, wait_log_interval=0, wait_reason=''):
"""When there is litte work to do, the queuing thread sleeps a lot.
It can't sleep for too long without checking for the quit flag and/or
logging about why it is sleeping.
parameters:
seconds - the nu... | When there is litte work to do, the queuing thread sleeps a lot.
It can't sleep for too long without checking for the quit flag and/or
logging about why it is sleeping.
parameters:
seconds - the number of seconds to sleep
wait_log_interval - while sleeping, it is helpful... | Below is the the instruction that describes the task:
### Input:
When there is litte work to do, the queuing thread sleeps a lot.
It can't sleep for too long without checking for the quit flag and/or
logging about why it is sleeping.
parameters:
seconds - the number of seconds t... |
def repo_exists(self, auth, username, repo_name):
"""
Returns whether a repository with name ``repo_name`` owned by the user with username ``username`` exists.
:param auth.Authentication auth: authentication object
:param str username: username of owner of repository
:param str ... | Returns whether a repository with name ``repo_name`` owned by the user with username ``username`` exists.
:param auth.Authentication auth: authentication object
:param str username: username of owner of repository
:param str repo_name: name of repository
:return: whether the repository ... | Below is the the instruction that describes the task:
### Input:
Returns whether a repository with name ``repo_name`` owned by the user with username ``username`` exists.
:param auth.Authentication auth: authentication object
:param str username: username of owner of repository
:param str r... |
def loadUnStructuredGrid(filename): # not tested
"""Load a ``vtkunStructuredGrid`` object from file and return a ``Actor(vtkActor)`` object."""
reader = vtk.vtkUnstructuredGridReader()
reader.SetFileName(filename)
reader.Update()
gf = vtk.vtkUnstructuredGridGeometryFilter()
gf.SetInputConnectio... | Load a ``vtkunStructuredGrid`` object from file and return a ``Actor(vtkActor)`` object. | Below is the the instruction that describes the task:
### Input:
Load a ``vtkunStructuredGrid`` object from file and return a ``Actor(vtkActor)`` object.
### Response:
def loadUnStructuredGrid(filename): # not tested
"""Load a ``vtkunStructuredGrid`` object from file and return a ``Actor(vtkActor)`` object.""... |
def _create_parser(self, html_parser, current_url):
"""
Create the tinycss stylesheet.
:param html_parser: The HTML parser.
:type html_parser: hatemile.util.html.htmldomparser.HTMLDOMParser
:param current_url: The current URL of page.
:type current_url: str
"""
... | Create the tinycss stylesheet.
:param html_parser: The HTML parser.
:type html_parser: hatemile.util.html.htmldomparser.HTMLDOMParser
:param current_url: The current URL of page.
:type current_url: str | Below is the the instruction that describes the task:
### Input:
Create the tinycss stylesheet.
:param html_parser: The HTML parser.
:type html_parser: hatemile.util.html.htmldomparser.HTMLDOMParser
:param current_url: The current URL of page.
:type current_url: str
### Response:
d... |
def os_tree(directory, enable_scandir=False):
"""
Return a directories contents as a dictionary hierarchy.
.. code:: python
reusables.os_tree(".")
# {'doc': {'build': {'doctrees': {},
# 'html': {'_sources': {}, '_static': {}}},
# 'source': {}},
... | Return a directories contents as a dictionary hierarchy.
.. code:: python
reusables.os_tree(".")
# {'doc': {'build': {'doctrees': {},
# 'html': {'_sources': {}, '_static': {}}},
# 'source': {}},
# 'reusables': {'__pycache__': {}},
# 'test... | Below is the the instruction that describes the task:
### Input:
Return a directories contents as a dictionary hierarchy.
.. code:: python
reusables.os_tree(".")
# {'doc': {'build': {'doctrees': {},
# 'html': {'_sources': {}, '_static': {}}},
# 'source... |
def create(cls, name, user_group=None, activation_date=None,
expiration_date=None, comment=None):
"""
Create an internal user.
Add a user example::
InternalUser.create(name='goog', comment='my comment')
:param str name: name of user that is disp... | Create an internal user.
Add a user example::
InternalUser.create(name='goog', comment='my comment')
:param str name: name of user that is displayed in SMC
:param list(str,InternalUserGroup) user_group: internal user groups
which to add this use... | Below is the the instruction that describes the task:
### Input:
Create an internal user.
Add a user example::
InternalUser.create(name='goog', comment='my comment')
:param str name: name of user that is displayed in SMC
:param list(str,InternalUserGrou... |
def save(self):
"""
Save the entire configuration files
"""
self.projects.save()
self.experiments.save()
safe_dump(self.global_config, self._globals_file,
default_flow_style=False) | Save the entire configuration files | Below is the the instruction that describes the task:
### Input:
Save the entire configuration files
### Response:
def save(self):
"""
Save the entire configuration files
"""
self.projects.save()
self.experiments.save()
safe_dump(self.global_config, self._globals_fil... |
def _resolve_dtype(data_type):
"""Retrieve the corresponding NumPy's `dtype` for a given data type."""
if isinstance(data_type, _FIXED_ATOMIC):
out = _get_atomic_dtype(data_type)
elif isinstance(data_type, _FLEXIBLE_ATOMIC):
out = (_get_atomic_dtype(data_type), data_type.length)
elif isi... | Retrieve the corresponding NumPy's `dtype` for a given data type. | Below is the the instruction that describes the task:
### Input:
Retrieve the corresponding NumPy's `dtype` for a given data type.
### Response:
def _resolve_dtype(data_type):
"""Retrieve the corresponding NumPy's `dtype` for a given data type."""
if isinstance(data_type, _FIXED_ATOMIC):
out = _get... |
def to_workspace_value(self, result, assets):
"""
Called with a column of the result of a pipeline. This needs to put
the data into a format that can be used in a workspace to continue
doing computations.
Parameters
----------
result : pd.Series
A mul... | Called with a column of the result of a pipeline. This needs to put
the data into a format that can be used in a workspace to continue
doing computations.
Parameters
----------
result : pd.Series
A multiindexed series with (dates, assets) whose values are the
... | Below is the the instruction that describes the task:
### Input:
Called with a column of the result of a pipeline. This needs to put
the data into a format that can be used in a workspace to continue
doing computations.
Parameters
----------
result : pd.Series
A ... |
def observed_data_to_xarray(self):
"""Convert observed data to xarray."""
if self.observed is None:
return None
observed_data = {}
if isinstance(self.observed, self.tf.Tensor):
with self.tf.Session() as sess:
vals = sess.run(self.observed,... | Convert observed data to xarray. | Below is the the instruction that describes the task:
### Input:
Convert observed data to xarray.
### Response:
def observed_data_to_xarray(self):
"""Convert observed data to xarray."""
if self.observed is None:
return None
observed_data = {}
if isinstance(self.ob... |
def create_app(*, debug=False, threads=1, bigchaindb_factory=None):
"""Return an instance of the Flask application.
Args:
debug (bool): a flag to activate the debug mode for the app
(default: False).
threads (int): number of threads to use
Return:
an instance of the Flas... | Return an instance of the Flask application.
Args:
debug (bool): a flag to activate the debug mode for the app
(default: False).
threads (int): number of threads to use
Return:
an instance of the Flask application. | Below is the the instruction that describes the task:
### Input:
Return an instance of the Flask application.
Args:
debug (bool): a flag to activate the debug mode for the app
(default: False).
threads (int): number of threads to use
Return:
an instance of the Flask appl... |
def get_signature(payment_request):
"""
Returns the signature for the transaction.
To compute the signature, first you have to get the value of all
the fields that starts by 'vads_', ordering them alphabetically.
All the values are separated by the '+' character. Then you add
the value of the p... | Returns the signature for the transaction.
To compute the signature, first you have to get the value of all
the fields that starts by 'vads_', ordering them alphabetically.
All the values are separated by the '+' character. Then you add
the value of the payzen certificate.
Finaly you hash the strin... | Below is the the instruction that describes the task:
### Input:
Returns the signature for the transaction.
To compute the signature, first you have to get the value of all
the fields that starts by 'vads_', ordering them alphabetically.
All the values are separated by the '+' character. Then you add
... |
def cable_from_html(html, reference_id=None):
"""\
Returns a cable from the provided HTML page.
`html`
The HTML page of the cable
`reference_id`
The reference identifier of the cable. If the reference_id is ``None``
this function tries to detect it.
"""
if not html:
... | \
Returns a cable from the provided HTML page.
`html`
The HTML page of the cable
`reference_id`
The reference identifier of the cable. If the reference_id is ``None``
this function tries to detect it. | Below is the the instruction that describes the task:
### Input:
\
Returns a cable from the provided HTML page.
`html`
The HTML page of the cable
`reference_id`
The reference identifier of the cable. If the reference_id is ``None``
this function tries to detect it.
### Respo... |
def render_arrow(self, label, start, end, direction, i):
"""Render individual arrow.
label (unicode): Dependency label.
start (int): Index of start word.
end (int): Index of end word.
direction (unicode): Arrow direction, 'left' or 'right'.
i (int): Unique ID, typically ... | Render individual arrow.
label (unicode): Dependency label.
start (int): Index of start word.
end (int): Index of end word.
direction (unicode): Arrow direction, 'left' or 'right'.
i (int): Unique ID, typically arrow index.
RETURNS (unicode): Rendered SVG markup. | Below is the the instruction that describes the task:
### Input:
Render individual arrow.
label (unicode): Dependency label.
start (int): Index of start word.
end (int): Index of end word.
direction (unicode): Arrow direction, 'left' or 'right'.
i (int): Unique ID, typically... |
def list_tables(self):
"""
Runs the ``\\dt`` command and returns a list of column values with
information about all tables in the database.
"""
lines = output_lines(self.exec_psql('\\dt'))
return [line.split('|') for line in lines] | Runs the ``\\dt`` command and returns a list of column values with
information about all tables in the database. | Below is the the instruction that describes the task:
### Input:
Runs the ``\\dt`` command and returns a list of column values with
information about all tables in the database.
### Response:
def list_tables(self):
"""
Runs the ``\\dt`` command and returns a list of column values with
... |
def create_index(self, table_name, attr_name):
"""
:param str table_name:
Table name that contains the attribute to be indexed.
:param str attr_name: Attribute name to create index.
:raises IOError: |raises_write_permission|
:raises simplesqlite.NullDatabaseConnection... | :param str table_name:
Table name that contains the attribute to be indexed.
:param str attr_name: Attribute name to create index.
:raises IOError: |raises_write_permission|
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simple... | Below is the the instruction that describes the task:
### Input:
:param str table_name:
Table name that contains the attribute to be indexed.
:param str attr_name: Attribute name to create index.
:raises IOError: |raises_write_permission|
:raises simplesqlite.NullDatabaseConnecti... |
def _oai_to_xml(marc_oai): # TODO: move this to MARC XML parser?
"""
Convert OAI to MARC XML.
Args:
marc_oai (str): String with either OAI or MARC XML.
Returns:
str: String with MARC XML.
"""
record = MARCXMLRecord(marc_oai)
record.oai_marc = False
return record.to_XM... | Convert OAI to MARC XML.
Args:
marc_oai (str): String with either OAI or MARC XML.
Returns:
str: String with MARC XML. | Below is the the instruction that describes the task:
### Input:
Convert OAI to MARC XML.
Args:
marc_oai (str): String with either OAI or MARC XML.
Returns:
str: String with MARC XML.
### Response:
def _oai_to_xml(marc_oai): # TODO: move this to MARC XML parser?
"""
Convert OAI t... |
def get_connection(self, address):
"""Create or retrieve a muxed connection
Arguments:
address -- a peer endpoint in IPv4/v6 address format; None refers
to the connection for unknown peers
Return:
a bound, connected datagram socket instance
"""
... | Create or retrieve a muxed connection
Arguments:
address -- a peer endpoint in IPv4/v6 address format; None refers
to the connection for unknown peers
Return:
a bound, connected datagram socket instance | Below is the the instruction that describes the task:
### Input:
Create or retrieve a muxed connection
Arguments:
address -- a peer endpoint in IPv4/v6 address format; None refers
to the connection for unknown peers
Return:
a bound, connected datagram socket inst... |
def http_auth(self):
"""
Returns ``True`` if valid http auth credentials are found in the
request header.
"""
if 'HTTP_AUTHORIZATION' in self.request.META.keys():
authmeth, auth = self.request.META['HTTP_AUTHORIZATION'].split(
' ', 1)
if a... | Returns ``True`` if valid http auth credentials are found in the
request header. | Below is the the instruction that describes the task:
### Input:
Returns ``True`` if valid http auth credentials are found in the
request header.
### Response:
def http_auth(self):
"""
Returns ``True`` if valid http auth credentials are found in the
request header.
"""
... |
def process(self, tup):
"""Process steps:
1. Stream third positional value from input into Kafka topic.
"""
status_seq = self.iter_using_shelf(tup.values[2], self.tweet_shelf)
# This could be more efficient by passing the result from twitter
# straight through to the pro... | Process steps:
1. Stream third positional value from input into Kafka topic. | Below is the the instruction that describes the task:
### Input:
Process steps:
1. Stream third positional value from input into Kafka topic.
### Response:
def process(self, tup):
"""Process steps:
1. Stream third positional value from input into Kafka topic.
"""
status_se... |
def _from_dict(cls, _dict):
"""Initialize a Face object from a json dictionary."""
args = {}
if 'age' in _dict:
args['age'] = FaceAge._from_dict(_dict.get('age'))
if 'gender' in _dict:
args['gender'] = FaceGender._from_dict(_dict.get('gender'))
if 'face_lo... | Initialize a Face object from a json dictionary. | Below is the the instruction that describes the task:
### Input:
Initialize a Face object from a json dictionary.
### Response:
def _from_dict(cls, _dict):
"""Initialize a Face object from a json dictionary."""
args = {}
if 'age' in _dict:
args['age'] = FaceAge._from_dict(_dict.... |
def last_instr(self, start, end, instr, target=None, exact=True):
"""
Find the last <instr> in the block from start to end.
<instr> is any python bytecode instruction or a list of opcodes
If <instr> is an opcode with a target (like a jump), a target
destination can be specified w... | Find the last <instr> in the block from start to end.
<instr> is any python bytecode instruction or a list of opcodes
If <instr> is an opcode with a target (like a jump), a target
destination can be specified which must match precisely if exact
is True, or if exact is False, the instruct... | Below is the the instruction that describes the task:
### Input:
Find the last <instr> in the block from start to end.
<instr> is any python bytecode instruction or a list of opcodes
If <instr> is an opcode with a target (like a jump), a target
destination can be specified which must match p... |
def align_rasters(raster, alignraster, how=np.ma.mean, cxsize=None, cysize=None, masked=False):
'''
Align two rasters so that data overlaps by geographical location
Usage:
(alignedraster_o, alignedraster_a, geot_a) = AlignRasters(raster, alignraster, how=np.mean)
where:
raster: string with ... | Align two rasters so that data overlaps by geographical location
Usage:
(alignedraster_o, alignedraster_a, geot_a) = AlignRasters(raster, alignraster, how=np.mean)
where:
raster: string with location of raster to be aligned
alignraster: string with location of raster to which raster will b... | Below is the the instruction that describes the task:
### Input:
Align two rasters so that data overlaps by geographical location
Usage:
(alignedraster_o, alignedraster_a, geot_a) = AlignRasters(raster, alignraster, how=np.mean)
where:
raster: string with location of raster to be aligned
... |
def files(self, *args, **kwargs):
""" D.files() -> List of the files in this directory.
The elements of the list are Path objects.
This does not walk into subdirectories (see :meth:`walkfiles`).
Accepts parameters to :meth:`listdir`.
"""
return [p for p in self.listdir... | D.files() -> List of the files in this directory.
The elements of the list are Path objects.
This does not walk into subdirectories (see :meth:`walkfiles`).
Accepts parameters to :meth:`listdir`. | Below is the the instruction that describes the task:
### Input:
D.files() -> List of the files in this directory.
The elements of the list are Path objects.
This does not walk into subdirectories (see :meth:`walkfiles`).
Accepts parameters to :meth:`listdir`.
### Response:
def files(self... |
def groups_pools_getGroups():
"""Get a list of groups the auth'd user can post photos to."""
method = 'flickr.groups.pools.getGroups'
data = _doget(method, auth=True)
groups = []
if isinstance(data.rsp.groups.group, list):
for group in data.rsp.groups.group:
groups.append(Group(g... | Get a list of groups the auth'd user can post photos to. | Below is the the instruction that describes the task:
### Input:
Get a list of groups the auth'd user can post photos to.
### Response:
def groups_pools_getGroups():
"""Get a list of groups the auth'd user can post photos to."""
method = 'flickr.groups.pools.getGroups'
data = _doget(method, auth=True)
... |
def receive(self, path, diffTo, diffFrom):
""" Receive a btrfs diff. """
diff = self.toObj.diff(diffTo, diffFrom)
self._open(self.butterStore.receive(diff, [path, ])) | Receive a btrfs diff. | Below is the the instruction that describes the task:
### Input:
Receive a btrfs diff.
### Response:
def receive(self, path, diffTo, diffFrom):
""" Receive a btrfs diff. """
diff = self.toObj.diff(diffTo, diffFrom)
self._open(self.butterStore.receive(diff, [path, ])) |
def reduce(self, mapped_props, aggregated, value_type, visitor):
"""This reduction is called to combine the mapped slot and collection
item values into a single value for return.
The default implementation tries to behave naturally; you'll almost
always get a dict back when mapping over... | This reduction is called to combine the mapped slot and collection
item values into a single value for return.
The default implementation tries to behave naturally; you'll almost
always get a dict back when mapping over a record, and list or some
other collection when mapping over colle... | Below is the the instruction that describes the task:
### Input:
This reduction is called to combine the mapped slot and collection
item values into a single value for return.
The default implementation tries to behave naturally; you'll almost
always get a dict back when mapping over a reco... |
def send_PointerEvent(self, x, y, buttonmask=0):
"""Indicates either pointer movement or a pointer button press or
release. The pointer is now at (x-position, y-position),
and the current state of buttons 1 to 8 are represented by
bits 0 to 7 of button-mask respectively, 0 meani... | Indicates either pointer movement or a pointer button press or
release. The pointer is now at (x-position, y-position),
and the current state of buttons 1 to 8 are represented by
bits 0 to 7 of button-mask respectively, 0 meaning up, 1
meaning down (pressed). | Below is the the instruction that describes the task:
### Input:
Indicates either pointer movement or a pointer button press or
release. The pointer is now at (x-position, y-position),
and the current state of buttons 1 to 8 are represented by
bits 0 to 7 of button-mask respectively... |
def read_table(source, tablename=None, **kwargs):
"""Read a `Table` from one or more LIGO_LW XML documents
source : `file`, `str`, :class:`~ligo.lw.ligolw.Document`, `list`
one or more open files, file paths, or LIGO_LW `Document` objects
tablename : `str`, optional
the `Name` of the relev... | Read a `Table` from one or more LIGO_LW XML documents
source : `file`, `str`, :class:`~ligo.lw.ligolw.Document`, `list`
one or more open files, file paths, or LIGO_LW `Document` objects
tablename : `str`, optional
the `Name` of the relevant `Table` to read, if not given a table will
be... | Below is the the instruction that describes the task:
### Input:
Read a `Table` from one or more LIGO_LW XML documents
source : `file`, `str`, :class:`~ligo.lw.ligolw.Document`, `list`
one or more open files, file paths, or LIGO_LW `Document` objects
tablename : `str`, optional
the `Name` ... |
def main(nodes, edges):
"""Generate a random graph, submit jobs, then validate that the
dependency order was enforced.
Finally, plot the graph, with time on the x-axis, and
in-degree on the y (just for spread). All arrows must
point at least slightly to the right if the graph is valid.
"""
... | Generate a random graph, submit jobs, then validate that the
dependency order was enforced.
Finally, plot the graph, with time on the x-axis, and
in-degree on the y (just for spread). All arrows must
point at least slightly to the right if the graph is valid. | Below is the the instruction that describes the task:
### Input:
Generate a random graph, submit jobs, then validate that the
dependency order was enforced.
Finally, plot the graph, with time on the x-axis, and
in-degree on the y (just for spread). All arrows must
point at least slightly to the rig... |
def analysis_search(self, query):
"""
Lists the webids of the analyses that match the given query.
Searches in MD5, SHA1, SHA256, filename, cookbook name, comment, url and report id.
"""
response = self._post(self.apiurl + "/v2/analysis/search", data={'apikey': self.apikey, 'q':... | Lists the webids of the analyses that match the given query.
Searches in MD5, SHA1, SHA256, filename, cookbook name, comment, url and report id. | Below is the the instruction that describes the task:
### Input:
Lists the webids of the analyses that match the given query.
Searches in MD5, SHA1, SHA256, filename, cookbook name, comment, url and report id.
### Response:
def analysis_search(self, query):
"""
Lists the webids of the anal... |
def format(self, record):
"""Apply little arrow and colors to the record.
Arrow and colors are only applied to sphinxcontrib.versioning log statements.
:param logging.LogRecord record: The log record object to log.
"""
formatted = super(ColorFormatter, self).format(record)
... | Apply little arrow and colors to the record.
Arrow and colors are only applied to sphinxcontrib.versioning log statements.
:param logging.LogRecord record: The log record object to log. | Below is the the instruction that describes the task:
### Input:
Apply little arrow and colors to the record.
Arrow and colors are only applied to sphinxcontrib.versioning log statements.
:param logging.LogRecord record: The log record object to log.
### Response:
def format(self, record):
... |
def get_google_service(service_type=None,version=None):
'''
get_url will use the requests library to get a url
:param service_type: the service to get (default is storage)
:param version: version to use (default is v1)
'''
if service_type == None:
service_type = "storage"
if version ... | get_url will use the requests library to get a url
:param service_type: the service to get (default is storage)
:param version: version to use (default is v1) | Below is the the instruction that describes the task:
### Input:
get_url will use the requests library to get a url
:param service_type: the service to get (default is storage)
:param version: version to use (default is v1)
### Response:
def get_google_service(service_type=None,version=None):
'''
g... |
def default_middlewares(web3):
"""
List the default middlewares for the request manager.
Leaving ens unspecified will prevent the middleware from resolving names.
"""
return [
(request_parameter_normalizer, 'request_param_normalizer'),
(gas_price_strategy_... | List the default middlewares for the request manager.
Leaving ens unspecified will prevent the middleware from resolving names. | Below is the the instruction that describes the task:
### Input:
List the default middlewares for the request manager.
Leaving ens unspecified will prevent the middleware from resolving names.
### Response:
def default_middlewares(web3):
"""
List the default middlewares for the request mana... |
def render(self, name, value, attrs=None, multi=False, renderer=None):
"""
Django <= 1.10 variant.
"""
DJANGO_111_OR_UP = (VERSION[0] == 1 and VERSION[1] >= 11) or (
VERSION[0] >= 2
)
if DJANGO_111_OR_UP:
return super(DynamicRawIDWidget, self).rend... | Django <= 1.10 variant. | Below is the the instruction that describes the task:
### Input:
Django <= 1.10 variant.
### Response:
def render(self, name, value, attrs=None, multi=False, renderer=None):
"""
Django <= 1.10 variant.
"""
DJANGO_111_OR_UP = (VERSION[0] == 1 and VERSION[1] >= 11) or (
VE... |
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.
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
... | 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 observe(self, amount):
"""Observe the given amount."""
self._count.inc(1)
self._sum.inc(amount) | Observe the given amount. | Below is the the instruction that describes the task:
### Input:
Observe the given amount.
### Response:
def observe(self, amount):
"""Observe the given amount."""
self._count.inc(1)
self._sum.inc(amount) |
def _EncodeParameters(self, parameters):
"""
Return a string in key=value&key=value form.
:param parameters: A dict of (key, value) tuples, where value is encoded as specified by self._encoding
:return:A URL-encoded string in "key=value&key=value" form
"""
if parameters ... | Return a string in key=value&key=value form.
:param parameters: A dict of (key, value) tuples, where value is encoded as specified by self._encoding
:return:A URL-encoded string in "key=value&key=value" form | Below is the the instruction that describes the task:
### Input:
Return a string in key=value&key=value form.
:param parameters: A dict of (key, value) tuples, where value is encoded as specified by self._encoding
:return:A URL-encoded string in "key=value&key=value" form
### Response:
def _EncodeP... |
def addImage(self,name,rsrc):
"""
Adds an image to the internal registry.
``rsrc`` should be a 2-tuple of ``(resource_name,category)``\ .
"""
self.imgs[name]=self.widget.peng.resourceMgr.getTex(*rsrc) | Adds an image to the internal registry.
``rsrc`` should be a 2-tuple of ``(resource_name,category)``\ . | Below is the the instruction that describes the task:
### Input:
Adds an image to the internal registry.
``rsrc`` should be a 2-tuple of ``(resource_name,category)``\ .
### Response:
def addImage(self,name,rsrc):
"""
Adds an image to the internal registry.
``rsrc``... |
def make_ctypes_convertor(self, _flags):
"""
Fix clang types to ctypes convertion for this parsing isntance.
Some architecture dependent size types ahve to be changed if the target
architecture is not the same as local
"""
tu = util.get_tu('''
typedef short short_t;
typed... | Fix clang types to ctypes convertion for this parsing isntance.
Some architecture dependent size types ahve to be changed if the target
architecture is not the same as local | Below is the the instruction that describes the task:
### Input:
Fix clang types to ctypes convertion for this parsing isntance.
Some architecture dependent size types ahve to be changed if the target
architecture is not the same as local
### Response:
def make_ctypes_convertor(self, _flags):
... |
def get_description(self):
"""
Tries to get WF description from 'collabration' or 'process' or 'pariticipant'
Returns str: WF description
"""
paths = ['bpmn:collaboration/bpmn:participant/bpmn:documentation',
'bpmn:collaboration/bpmn:documentation',
... | Tries to get WF description from 'collabration' or 'process' or 'pariticipant'
Returns str: WF description | Below is the the instruction that describes the task:
### Input:
Tries to get WF description from 'collabration' or 'process' or 'pariticipant'
Returns str: WF description
### Response:
def get_description(self):
"""
Tries to get WF description from 'collabration' or 'process' or 'paritici... |
def file_crc32(filePath):
"""计算文件的crc32检验码:
Args:
filePath: 待计算校验码的文件路径
Returns:
文件内容的crc32校验码。
"""
crc = 0
with open(filePath, 'rb') as f:
for block in _file_iter(f, _BLOCK_SIZE):
crc = binascii.crc32(block, crc) & 0xFFFFFFFF
return crc | 计算文件的crc32检验码:
Args:
filePath: 待计算校验码的文件路径
Returns:
文件内容的crc32校验码。 | Below is the the instruction that describes the task:
### Input:
计算文件的crc32检验码:
Args:
filePath: 待计算校验码的文件路径
Returns:
文件内容的crc32校验码。
### Response:
def file_crc32(filePath):
"""计算文件的crc32检验码:
Args:
filePath: 待计算校验码的文件路径
Returns:
文件内容的crc32校验码。
"""
crc =... |
def remote_archive(class_obj: type) -> type:
"""
Decorator to annotate the RemoteArchive class. Registers the decorated class
as the RemoteArchive known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _remote_archive_resource_type
_remote_archive_resource_type... | Decorator to annotate the RemoteArchive class. Registers the decorated class
as the RemoteArchive known type. | Below is the the instruction that describes the task:
### Input:
Decorator to annotate the RemoteArchive class. Registers the decorated class
as the RemoteArchive known type.
### Response:
def remote_archive(class_obj: type) -> type:
"""
Decorator to annotate the RemoteArchive class. Registers the deco... |
def add_state(self, state_name, initial_state, batch_size=None):
"""Adds a state to the state saver.
Args:
state_name: The name of this state.
initial_state: The initial state vector. Only zeros are supported.
batch_size: The batch_size or None for unknown.
"""
state_shape = initial_s... | Adds a state to the state saver.
Args:
state_name: The name of this state.
initial_state: The initial state vector. Only zeros are supported.
batch_size: The batch_size or None for unknown. | Below is the the instruction that describes the task:
### Input:
Adds a state to the state saver.
Args:
state_name: The name of this state.
initial_state: The initial state vector. Only zeros are supported.
batch_size: The batch_size or None for unknown.
### Response:
def add_state(self, sta... |
def validate_name(self, name):
"""
Can the name be used as a python module or package?
Raises ``ValueError`` if the name is invalid.
:param name: the name to check
"""
if not name:
raise ValueError("Name cannot be empty")
# Can the name be ... | Can the name be used as a python module or package?
Raises ``ValueError`` if the name is invalid.
:param name: the name to check | Below is the the instruction that describes the task:
### Input:
Can the name be used as a python module or package?
Raises ``ValueError`` if the name is invalid.
:param name: the name to check
### Response:
def validate_name(self, name):
"""
Can the name be used as a python m... |
def setup(app):
''' Required Sphinx extension setup function. '''
app.add_node(bokeh_palette_group, html=(html_visit_bokeh_palette_group, None))
app.add_directive('bokeh-palette-group', BokehPaletteGroupDirective) | Required Sphinx extension setup function. | Below is the the instruction that describes the task:
### Input:
Required Sphinx extension setup function.
### Response:
def setup(app):
''' Required Sphinx extension setup function. '''
app.add_node(bokeh_palette_group, html=(html_visit_bokeh_palette_group, None))
app.add_directive('bokeh-palette-grou... |
def _update_state(self, vals):
"""
Takes as input a list or tuple of two elements. First the
value returned by incrementing by 'stepsize' followed by the
value returned after a 'stepsize' decrement.
"""
self._steps_complete += 1
if self._steps_complete == self.max... | Takes as input a list or tuple of two elements. First the
value returned by incrementing by 'stepsize' followed by the
value returned after a 'stepsize' decrement. | Below is the the instruction that describes the task:
### Input:
Takes as input a list or tuple of two elements. First the
value returned by incrementing by 'stepsize' followed by the
value returned after a 'stepsize' decrement.
### Response:
def _update_state(self, vals):
"""
Takes... |
def setup(self):
"""Initialize the driver by setting up GPIO interrupts
and periodic statistics processing. """
# Initialize the statistics variables.
self.radiation_count = 0
self.noise_count = 0
self.count = 0
# Initialize count_history[].
self.count_his... | Initialize the driver by setting up GPIO interrupts
and periodic statistics processing. | Below is the the instruction that describes the task:
### Input:
Initialize the driver by setting up GPIO interrupts
and periodic statistics processing.
### Response:
def setup(self):
"""Initialize the driver by setting up GPIO interrupts
and periodic statistics processing. """
# In... |
def format(self, record):
"""
The formatting function
:param record: The record object
:return: The string representation of the record
"""
try:
n = record.n
except AttributeError:
n = 'default'
try:
message = record.... | The formatting function
:param record: The record object
:return: The string representation of the record | Below is the the instruction that describes the task:
### Input:
The formatting function
:param record: The record object
:return: The string representation of the record
### Response:
def format(self, record):
"""
The formatting function
:param record: The record object
... |
def _parse_json(doc, exactly_one=True):
"""
Parse a location name, latitude, and longitude from an JSON response.
"""
status_code = doc.get("statusCode", 200)
if status_code != 200:
err = doc.get("errorDetails", "")
if status_code == 401:
r... | Parse a location name, latitude, and longitude from an JSON response. | Below is the the instruction that describes the task:
### Input:
Parse a location name, latitude, and longitude from an JSON response.
### Response:
def _parse_json(doc, exactly_one=True):
"""
Parse a location name, latitude, and longitude from an JSON response.
"""
status_code = do... |
def skip(self):
'''Mark the item as processed without download.'''
_logger.debug(__(_('Skipping ‘{url}’.'), url=self.url_record.url))
self.app_session.factory['URLTable'].check_in(self.url_record.url, Status.skipped)
self._processed = True | Mark the item as processed without download. | Below is the the instruction that describes the task:
### Input:
Mark the item as processed without download.
### Response:
def skip(self):
'''Mark the item as processed without download.'''
_logger.debug(__(_('Skipping ‘{url}’.'), url=self.url_record.url))
self.app_session.factory['URLTabl... |
def write_to_file(self, filename):
"""Write the molecular geometry to a file.
The file format is inferred from the extensions. Currently supported
formats are: ``*.xyz``, ``*.cml``
Argument:
| ``filename`` -- a filename
"""
# TODO: give all file f... | Write the molecular geometry to a file.
The file format is inferred from the extensions. Currently supported
formats are: ``*.xyz``, ``*.cml``
Argument:
| ``filename`` -- a filename | Below is the the instruction that describes the task:
### Input:
Write the molecular geometry to a file.
The file format is inferred from the extensions. Currently supported
formats are: ``*.xyz``, ``*.cml``
Argument:
| ``filename`` -- a filename
### Response:
def w... |
def query_by_id(self, id):
"""
Returns object with _id = id.
:param id: Value for ID. If not a string will be coerced to string.
:type id: ``string``
:return: Document with id
:rtype: ``dict``
"""
return json.loads(self._get(UrlEncoded(str(id))).body.rea... | Returns object with _id = id.
:param id: Value for ID. If not a string will be coerced to string.
:type id: ``string``
:return: Document with id
:rtype: ``dict`` | Below is the the instruction that describes the task:
### Input:
Returns object with _id = id.
:param id: Value for ID. If not a string will be coerced to string.
:type id: ``string``
:return: Document with id
:rtype: ``dict``
### Response:
def query_by_id(self, id):
"""
... |
def reassign_label(self, label, new_label, relabel=False):
"""
Reassign a label number to a new number.
If ``new_label`` is already present in the segmentation image,
then it will be combined with the input ``label`` number.
Parameters
----------
labels : int
... | Reassign a label number to a new number.
If ``new_label`` is already present in the segmentation image,
then it will be combined with the input ``label`` number.
Parameters
----------
labels : int
The label number to reassign.
new_label : int
Th... | Below is the the instruction that describes the task:
### Input:
Reassign a label number to a new number.
If ``new_label`` is already present in the segmentation image,
then it will be combined with the input ``label`` number.
Parameters
----------
labels : int
... |
def numToDigits(num, places):
"""
Helper, for converting numbers to textual digits.
"""
s = str(num)
if len(s) < places:
return ("0" * (places - len(s))) + s
elif len(s) > places:
return s[len(s)-places: ]
else:
return s | Helper, for converting numbers to textual digits. | Below is the the instruction that describes the task:
### Input:
Helper, for converting numbers to textual digits.
### Response:
def numToDigits(num, places):
"""
Helper, for converting numbers to textual digits.
"""
s = str(num)
if len(s) < places:
return ("0" * (places - len(s))) + s
... |
def authorize_host_to_volume(self, volume_id,
hardware_ids=None,
virtual_guest_ids=None,
ip_address_ids=None,
**kwargs):
"""Authorizes hosts to Block Storage Volumes
:para... | Authorizes hosts to Block Storage Volumes
:param volume_id: The Block volume to authorize hosts to
:param hardware_ids: A List of SoftLayer_Hardware ids
:param virtual_guest_ids: A List of SoftLayer_Virtual_Guest ids
:param ip_address_ids: A List of SoftLayer_Network_Subnet_IpAddress id... | Below is the the instruction that describes the task:
### Input:
Authorizes hosts to Block Storage Volumes
:param volume_id: The Block volume to authorize hosts to
:param hardware_ids: A List of SoftLayer_Hardware ids
:param virtual_guest_ids: A List of SoftLayer_Virtual_Guest ids
:... |
def grid_1d(self):
""" The arc second-grid of (y,x) coordinates of every pixel.
This is defined from the top-left corner, such that the first pixel at location [0, 0] will have a negative x \
value y value in arc seconds.
"""
return grid_util.regular_grid_1d_from_shape_pixel_sca... | The arc second-grid of (y,x) coordinates of every pixel.
This is defined from the top-left corner, such that the first pixel at location [0, 0] will have a negative x \
value y value in arc seconds. | Below is the the instruction that describes the task:
### Input:
The arc second-grid of (y,x) coordinates of every pixel.
This is defined from the top-left corner, such that the first pixel at location [0, 0] will have a negative x \
value y value in arc seconds.
### Response:
def grid_1d(self):
... |
def check(self):
"""Check that the entry has the required fields."""
# Make sure there is a schema key in dict
if self._KEYS.SCHEMA not in self:
self[self._KEYS.SCHEMA] = self.catalog.SCHEMA.URL
# Make sure there is a name key in dict
if (self._KEYS.NAME not in self o... | Check that the entry has the required fields. | Below is the the instruction that describes the task:
### Input:
Check that the entry has the required fields.
### Response:
def check(self):
"""Check that the entry has the required fields."""
# Make sure there is a schema key in dict
if self._KEYS.SCHEMA not in self:
self[self... |
def request_comments(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/requests#listing-comments"
api_path = "/api/v2/requests/{id}/comments.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/requests#listing-comments | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/requests#listing-comments
### Response:
def request_comments(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/requests#listing-comments"
api_path = "/api/v2/reques... |
def add_uppercase(table):
"""
Extend the table with uppercase options
>>> print("а" in add_uppercase({"а": "a"}))
True
>>> print(add_uppercase({"а": "a"})["а"] == "a")
True
>>> print("А" in add_uppercase({"а": "a"}))
True
>>> print(add_uppercase({"а": "a"})["А"] == "A")
True
... | Extend the table with uppercase options
>>> print("а" in add_uppercase({"а": "a"}))
True
>>> print(add_uppercase({"а": "a"})["а"] == "a")
True
>>> print("А" in add_uppercase({"а": "a"}))
True
>>> print(add_uppercase({"а": "a"})["А"] == "A")
True
>>> print(len(add_uppercase({"а": "a"... | Below is the the instruction that describes the task:
### Input:
Extend the table with uppercase options
>>> print("а" in add_uppercase({"а": "a"}))
True
>>> print(add_uppercase({"а": "a"})["а"] == "a")
True
>>> print("А" in add_uppercase({"а": "a"}))
True
>>> print(add_uppercase({"а": ... |
def get_numeric_value(event_tags, logger=None):
"""
A smart getter of the numeric value from the event tags.
Args:
event_tags: A dictionary of event tags.
logger: Optional logger.
Returns:
A float numeric metric value is returned when the provided numeric
metric value is in the followi... | A smart getter of the numeric value from the event tags.
Args:
event_tags: A dictionary of event tags.
logger: Optional logger.
Returns:
A float numeric metric value is returned when the provided numeric
metric value is in the following format:
- A string (properly formatted, e.g... | Below is the the instruction that describes the task:
### Input:
A smart getter of the numeric value from the event tags.
Args:
event_tags: A dictionary of event tags.
logger: Optional logger.
Returns:
A float numeric metric value is returned when the provided numeric
metric value is i... |
def parse(source, world, jointgroup=None, density=1000, color=None):
'''Load and parse a source file.
Parameters
----------
source : file
A file-like object that contains text information describing bodies and
joints to add to the world.
world : :class:`pagoda.physics.World`
... | Load and parse a source file.
Parameters
----------
source : file
A file-like object that contains text information describing bodies and
joints to add to the world.
world : :class:`pagoda.physics.World`
The world to add objects and joints to.
jointgroup : ode.JointGroup, op... | Below is the the instruction that describes the task:
### Input:
Load and parse a source file.
Parameters
----------
source : file
A file-like object that contains text information describing bodies and
joints to add to the world.
world : :class:`pagoda.physics.World`
The wo... |
def _get_cache_dir():
'''
Get pillar cache directory. Initialize it if it does not exist.
'''
cache_dir = os.path.join(__opts__['cachedir'], 'pillar_s3fs')
if not os.path.isdir(cache_dir):
log.debug('Initializing S3 Pillar Cache')
os.makedirs(cache_dir)
return cache_dir | Get pillar cache directory. Initialize it if it does not exist. | Below is the the instruction that describes the task:
### Input:
Get pillar cache directory. Initialize it if it does not exist.
### Response:
def _get_cache_dir():
'''
Get pillar cache directory. Initialize it if it does not exist.
'''
cache_dir = os.path.join(__opts__['cachedir'], 'pillar_s3fs')... |
def paintEvent(self, event):
"""Override Qt method"""
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
# Decoration
painter.fillPath(self.path_current, QBrush(self.color))
painter.strokePath(self.path_decoration, QPen(self.color_decoration,
... | Override Qt method | Below is the the instruction that describes the task:
### Input:
Override Qt method
### Response:
def paintEvent(self, event):
"""Override Qt method"""
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
# Decoration
painter.fillPath(self.path_current,... |
def computeRange(corners):
""" Determine the range spanned by an array of pixel positions. """
x = corners[:, 0]
y = corners[:, 1]
_xrange = (np.minimum.reduce(x), np.maximum.reduce(x))
_yrange = (np.minimum.reduce(y), np.maximum.reduce(y))
return _xrange, _yrange | Determine the range spanned by an array of pixel positions. | Below is the the instruction that describes the task:
### Input:
Determine the range spanned by an array of pixel positions.
### Response:
def computeRange(corners):
""" Determine the range spanned by an array of pixel positions. """
x = corners[:, 0]
y = corners[:, 1]
_xrange = (np.minimum.reduce(... |
def multidict(ordered_pairs):
"""Convert duplicate keys values to lists."""
# read all values into lists
d = defaultdict(list)
for k, v in ordered_pairs:
d[k].append(v)
# unpack lists that have only 1 item
dict_copy = deepcopy(d)
for k, v in iteritems(dict_copy):
if len(v) ==... | Convert duplicate keys values to lists. | Below is the the instruction that describes the task:
### Input:
Convert duplicate keys values to lists.
### Response:
def multidict(ordered_pairs):
"""Convert duplicate keys values to lists."""
# read all values into lists
d = defaultdict(list)
for k, v in ordered_pairs:
d[k].append(v)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.