code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def set_homepage(self, shop_id, template_id, url=None):
"""
设置商家主页
详情请参考
http://mp.weixin.qq.com/wiki/6/2732f3cf83947e0e4971aa8797ee9d6a.html
:param shop_id: 门店 ID
:param template_id: 模板ID,0-默认模板,1-自定义url
:param url: 自定义链接,当template_id为1时必填
:return: 返回的 ... | 设置商家主页
详情请参考
http://mp.weixin.qq.com/wiki/6/2732f3cf83947e0e4971aa8797ee9d6a.html
:param shop_id: 门店 ID
:param template_id: 模板ID,0-默认模板,1-自定义url
:param url: 自定义链接,当template_id为1时必填
:return: 返回的 JSON 数据包 | Below is the the instruction that describes the task:
### Input:
设置商家主页
详情请参考
http://mp.weixin.qq.com/wiki/6/2732f3cf83947e0e4971aa8797ee9d6a.html
:param shop_id: 门店 ID
:param template_id: 模板ID,0-默认模板,1-自定义url
:param url: 自定义链接,当template_id为1时必填
:return: 返回的 JSON 数据... |
def to_openmath(self, obj):
""" Convert Python object to OpenMath """
for cl, conv in reversed(self._conv_to_om):
if cl is None or isinstance(obj, cl):
try:
return conv(obj)
except CannotConvertError:
continue
i... | Convert Python object to OpenMath | Below is the the instruction that describes the task:
### Input:
Convert Python object to OpenMath
### Response:
def to_openmath(self, obj):
""" Convert Python object to OpenMath """
for cl, conv in reversed(self._conv_to_om):
if cl is None or isinstance(obj, cl):
try:
... |
def pool_to_HW(shape, data_frmt):
""" Convert from NHWC|NCHW => HW
"""
if len(shape) != 4:
return shape # Not NHWC|NCHW, return as is
if data_frmt == 'NCHW':
return [shape[2], shape[3]]
return [shape[1], shape[2]] | Convert from NHWC|NCHW => HW | Below is the the instruction that describes the task:
### Input:
Convert from NHWC|NCHW => HW
### Response:
def pool_to_HW(shape, data_frmt):
""" Convert from NHWC|NCHW => HW
"""
if len(shape) != 4:
return shape # Not NHWC|NCHW, return as is
if data_frmt == 'NCHW':
return [shape[2],... |
def client(self):
"""Return a lazy-instantiated pymongo client.
When running with eventlet, connection causes IO and can result in more
than one MongoDB client getting instantiatied, so we wrap the code in
a semaphore to make sure only one mongodb client is instantiated per
Simp... | Return a lazy-instantiated pymongo client.
When running with eventlet, connection causes IO and can result in more
than one MongoDB client getting instantiatied, so we wrap the code in
a semaphore to make sure only one mongodb client is instantiated per
SimplDB class. | Below is the the instruction that describes the task:
### Input:
Return a lazy-instantiated pymongo client.
When running with eventlet, connection causes IO and can result in more
than one MongoDB client getting instantiatied, so we wrap the code in
a semaphore to make sure only one mongodb... |
def padDigitalData(self, dig_data, n):
"""Pad dig_data with its last element so that the new array is a
multiple of n.
"""
n = int(n)
l0 = len(dig_data)
if l0 % n == 0:
return dig_data # no need of padding
else:
ladd = n - (l0 % n)
... | Pad dig_data with its last element so that the new array is a
multiple of n. | Below is the the instruction that describes the task:
### Input:
Pad dig_data with its last element so that the new array is a
multiple of n.
### Response:
def padDigitalData(self, dig_data, n):
"""Pad dig_data with its last element so that the new array is a
multiple of n.
"""
... |
def send(self, request):
"""Queue a request to be sent to the RPC."""
if self._UNARY_REQUESTS:
try:
self._send_unary_request(request)
except exceptions.GoogleAPICallError:
_LOGGER.debug(
"Exception while sending unary RPC. This ... | Queue a request to be sent to the RPC. | Below is the the instruction that describes the task:
### Input:
Queue a request to be sent to the RPC.
### Response:
def send(self, request):
"""Queue a request to be sent to the RPC."""
if self._UNARY_REQUESTS:
try:
self._send_unary_request(request)
except ... |
async def send_read_acknowledge(
self, entity, message=None, *, max_id=None, clear_mentions=False):
"""
Sends a "read acknowledge" (i.e., notifying the given peer that we've
read their messages, also known as the "double check").
This effectively marks a message as read (or ... | Sends a "read acknowledge" (i.e., notifying the given peer that we've
read their messages, also known as the "double check").
This effectively marks a message as read (or more than one) in the
given conversation.
If neither message nor maximum ID are provided, all messages will be
... | Below is the the instruction that describes the task:
### Input:
Sends a "read acknowledge" (i.e., notifying the given peer that we've
read their messages, also known as the "double check").
This effectively marks a message as read (or more than one) in the
given conversation.
If n... |
def module(self):
"""The module in which the Class is defined.
Python equivalent of the CLIPS defglobal-module command.
"""
modname = ffi.string(lib.EnvDefclassModule(self._env, self._cls))
defmodule = lib.EnvFindDefmodule(self._env, modname)
return Module(self._env, d... | The module in which the Class is defined.
Python equivalent of the CLIPS defglobal-module command. | Below is the the instruction that describes the task:
### Input:
The module in which the Class is defined.
Python equivalent of the CLIPS defglobal-module command.
### Response:
def module(self):
"""The module in which the Class is defined.
Python equivalent of the CLIPS defglobal-module ... |
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
... | Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object | Below is the the instruction that describes the task:
### Input:
Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
### Response:
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
... |
def metrics(ty, query, query_type, **kwargs):
"""
Outputs runtime metrics collected from cocaine-runtime and its services.
This command shows runtime metrics collected from cocaine-runtime and its services during their
lifetime.
There are four kind of metrics available: gauges, counters, meters and... | Outputs runtime metrics collected from cocaine-runtime and its services.
This command shows runtime metrics collected from cocaine-runtime and its services during their
lifetime.
There are four kind of metrics available: gauges, counters, meters and timers.
\b
- Gauges - an instantaneous measure... | Below is the the instruction that describes the task:
### Input:
Outputs runtime metrics collected from cocaine-runtime and its services.
This command shows runtime metrics collected from cocaine-runtime and its services during their
lifetime.
There are four kind of metrics available: gauges, counters,... |
def releases(self, **kwargs):
"""
Get the release date and certification information by country for a
specific movie id.
Args:
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the ... | Get the release date and certification information by country for a
specific movie id.
Args:
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API. | Below is the the instruction that describes the task:
### Input:
Get the release date and certification information by country for a
specific movie id.
Args:
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON... |
def do_jump(self, arg):
"""j(ump) lineno
Set the next line that will be executed. Only available in
the bottom-most frame. This lets you jump back and execute
code again, or jump forward to skip code that you don't want
to run.
It should be noted that not all jumps are... | j(ump) lineno
Set the next line that will be executed. Only available in
the bottom-most frame. This lets you jump back and execute
code again, or jump forward to skip code that you don't want
to run.
It should be noted that not all jumps are allowed -- for
instance it... | Below is the the instruction that describes the task:
### Input:
j(ump) lineno
Set the next line that will be executed. Only available in
the bottom-most frame. This lets you jump back and execute
code again, or jump forward to skip code that you don't want
to run.
It shou... |
def register_success(self, upgrade):
"""Register a successful upgrade."""
u = Upgrade(upgrade=upgrade.name, applied=datetime.now())
db.session.add(u)
db.session.commit() | Register a successful upgrade. | Below is the the instruction that describes the task:
### Input:
Register a successful upgrade.
### Response:
def register_success(self, upgrade):
"""Register a successful upgrade."""
u = Upgrade(upgrade=upgrade.name, applied=datetime.now())
db.session.add(u)
db.session.commit() |
def set_selection_strategy(self, strategy='spectral-oasis', nsel=1, neig=None):
""" Defines the column selection strategy
Parameters
----------
strategy : str
One of the following strategies to select new columns:
random : randomly choose from non-selected column... | Defines the column selection strategy
Parameters
----------
strategy : str
One of the following strategies to select new columns:
random : randomly choose from non-selected columns
oasis : maximal approximation error in the diagonal of :math:`A`
s... | Below is the the instruction that describes the task:
### Input:
Defines the column selection strategy
Parameters
----------
strategy : str
One of the following strategies to select new columns:
random : randomly choose from non-selected columns
oasis : m... |
def main():
"""cm.
Usage:
cm [-q] help
cm [-v] [-b] [--file=SCRIPT] [-i] [COMMAND ...]
Arguments:
COMMAND A command to be executed
Options:
--file=SCRIPT -f SCRIPT Executes the script
-i After start keep the shell interactive,
... | cm.
Usage:
cm [-q] help
cm [-v] [-b] [--file=SCRIPT] [-i] [COMMAND ...]
Arguments:
COMMAND A command to be executed
Options:
--file=SCRIPT -f SCRIPT Executes the script
-i After start keep the shell interactive,
ot... | Below is the the instruction that describes the task:
### Input:
cm.
Usage:
cm [-q] help
cm [-v] [-b] [--file=SCRIPT] [-i] [COMMAND ...]
Arguments:
COMMAND A command to be executed
Options:
--file=SCRIPT -f SCRIPT Executes the script
-i ... |
def py_to_go_cookie(py_cookie):
'''Convert a python cookie to the JSON-marshalable Go-style cookie form.'''
# TODO (perhaps):
# HttpOnly
# Creation
# LastAccess
# Updated
# not done properly: CanonicalHost.
go_cookie = {
'Name': py_cookie.name,
'Value': py_cookie.... | Convert a python cookie to the JSON-marshalable Go-style cookie form. | Below is the the instruction that describes the task:
### Input:
Convert a python cookie to the JSON-marshalable Go-style cookie form.
### Response:
def py_to_go_cookie(py_cookie):
'''Convert a python cookie to the JSON-marshalable Go-style cookie form.'''
# TODO (perhaps):
# HttpOnly
# Creatio... |
def modsplit(s):
"""Split importable"""
if ':' in s:
c = s.split(':')
if len(c) != 2:
raise ValueError("Syntax error: {s}")
return c[0], c[1]
else:
c = s.split('.')
if len(c) < 2:
raise ValueError("Syntax error: {s}")
return '.'.join(c[... | Split importable | Below is the the instruction that describes the task:
### Input:
Split importable
### Response:
def modsplit(s):
"""Split importable"""
if ':' in s:
c = s.split(':')
if len(c) != 2:
raise ValueError("Syntax error: {s}")
return c[0], c[1]
else:
c = s.split('.'... |
def _values_of_same_type(self, val1, val2):
"""Checks if two values agree in type.
Raises a TypeError if both values are not supported by the parameter.
Returns false if only one of the two values is supported by the parameter.
Example usage:
>>>param._values_of_same_type(42,4... | Checks if two values agree in type.
Raises a TypeError if both values are not supported by the parameter.
Returns false if only one of the two values is supported by the parameter.
Example usage:
>>>param._values_of_same_type(42,43)
True
>>>param._values_of_same_type(... | Below is the the instruction that describes the task:
### Input:
Checks if two values agree in type.
Raises a TypeError if both values are not supported by the parameter.
Returns false if only one of the two values is supported by the parameter.
Example usage:
>>>param._values_of_... |
def json_dump_hook(cfg, text: bool=False):
"""
Dumps all the data into a JSON file.
"""
data = cfg.config.dump()
if not text:
json.dump(data, cfg.fd)
else:
return json.dumps(data) | Dumps all the data into a JSON file. | Below is the the instruction that describes the task:
### Input:
Dumps all the data into a JSON file.
### Response:
def json_dump_hook(cfg, text: bool=False):
"""
Dumps all the data into a JSON file.
"""
data = cfg.config.dump()
if not text:
json.dump(data, cfg.fd)
else:
re... |
def Reload(self):
"""Loads all events added since the last call to `Reload`.
If `Reload` was never called, loads all events in the file.
Returns:
The `EventAccumulator`.
"""
with self._generator_mutex:
for event in self._generator.Load():
self._ProcessEvent(event)
return se... | Loads all events added since the last call to `Reload`.
If `Reload` was never called, loads all events in the file.
Returns:
The `EventAccumulator`. | Below is the the instruction that describes the task:
### Input:
Loads all events added since the last call to `Reload`.
If `Reload` was never called, loads all events in the file.
Returns:
The `EventAccumulator`.
### Response:
def Reload(self):
"""Loads all events added since the last call to ... |
def ExamineEvent(self, mediator, event):
"""Analyzes an event.
Args:
mediator (AnalysisMediator): mediates interactions between
analysis plugins and other components, such as storage and dfvfs.
event (EventObject): event to examine.
"""
# This event requires an URL attribute.
... | Analyzes an event.
Args:
mediator (AnalysisMediator): mediates interactions between
analysis plugins and other components, such as storage and dfvfs.
event (EventObject): event to examine. | Below is the the instruction that describes the task:
### Input:
Analyzes an event.
Args:
mediator (AnalysisMediator): mediates interactions between
analysis plugins and other components, such as storage and dfvfs.
event (EventObject): event to examine.
### Response:
def ExamineEvent(sel... |
def filter_icc(icc, mask=None, thr=2, zscore=True, mode="+"):
""" Threshold then mask an IC correlation map.
Parameters
----------
icc: img-like
The 'raw' ICC map.
mask: img-like
If not None. Will apply this masks in the end of the process.
thr: float
The threshold valu... | Threshold then mask an IC correlation map.
Parameters
----------
icc: img-like
The 'raw' ICC map.
mask: img-like
If not None. Will apply this masks in the end of the process.
thr: float
The threshold value.
zscore: bool
If True will calculate the z-score of the... | Below is the the instruction that describes the task:
### Input:
Threshold then mask an IC correlation map.
Parameters
----------
icc: img-like
The 'raw' ICC map.
mask: img-like
If not None. Will apply this masks in the end of the process.
thr: float
The threshold value... |
def generate_base_grid(self, vtk_filename=None):
"""
Run first step of algorithm. Next step is split_voxels
:param vtk_filename:
:return:
"""
nd, ed, ed_dir = self.gen_grid_fcn(self.data.shape, self.voxelsize)
self.add_nodes(nd)
self.add_edges(ed, ed_dir, ... | Run first step of algorithm. Next step is split_voxels
:param vtk_filename:
:return: | Below is the the instruction that describes the task:
### Input:
Run first step of algorithm. Next step is split_voxels
:param vtk_filename:
:return:
### Response:
def generate_base_grid(self, vtk_filename=None):
"""
Run first step of algorithm. Next step is split_voxels
:pa... |
def _check_args(self, source):
'''Validate the argument section.
Args may be either a dict or a list (to allow multiple positional args).
'''
path = [source]
args = self.parsed_yaml.get('args', {})
self._assert_struct_type(args, 'args', (dict, list), path)
path.a... | Validate the argument section.
Args may be either a dict or a list (to allow multiple positional args). | Below is the the instruction that describes the task:
### Input:
Validate the argument section.
Args may be either a dict or a list (to allow multiple positional args).
### Response:
def _check_args(self, source):
'''Validate the argument section.
Args may be either a dict or a list (to a... |
def parse_targets(name=None,
pkgs=None,
sources=None,
saltenv='base',
normalize=True,
**kwargs):
'''
Parses the input to pkg.install and returns back the package(s) to be
installed. Returns a list of packages, as well ... | Parses the input to pkg.install and returns back the package(s) to be
installed. Returns a list of packages, as well as a string noting whether
the packages are to come from a repository or a binary package.
CLI Example:
.. code-block:: bash
salt '*' pkg_resource.parse_targets | Below is the the instruction that describes the task:
### Input:
Parses the input to pkg.install and returns back the package(s) to be
installed. Returns a list of packages, as well as a string noting whether
the packages are to come from a repository or a binary package.
CLI Example:
.. code-bloc... |
def members_entries(self, all_are_optional: Optional[bool] = False) -> List[Tuple[str, str]]:
""" Generate a list quoted raw name, signature type entries for this pairdef, recursively traversing
reference types
:param all_are_optional: If true, all types are forced optional
:return: raw... | Generate a list quoted raw name, signature type entries for this pairdef, recursively traversing
reference types
:param all_are_optional: If true, all types are forced optional
:return: raw name/ signature type for all elements in this pair | Below is the the instruction that describes the task:
### Input:
Generate a list quoted raw name, signature type entries for this pairdef, recursively traversing
reference types
:param all_are_optional: If true, all types are forced optional
:return: raw name/ signature type for all element... |
def __send_smtp_email(self, recipients, subject, html_body, text_body):
"""Send an email using SMTP
Args:
recipients (`list` of `str`): List of recipient email addresses
subject (str): Subject of the email
html_body (str): HTML body of the email
text_body... | Send an email using SMTP
Args:
recipients (`list` of `str`): List of recipient email addresses
subject (str): Subject of the email
html_body (str): HTML body of the email
text_body (str): Text body of the email
Returns:
`None` | Below is the the instruction that describes the task:
### Input:
Send an email using SMTP
Args:
recipients (`list` of `str`): List of recipient email addresses
subject (str): Subject of the email
html_body (str): HTML body of the email
text_body (str): Text b... |
def create(cls, path, encoding='utf-8'):
"""Create a new bare repository"""
cmd = [GIT, 'init', '--quiet', '--bare', path]
subprocess.check_call(cmd)
return cls(path, encoding) | Create a new bare repository | Below is the the instruction that describes the task:
### Input:
Create a new bare repository
### Response:
def create(cls, path, encoding='utf-8'):
"""Create a new bare repository"""
cmd = [GIT, 'init', '--quiet', '--bare', path]
subprocess.check_call(cmd)
return cls(path, encoding... |
def get(self):
"""Handle get request."""
try:
app_user = InitUser()
if (app_user.client_id and app_user.client_secret and
app_user.adwords_manager_cid and app_user.developer_token and
app_user.refresh_token):
self.redirect('/showAccounts')
else:
self.redire... | Handle get request. | Below is the the instruction that describes the task:
### Input:
Handle get request.
### Response:
def get(self):
"""Handle get request."""
try:
app_user = InitUser()
if (app_user.client_id and app_user.client_secret and
app_user.adwords_manager_cid and app_user.developer_token and
... |
def error_page(
participant=None,
error_text=None,
compensate=True,
error_type="default",
request_data="",
):
"""Render HTML for error page."""
config = _config()
if error_text is None:
error_text = """There has been an error and so you are unable to
continue, sorry!"""
... | Render HTML for error page. | Below is the the instruction that describes the task:
### Input:
Render HTML for error page.
### Response:
def error_page(
participant=None,
error_text=None,
compensate=True,
error_type="default",
request_data="",
):
"""Render HTML for error page."""
config = _config()
if error_tex... |
def rosenbrock(x, y, a=1, b=100):
"""Bigger is better; global optimum at x=a, y=a**2"""
return -1 * ((a - x)**2 + b * (y - x**2)**2) | Bigger is better; global optimum at x=a, y=a**2 | Below is the the instruction that describes the task:
### Input:
Bigger is better; global optimum at x=a, y=a**2
### Response:
def rosenbrock(x, y, a=1, b=100):
"""Bigger is better; global optimum at x=a, y=a**2"""
return -1 * ((a - x)**2 + b * (y - x**2)**2) |
def _register(self, assignment): # type: (Assignment) -> None
"""
Registers an Assignment in _positive or _negative.
"""
name = assignment.dependency.name
old_positive = self._positive.get(name)
if old_positive is not None:
self._positive[name] = old_positive... | Registers an Assignment in _positive or _negative. | Below is the the instruction that describes the task:
### Input:
Registers an Assignment in _positive or _negative.
### Response:
def _register(self, assignment): # type: (Assignment) -> None
"""
Registers an Assignment in _positive or _negative.
"""
name = assignment.dependency.na... |
def add_element(self, element):
"""
Element can be href or type :py:class:`smc.base.model.Element`
::
>>> from smc.elements.other import Category
>>> category = Category('foo')
>>> category.add_element(Host('kali'))
:param str,Element element: elemen... | Element can be href or type :py:class:`smc.base.model.Element`
::
>>> from smc.elements.other import Category
>>> category = Category('foo')
>>> category.add_element(Host('kali'))
:param str,Element element: element to add to tag
:raises: ModificationFailed:... | Below is the the instruction that describes the task:
### Input:
Element can be href or type :py:class:`smc.base.model.Element`
::
>>> from smc.elements.other import Category
>>> category = Category('foo')
>>> category.add_element(Host('kali'))
:param str,Elemen... |
def correct_scanpy(adatas, **kwargs):
"""Batch correct a list of `scanpy.api.AnnData`.
Parameters
----------
adatas : `list` of `scanpy.api.AnnData`
Data sets to integrate and/or correct.
kwargs : `dict`
See documentation for the `correct()` method for a full list of
paramet... | Batch correct a list of `scanpy.api.AnnData`.
Parameters
----------
adatas : `list` of `scanpy.api.AnnData`
Data sets to integrate and/or correct.
kwargs : `dict`
See documentation for the `correct()` method for a full list of
parameters to use for batch correction.
Returns... | Below is the the instruction that describes the task:
### Input:
Batch correct a list of `scanpy.api.AnnData`.
Parameters
----------
adatas : `list` of `scanpy.api.AnnData`
Data sets to integrate and/or correct.
kwargs : `dict`
See documentation for the `correct()` method for a full... |
def list_known_codes(s, unique=True, rgb_mode=False):
""" Find and print all known escape codes in a string,
using get_known_codes.
"""
total = 0
for codedesc in get_known_codes(s, unique=unique, rgb_mode=rgb_mode):
total += 1
print(codedesc)
plural = 'code' if total == 1 els... | Find and print all known escape codes in a string,
using get_known_codes. | Below is the the instruction that describes the task:
### Input:
Find and print all known escape codes in a string,
using get_known_codes.
### Response:
def list_known_codes(s, unique=True, rgb_mode=False):
""" Find and print all known escape codes in a string,
using get_known_codes.
"""
... |
def G(self, ID, lat, lon):
""" Creates a generic entry for an object. """
# Equatorial coordinates
eqM = utils.eqCoords(lon, lat)
eqZ = eqM
if lat != 0:
eqZ = utils.eqCoords(lon, 0)
return {
'id': ID,
'lat': lat,
... | Creates a generic entry for an object. | Below is the the instruction that describes the task:
### Input:
Creates a generic entry for an object.
### Response:
def G(self, ID, lat, lon):
""" Creates a generic entry for an object. """
# Equatorial coordinates
eqM = utils.eqCoords(lon, lat)
eqZ = eqM
if lat !... |
def event(name):
'''
Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
... | Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: salt/foo... | Below is the the instruction that describes the task:
### Input:
Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- f... |
def from_config(cls, cp, section, variable_args):
"""Returns a distribution based on a configuration file. The parameters
for the distribution are retrieved from the section titled
"[`section`-`variable_args`]" in the config file.
Parameters
----------
cp : pycbc.workflo... | Returns a distribution based on a configuration file. The parameters
for the distribution are retrieved from the section titled
"[`section`-`variable_args`]" in the config file.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
A parsed configuration fil... | Below is the the instruction that describes the task:
### Input:
Returns a distribution based on a configuration file. The parameters
for the distribution are retrieved from the section titled
"[`section`-`variable_args`]" in the config file.
Parameters
----------
cp : pycbc... |
def DescargarConstancia(self, nro_doc, filename="constancia.pdf"):
"Llama a la API para descargar una constancia de inscripcion (PDF)"
if not self.client:
self.Conectar()
self.response = self.client("sr-padron", "v1", "constancia", str(nro_doc))
if self.response.startswith("{... | Llama a la API para descargar una constancia de inscripcion (PDF) | Below is the the instruction that describes the task:
### Input:
Llama a la API para descargar una constancia de inscripcion (PDF)
### Response:
def DescargarConstancia(self, nro_doc, filename="constancia.pdf"):
"Llama a la API para descargar una constancia de inscripcion (PDF)"
if not self.client:... |
def create_italic(self, tag):
"""
See if span tag has italic style and wrap with em tag.
"""
style = tag.get('style')
if style and 'font-style:italic' in style:
tag.wrap(self.soup.new_tag('em')) | See if span tag has italic style and wrap with em tag. | Below is the the instruction that describes the task:
### Input:
See if span tag has italic style and wrap with em tag.
### Response:
def create_italic(self, tag):
"""
See if span tag has italic style and wrap with em tag.
"""
style = tag.get('style')
if style and 'font-styl... |
def get_list_url_filtered_by_field_value(view, model, name, reverse=False):
"""Get the URL if a filter of model[name] value was appended.
This allows programatically adding filters. This is used in the specialized case
of filtering deeper into a list by a field's value.
For instance, since there can b... | Get the URL if a filter of model[name] value was appended.
This allows programatically adding filters. This is used in the specialized case
of filtering deeper into a list by a field's value.
For instance, since there can be multiple assignments in a list of handins. The
assignment column can have a U... | Below is the the instruction that describes the task:
### Input:
Get the URL if a filter of model[name] value was appended.
This allows programatically adding filters. This is used in the specialized case
of filtering deeper into a list by a field's value.
For instance, since there can be multiple ass... |
def pydevd(context):
"""
Start a pydev settrace
"""
global pdevd_not_available
if pdevd_not_available:
return ''
try:
import pydevd
except ImportError:
pdevd_not_available = True
return ''
render = lambda s: template.Template(s).render(context)
availab... | Start a pydev settrace | Below is the the instruction that describes the task:
### Input:
Start a pydev settrace
### Response:
def pydevd(context):
"""
Start a pydev settrace
"""
global pdevd_not_available
if pdevd_not_available:
return ''
try:
import pydevd
except ImportError:
pdevd_not... |
def send_request(req=None, method=None, requires_response=True):
"""Call function req and then send its results via ZMQ."""
if req is None:
return functools.partial(send_request, method=method,
requires_response=requires_response)
@functools.wraps(req)
def wrapp... | Call function req and then send its results via ZMQ. | Below is the the instruction that describes the task:
### Input:
Call function req and then send its results via ZMQ.
### Response:
def send_request(req=None, method=None, requires_response=True):
"""Call function req and then send its results via ZMQ."""
if req is None:
return functools.partial(se... |
def to_positions(self):
"""
Converts fractional coordinates of trajectory into positions
"""
if self.coords_are_displacement:
cumulative_displacements = np.cumsum(self.frac_coords, axis=0)
positions = self.base_positions + cumulative_displacements
self... | Converts fractional coordinates of trajectory into positions | Below is the the instruction that describes the task:
### Input:
Converts fractional coordinates of trajectory into positions
### Response:
def to_positions(self):
"""
Converts fractional coordinates of trajectory into positions
"""
if self.coords_are_displacement:
cumul... |
def setup_new_conf(self):
# pylint: disable=too-many-locals
""" Setup a new configuration received from a Master arbiter.
TODO: perharps we should not accept the configuration or raise an error if we do not
find our own configuration data in the data. Thus this should never happen...
... | Setup a new configuration received from a Master arbiter.
TODO: perharps we should not accept the configuration or raise an error if we do not
find our own configuration data in the data. Thus this should never happen...
:return: None | Below is the the instruction that describes the task:
### Input:
Setup a new configuration received from a Master arbiter.
TODO: perharps we should not accept the configuration or raise an error if we do not
find our own configuration data in the data. Thus this should never happen...
:retu... |
def lzprob(z):
"""
Returns the area under the normal curve 'to the left of' the given z value.
Thus,
for z<0, zprob(z) = 1-tail probability
for z>0, 1.0-zprob(z) = 1-tail probability
for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability
Adapted from z.c in Gary Perlman's |Stat.
Usage: lzprob(z)
""... | Returns the area under the normal curve 'to the left of' the given z value.
Thus,
for z<0, zprob(z) = 1-tail probability
for z>0, 1.0-zprob(z) = 1-tail probability
for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability
Adapted from z.c in Gary Perlman's |Stat.
Usage: lzprob(z) | Below is the the instruction that describes the task:
### Input:
Returns the area under the normal curve 'to the left of' the given z value.
Thus,
for z<0, zprob(z) = 1-tail probability
for z>0, 1.0-zprob(z) = 1-tail probability
for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability
Adapted from z.c i... |
def get_z_variables(nc):
'''
Returns a list of all variables matching definitions for Z
:param netcdf4.dataset nc: an open netcdf dataset object
'''
z_variables = []
# Vertical coordinates will be identifiable by units of pressure or the
# presence of the positive attribute with a value of ... | Returns a list of all variables matching definitions for Z
:param netcdf4.dataset nc: an open netcdf dataset object | Below is the the instruction that describes the task:
### Input:
Returns a list of all variables matching definitions for Z
:param netcdf4.dataset nc: an open netcdf dataset object
### Response:
def get_z_variables(nc):
'''
Returns a list of all variables matching definitions for Z
:param netcdf4... |
def notify_change(self, change):
"""Called when a property has changed."""
# Send the state to the frontend before the user-registered callbacks
# are called.
name = change['name']
if self.comm is not None and self.comm.kernel is not None:
# Make sure this isn't infor... | Called when a property has changed. | Below is the the instruction that describes the task:
### Input:
Called when a property has changed.
### Response:
def notify_change(self, change):
"""Called when a property has changed."""
# Send the state to the frontend before the user-registered callbacks
# are called.
name = ch... |
def bcdc_package_show(package):
"""Query DataBC Catalogue API about given package
"""
params = {"id": package}
r = requests.get(bcdata.BCDC_API_URL + "package_show", params=params)
if r.status_code != 200:
raise ValueError("{d} is not present in DataBC API list".format(d=package))
return... | Query DataBC Catalogue API about given package | Below is the the instruction that describes the task:
### Input:
Query DataBC Catalogue API about given package
### Response:
def bcdc_package_show(package):
"""Query DataBC Catalogue API about given package
"""
params = {"id": package}
r = requests.get(bcdata.BCDC_API_URL + "package_show", params=... |
def get_thermal_conductivity(self, output='eigs', doping_levels=True,
k_el=True, relaxation_time=1e-14):
"""
Gives the electronic part of the thermal conductivity in either a
full 3x3 tensor form,
as 3 eigenvalues, or as the average value (trace/3.0) If
... | Gives the electronic part of the thermal conductivity in either a
full 3x3 tensor form,
as 3 eigenvalues, or as the average value (trace/3.0) If
doping_levels=True, the results are given at
different p and n doping levels (given by self.doping), otherwise it
is given as a series ... | Below is the the instruction that describes the task:
### Input:
Gives the electronic part of the thermal conductivity in either a
full 3x3 tensor form,
as 3 eigenvalues, or as the average value (trace/3.0) If
doping_levels=True, the results are given at
different p and n doping leve... |
def visit_ArraySelect(self, expression, *operands):
""" ArraySelect (ArrayStore((ArrayStore(x0,v0) ...),xn, vn), x0)
-> v0
"""
arr, index = operands
if isinstance(arr, ArrayVariable):
return
if isinstance(index, BitVecConstant):
ival = ind... | ArraySelect (ArrayStore((ArrayStore(x0,v0) ...),xn, vn), x0)
-> v0 | Below is the the instruction that describes the task:
### Input:
ArraySelect (ArrayStore((ArrayStore(x0,v0) ...),xn, vn), x0)
-> v0
### Response:
def visit_ArraySelect(self, expression, *operands):
""" ArraySelect (ArrayStore((ArrayStore(x0,v0) ...),xn, vn), x0)
-> v0
... |
def calibrate_cameras(self):
"""Calibrate cameras based on found chessboard corners."""
criteria = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS,
100, 1e-5)
flags = (cv2.CALIB_FIX_ASPECT_RATIO + cv2.CALIB_ZERO_TANGENT_DIST +
cv2.CALIB_SAME_FOCAL_LENGTH)... | Calibrate cameras based on found chessboard corners. | Below is the the instruction that describes the task:
### Input:
Calibrate cameras based on found chessboard corners.
### Response:
def calibrate_cameras(self):
"""Calibrate cameras based on found chessboard corners."""
criteria = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS,
... |
def get(self, selector, index=0, default=None):
""" Get first element from CSSSelector """
elements = self(selector)
if elements:
try:
return elements[index]
except (IndexError):
pass
return default | Get first element from CSSSelector | Below is the the instruction that describes the task:
### Input:
Get first element from CSSSelector
### Response:
def get(self, selector, index=0, default=None):
""" Get first element from CSSSelector """
elements = self(selector)
if elements:
try:
return element... |
def get_groups_with_perms(obj, attach_perms=False):
"""Return queryset of all ``Group`` objects with *any* object permissions for the given ``obj``."""
ctype = get_content_type(obj)
group_model = get_group_obj_perms_model(obj)
if not attach_perms:
# It's much easier without attached perms so we... | Return queryset of all ``Group`` objects with *any* object permissions for the given ``obj``. | Below is the the instruction that describes the task:
### Input:
Return queryset of all ``Group`` objects with *any* object permissions for the given ``obj``.
### Response:
def get_groups_with_perms(obj, attach_perms=False):
"""Return queryset of all ``Group`` objects with *any* object permissions for the give... |
def update(self, data):
"""Hash data.
"""
view = memoryview(data)
bs = self.block_size
if self._buf:
need = bs - len(self._buf)
if len(view) < need:
self._buf += view.tobytes()
return
self._add_block(self._buf + ... | Hash data. | Below is the the instruction that describes the task:
### Input:
Hash data.
### Response:
def update(self, data):
"""Hash data.
"""
view = memoryview(data)
bs = self.block_size
if self._buf:
need = bs - len(self._buf)
if len(view) < need:
... |
def check_solver_status(status, raise_error=False):
"""Perform standard checks on a solver's status."""
if status == OPTIMAL:
return
elif (status in has_primals) and not raise_error:
warn("solver status is '{}'".format(status), UserWarning)
elif status is None:
raise Optimization... | Perform standard checks on a solver's status. | Below is the the instruction that describes the task:
### Input:
Perform standard checks on a solver's status.
### Response:
def check_solver_status(status, raise_error=False):
"""Perform standard checks on a solver's status."""
if status == OPTIMAL:
return
elif (status in has_primals) and not ... |
def get_nearest_site(self, coords, site, r=None):
"""
Given coords and a site, find closet site to coords.
Args:
coords (3x1 array): cartesian coords of center of sphere
site: site to find closest to coords
r: radius of sphere. Defaults to diagonal of unit cel... | Given coords and a site, find closet site to coords.
Args:
coords (3x1 array): cartesian coords of center of sphere
site: site to find closest to coords
r: radius of sphere. Defaults to diagonal of unit cell
Returns:
Closest site and distance. | Below is the the instruction that describes the task:
### Input:
Given coords and a site, find closet site to coords.
Args:
coords (3x1 array): cartesian coords of center of sphere
site: site to find closest to coords
r: radius of sphere. Defaults to diagonal of unit cell... |
def registry_key(self, key_name, value_name, value_type, **kwargs):
"""Add Registry Key data to Batch object.
Args:
key_name (str): The key_name value for this Indicator.
value_name (str): The value_name value for this Indicator.
value_type (str): The value_type valu... | Add Registry Key data to Batch object.
Args:
key_name (str): The key_name value for this Indicator.
value_name (str): The value_name value for this Indicator.
value_type (str): The value_type value for this Indicator.
confidence (str, kwargs): The threat confiden... | Below is the the instruction that describes the task:
### Input:
Add Registry Key data to Batch object.
Args:
key_name (str): The key_name value for this Indicator.
value_name (str): The value_name value for this Indicator.
value_type (str): The value_type value for this... |
def set_residual(self, pores=[], throats=[], overwrite=False):
r"""
Specify locations of any residual invader. These locations are set
to invaded at the start of the simulation.
Parameters
----------
pores : array_like
The pores locations that are to be fill... | r"""
Specify locations of any residual invader. These locations are set
to invaded at the start of the simulation.
Parameters
----------
pores : array_like
The pores locations that are to be filled with invader at the
beginning of the simulation.
... | Below is the the instruction that describes the task:
### Input:
r"""
Specify locations of any residual invader. These locations are set
to invaded at the start of the simulation.
Parameters
----------
pores : array_like
The pores locations that are to be filled... |
def tree_search(problem, frontier):
"""Search through the successors of a problem to find a goal.
The argument frontier should be an empty queue.
Don't worry about repeated paths to a state. [Fig. 3.7]"""
frontier.append(Node(problem.initial))
while frontier:
node = frontier.pop()
if... | Search through the successors of a problem to find a goal.
The argument frontier should be an empty queue.
Don't worry about repeated paths to a state. [Fig. 3.7] | Below is the the instruction that describes the task:
### Input:
Search through the successors of a problem to find a goal.
The argument frontier should be an empty queue.
Don't worry about repeated paths to a state. [Fig. 3.7]
### Response:
def tree_search(problem, frontier):
"""Search through the suc... |
def do_hdr(self, line, hdrs_usr):
"""Initialize self.h2i."""
# If there is no header hint, consider the first line the header.
if self.hdr_ex is None:
self._init_hdr(line, hdrs_usr)
return True
# If there is a header hint, examine each beginning line until header ... | Initialize self.h2i. | Below is the the instruction that describes the task:
### Input:
Initialize self.h2i.
### Response:
def do_hdr(self, line, hdrs_usr):
"""Initialize self.h2i."""
# If there is no header hint, consider the first line the header.
if self.hdr_ex is None:
self._init_hdr(line, hdrs_us... |
def format_record(record):
"""Serialise LogRecord instance"""
record = dict(
(key, getattr(record, key, None))
for key in (
"threadName",
"name",
"thread",
"created",
"process",
"processName",
"args",
... | Serialise LogRecord instance | Below is the the instruction that describes the task:
### Input:
Serialise LogRecord instance
### Response:
def format_record(record):
"""Serialise LogRecord instance"""
record = dict(
(key, getattr(record, key, None))
for key in (
"threadName",
"name",
... |
def _validate(claims, validate_claims, expiry_seconds):
""" Validate expiry related claims.
If validate_claims is False, do nothing.
Otherwise, validate the exp and nbf claims if they are present, and
validate the iat claim if expiry_seconds is provided.
"""
if not validate_claims:
ret... | Validate expiry related claims.
If validate_claims is False, do nothing.
Otherwise, validate the exp and nbf claims if they are present, and
validate the iat claim if expiry_seconds is provided. | Below is the the instruction that describes the task:
### Input:
Validate expiry related claims.
If validate_claims is False, do nothing.
Otherwise, validate the exp and nbf claims if they are present, and
validate the iat claim if expiry_seconds is provided.
### Response:
def _validate(claims, valid... |
def sigmalos(Pot,R,dens=None,surfdens=None,beta=0.,sigma_r=None):
"""
NAME:
sigmalos
PURPOSE:
Compute the line-of-sight velocity dispersion using the spherical Jeans equation
INPUT:
Pot - potential or list of potentials (evaluated at R=r/sqrt(2),z=r/sqrt(2), sphericity not chec... | NAME:
sigmalos
PURPOSE:
Compute the line-of-sight velocity dispersion using the spherical Jeans equation
INPUT:
Pot - potential or list of potentials (evaluated at R=r/sqrt(2),z=r/sqrt(2), sphericity not checked)
R - Galactocentric projected radius (can be Quantity)
den... | Below is the the instruction that describes the task:
### Input:
NAME:
sigmalos
PURPOSE:
Compute the line-of-sight velocity dispersion using the spherical Jeans equation
INPUT:
Pot - potential or list of potentials (evaluated at R=r/sqrt(2),z=r/sqrt(2), sphericity not checked)
... |
def logspace(self,bins=None,units=None,conversion_function=convert_time,resolution=None,end_at_end=True):
""" bins overwrites resolution """
if type(bins) in [list, np.ndarray]:
return bins
min = conversion_function(self.min,from_units=self.units,to_units=units)
max = convers... | bins overwrites resolution | Below is the the instruction that describes the task:
### Input:
bins overwrites resolution
### Response:
def logspace(self,bins=None,units=None,conversion_function=convert_time,resolution=None,end_at_end=True):
""" bins overwrites resolution """
if type(bins) in [list, np.ndarray]:
ret... |
def run(self, dag):
"""Expand all op nodes to the given basis.
Args:
dag(DAGCircuit): input dag
Raises:
QiskitError: if unable to unroll given the basis due to undefined
decomposition rules (such as a bad basis) or excessive recursion.
Returns:
... | Expand all op nodes to the given basis.
Args:
dag(DAGCircuit): input dag
Raises:
QiskitError: if unable to unroll given the basis due to undefined
decomposition rules (such as a bad basis) or excessive recursion.
Returns:
DAGCircuit: output unro... | Below is the the instruction that describes the task:
### Input:
Expand all op nodes to the given basis.
Args:
dag(DAGCircuit): input dag
Raises:
QiskitError: if unable to unroll given the basis due to undefined
decomposition rules (such as a bad basis) or exces... |
def results(self):
"""A list of namedtuples in the form (eid doi pii pubmed_id title
subtype creator afid affilname affiliation_city affiliation_country
author_count author_names author_ids author_afids coverDate
coverDisplayDate publicationName issn source_id eIssn aggregationType
... | A list of namedtuples in the form (eid doi pii pubmed_id title
subtype creator afid affilname affiliation_city affiliation_country
author_count author_names author_ids author_afids coverDate
coverDisplayDate publicationName issn source_id eIssn aggregationType
volume issueIdentifier arti... | Below is the the instruction that describes the task:
### Input:
A list of namedtuples in the form (eid doi pii pubmed_id title
subtype creator afid affilname affiliation_city affiliation_country
author_count author_names author_ids author_afids coverDate
coverDisplayDate publicationName iss... |
def remove_server(self, server_id):
"""
Remove a registered WBEM server from the subscription manager. This
also unregisters listeners from that server and removes all owned
indication subscriptions, owned indication filters and owned listener
destinations.
Parameters:
... | Remove a registered WBEM server from the subscription manager. This
also unregisters listeners from that server and removes all owned
indication subscriptions, owned indication filters and owned listener
destinations.
Parameters:
server_id (:term:`string`):
The se... | Below is the the instruction that describes the task:
### Input:
Remove a registered WBEM server from the subscription manager. This
also unregisters listeners from that server and removes all owned
indication subscriptions, owned indication filters and owned listener
destinations.
... |
def _parse_raw_members(
self, leaderboard_name, members, members_only=False, **options):
'''
Parse the raw leaders data as returned from a given leader board query. Do associative
lookups with the member to rank, score and potentially sort the results.
@param leaderboard_nam... | Parse the raw leaders data as returned from a given leader board query. Do associative
lookups with the member to rank, score and potentially sort the results.
@param leaderboard_name [String] Name of the leaderboard.
@param members [List] A list of members as returned from a sorted set range q... | Below is the the instruction that describes the task:
### Input:
Parse the raw leaders data as returned from a given leader board query. Do associative
lookups with the member to rank, score and potentially sort the results.
@param leaderboard_name [String] Name of the leaderboard.
@param m... |
def _PrintVSSStoreIdentifiersOverview(
self, volume_system, volume_identifiers):
"""Prints an overview of VSS store identifiers.
Args:
volume_system (dfvfs.VShadowVolumeSystem): volume system.
volume_identifiers (list[str]): allowed volume identifiers.
Raises:
SourceScannerError: i... | Prints an overview of VSS store identifiers.
Args:
volume_system (dfvfs.VShadowVolumeSystem): volume system.
volume_identifiers (list[str]): allowed volume identifiers.
Raises:
SourceScannerError: if a volume cannot be resolved from the volume
identifier. | Below is the the instruction that describes the task:
### Input:
Prints an overview of VSS store identifiers.
Args:
volume_system (dfvfs.VShadowVolumeSystem): volume system.
volume_identifiers (list[str]): allowed volume identifiers.
Raises:
SourceScannerError: if a volume cannot be reso... |
def isolate_and_get(src_container, src_resources, local_dst_dir, **kwargs):
"""
Uses :func:`copy_resources` to copy resources from a container, but afterwards generates a compressed tarball
and downloads it.
:param src_container: Container name or id.
:type src_container: unicode
:param src_res... | Uses :func:`copy_resources` to copy resources from a container, but afterwards generates a compressed tarball
and downloads it.
:param src_container: Container name or id.
:type src_container: unicode
:param src_resources: Resources, as (file or directory) names to copy.
:type src_resources: iterab... | Below is the the instruction that describes the task:
### Input:
Uses :func:`copy_resources` to copy resources from a container, but afterwards generates a compressed tarball
and downloads it.
:param src_container: Container name or id.
:type src_container: unicode
:param src_resources: Resources, ... |
def is_cloned(cls):
"""
Let us know if we are currently in the cloned version of
PyFunceble which implicitly mean that we are in developement mode.
"""
if not PyFunceble.path.isdir(".git"):
# The git directory does not exist.
# We return False, the curre... | Let us know if we are currently in the cloned version of
PyFunceble which implicitly mean that we are in developement mode. | Below is the the instruction that describes the task:
### Input:
Let us know if we are currently in the cloned version of
PyFunceble which implicitly mean that we are in developement mode.
### Response:
def is_cloned(cls):
"""
Let us know if we are currently in the cloned version of
... |
def longest_utterances_per_container(self):
""" Return a tuple/list containing the length of the longest utterance of ever container. """
lengths = []
for cnt in self.containers:
longest_in_container = 0
for utt_idx in self.utt_ids:
utt_length = cnt._file... | Return a tuple/list containing the length of the longest utterance of ever container. | Below is the the instruction that describes the task:
### Input:
Return a tuple/list containing the length of the longest utterance of ever container.
### Response:
def longest_utterances_per_container(self):
""" Return a tuple/list containing the length of the longest utterance of ever container. """
... |
def ones_matrix_band_part(rows, cols, num_lower, num_upper, out_shape=None):
"""Matrix band part of ones.
Args:
rows: int determining number of rows in output
cols: int
num_lower: int, maximum distance backward. Negative values indicate
unlimited.
num_upper: int, maximum distance forward. Neg... | Matrix band part of ones.
Args:
rows: int determining number of rows in output
cols: int
num_lower: int, maximum distance backward. Negative values indicate
unlimited.
num_upper: int, maximum distance forward. Negative values indicate
unlimited.
out_shape: shape to reshape output by.
... | Below is the the instruction that describes the task:
### Input:
Matrix band part of ones.
Args:
rows: int determining number of rows in output
cols: int
num_lower: int, maximum distance backward. Negative values indicate
unlimited.
num_upper: int, maximum distance forward. Negative values ... |
def load(self, configuration):
"""
Load a YAML configuration file.
:param configuration: Configuration filename or YAML string
"""
try:
self.config = yaml.load(open(configuration, "rb"))
except IOError:
try:
self.config = yaml.load... | Load a YAML configuration file.
:param configuration: Configuration filename or YAML string | Below is the the instruction that describes the task:
### Input:
Load a YAML configuration file.
:param configuration: Configuration filename or YAML string
### Response:
def load(self, configuration):
"""
Load a YAML configuration file.
:param configuration: Configuration filenam... |
def patch_namespaced_service(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_service # noqa: E501
partially update the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass as... | patch_namespaced_service # noqa: E501
partially update the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_service(name, namespace, body, async_re... | Below is the the instruction that describes the task:
### Input:
patch_namespaced_service # noqa: E501
partially update the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> ... |
def get_name_from_name_hash128( self, name ):
"""
Get the name from a name hash
"""
cur = self.db.cursor()
name = namedb_get_name_from_name_hash128( cur, name, self.lastblock )
return name | Get the name from a name hash | Below is the the instruction that describes the task:
### Input:
Get the name from a name hash
### Response:
def get_name_from_name_hash128( self, name ):
"""
Get the name from a name hash
"""
cur = self.db.cursor()
name = namedb_get_name_from_name_hash128( cur, name, self.l... |
def _parse_rmw_row_response(row_response):
"""Parses the response to a ``ReadModifyWriteRow`` request.
:type row_response: :class:`.data_v2_pb2.Row`
:param row_response: The response row (with only modified cells) from a
``ReadModifyWriteRow`` request.
:rtype: dict
:return... | Parses the response to a ``ReadModifyWriteRow`` request.
:type row_response: :class:`.data_v2_pb2.Row`
:param row_response: The response row (with only modified cells) from a
``ReadModifyWriteRow`` request.
:rtype: dict
:returns: The new contents of all modified cells. Returne... | Below is the the instruction that describes the task:
### Input:
Parses the response to a ``ReadModifyWriteRow`` request.
:type row_response: :class:`.data_v2_pb2.Row`
:param row_response: The response row (with only modified cells) from a
``ReadModifyWriteRow`` request.
:rtyp... |
def _set(self):
"""Called internally by Client to indicate this request has finished"""
self.__event.set()
if self._complete_func:
self.__run_completion_func(self._complete_func, self.id_) | Called internally by Client to indicate this request has finished | Below is the the instruction that describes the task:
### Input:
Called internally by Client to indicate this request has finished
### Response:
def _set(self):
"""Called internally by Client to indicate this request has finished"""
self.__event.set()
if self._complete_func:
sel... |
def parallel_graph_evaluation(data, adj_matrix, nb_runs=16,
nb_jobs=None, **kwargs):
"""Parallelize the various runs of CGNN to evaluate a graph."""
nb_jobs = SETTINGS.get_default(nb_jobs=nb_jobs)
if nb_runs == 1:
return graph_evaluation(data, adj_matrix, **kwargs)
... | Parallelize the various runs of CGNN to evaluate a graph. | Below is the the instruction that describes the task:
### Input:
Parallelize the various runs of CGNN to evaluate a graph.
### Response:
def parallel_graph_evaluation(data, adj_matrix, nb_runs=16,
nb_jobs=None, **kwargs):
"""Parallelize the various runs of CGNN to evaluate a graph... |
def writeGlyph(self,
name,
unicodes=None,
location=None,
masters=None,
note=None,
mute=False,
):
""" Add a new glyph to the current instance.
* name: the glyph name. Required.
* unicodes: unicode values f... | Add a new glyph to the current instance.
* name: the glyph name. Required.
* unicodes: unicode values for this glyph if it needs to be different from the unicode values associated with this glyph name in the masters.
* location: a design space location for this glyph if it needs to b... | Below is the the instruction that describes the task:
### Input:
Add a new glyph to the current instance.
* name: the glyph name. Required.
* unicodes: unicode values for this glyph if it needs to be different from the unicode values associated with this glyph name in the masters.
... |
def _find_conflicts_between_sub_selection_sets(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
are_... | Find all conflicts found between two selection sets.
Includes those found via spreading in fragments. Called when determining if conflicts exist
between the sub-fields of two overlapping fields. | Below is the the instruction that describes the task:
### Input:
Find all conflicts found between two selection sets.
Includes those found via spreading in fragments. Called when determining if conflicts exist
between the sub-fields of two overlapping fields.
### Response:
def _find_conflicts_betwee... |
def build_event_connections(self, component, runnable, structure):
"""
Adds event connections to a runnable component based on the structure
specifications in the component model.
@param component: Component model containing structure specifications.
@type component: lems.model.... | Adds event connections to a runnable component based on the structure
specifications in the component model.
@param component: Component model containing structure specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which structure ... | Below is the the instruction that describes the task:
### Input:
Adds event connections to a runnable component based on the structure
specifications in the component model.
@param component: Component model containing structure specifications.
@type component: lems.model.component.FatCompo... |
def get_report(report=None):
"""Returns details of a specific report
"""
if not report:
report = list_reports()[-1:][0]
report_path = _get_reports_path(report)
report_dict = {"report": report}
for filename in os.listdir(report_path):
with open(os.path.join(report_path, filename),... | Returns details of a specific report | Below is the the instruction that describes the task:
### Input:
Returns details of a specific report
### Response:
def get_report(report=None):
"""Returns details of a specific report
"""
if not report:
report = list_reports()[-1:][0]
report_path = _get_reports_path(report)
report_dict... |
def get_mod_log(self, subreddit, mod=None, action=None, *args, **kwargs):
"""Return a get_content generator for moderation log items.
:param subreddit: Either a Subreddit object or the name of the
subreddit to return the modlog for.
:param mod: If given, only return the actions made... | Return a get_content generator for moderation log items.
:param subreddit: Either a Subreddit object or the name of the
subreddit to return the modlog for.
:param mod: If given, only return the actions made by this moderator.
Both a moderator name or Redditor object can be used ... | Below is the the instruction that describes the task:
### Input:
Return a get_content generator for moderation log items.
:param subreddit: Either a Subreddit object or the name of the
subreddit to return the modlog for.
:param mod: If given, only return the actions made by this moderat... |
def reduce(self, func, dim=None, keep_attrs=None, **kwargs):
"""Reduce the items in this group by applying `func` along the
pre-defined resampling dimension.
Parameters
----------
func : function
Function which can be called in the form
`func(x, axis=axis... | Reduce the items in this group by applying `func` along the
pre-defined resampling dimension.
Parameters
----------
func : function
Function which can be called in the form
`func(x, axis=axis, **kwargs)` to return the result of collapsing
an np.ndarra... | Below is the the instruction that describes the task:
### Input:
Reduce the items in this group by applying `func` along the
pre-defined resampling dimension.
Parameters
----------
func : function
Function which can be called in the form
`func(x, axis=axis, *... |
def detect_client_auth_request(server_handshake_bytes):
"""
Determines if a CertificateRequest message is sent from the server asking
the client for a certificate
:param server_handshake_bytes:
A byte string of the handshake data received from the server
:return:
A boolean - if a c... | Determines if a CertificateRequest message is sent from the server asking
the client for a certificate
:param server_handshake_bytes:
A byte string of the handshake data received from the server
:return:
A boolean - if a client certificate request was found | Below is the the instruction that describes the task:
### Input:
Determines if a CertificateRequest message is sent from the server asking
the client for a certificate
:param server_handshake_bytes:
A byte string of the handshake data received from the server
:return:
A boolean - if a ... |
def element_attribs_to_dict(self, element):
"""
Convert the ``.attrib`` attributes of an etree element into a dict,
leaving out the xml:id attribute. Each key will be prepended by graph's
namespace.
"""
return {self.ns+':'+key: val for (key, val) in element.attrib.items()... | Convert the ``.attrib`` attributes of an etree element into a dict,
leaving out the xml:id attribute. Each key will be prepended by graph's
namespace. | Below is the the instruction that describes the task:
### Input:
Convert the ``.attrib`` attributes of an etree element into a dict,
leaving out the xml:id attribute. Each key will be prepended by graph's
namespace.
### Response:
def element_attribs_to_dict(self, element):
"""
Conve... |
def report_changes(self, content):
"""
1) Write changes in file,
2) Commit changes in git
3.1) If something changed, return tuple(True, changes)
3.2) If nothing changed, return tuple(False, None)
If style is "verbose", return changes in human-friendly format,
els... | 1) Write changes in file,
2) Commit changes in git
3.1) If something changed, return tuple(True, changes)
3.2) If nothing changed, return tuple(False, None)
If style is "verbose", return changes in human-friendly format,
else use unified diff | Below is the the instruction that describes the task:
### Input:
1) Write changes in file,
2) Commit changes in git
3.1) If something changed, return tuple(True, changes)
3.2) If nothing changed, return tuple(False, None)
If style is "verbose", return changes in human-friendly forma... |
def maxchord(A, ve = None):
"""
Maximal chordal subgraph of sparsity graph.
Returns a lower triangular sparse matrix which is the projection
of :math:`A` on a maximal chordal subgraph and a perfect
elimination order :math:`p`. Only the
lower triangular part of :math:`A` is accessed. The
opt... | Maximal chordal subgraph of sparsity graph.
Returns a lower triangular sparse matrix which is the projection
of :math:`A` on a maximal chordal subgraph and a perfect
elimination order :math:`p`. Only the
lower triangular part of :math:`A` is accessed. The
optional argument `ve` is the index of the ... | Below is the the instruction that describes the task:
### Input:
Maximal chordal subgraph of sparsity graph.
Returns a lower triangular sparse matrix which is the projection
of :math:`A` on a maximal chordal subgraph and a perfect
elimination order :math:`p`. Only the
lower triangular part of :math... |
def monitor_session_span_command_src_tengigabitethernet(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
monitor = ET.SubElement(config, "monitor", xmlns="urn:brocade.com:mgmt:brocade-span")
session = ET.SubElement(monitor, "session")
session_numb... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def monitor_session_span_command_src_tengigabitethernet(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
monitor = ET.SubElement(config, "monitor", xmlns="urn:... |
def start_semester_view(request):
"""
Initiates a semester"s worth of workshift, with the option to copy
workshift types from the previous semester.
"""
page_name = "Start Semester"
year, season = utils.get_year_season()
start_date, end_date = utils.get_semester_start_end(year, season)
... | Initiates a semester"s worth of workshift, with the option to copy
workshift types from the previous semester. | Below is the the instruction that describes the task:
### Input:
Initiates a semester"s worth of workshift, with the option to copy
workshift types from the previous semester.
### Response:
def start_semester_view(request):
"""
Initiates a semester"s worth of workshift, with the option to copy
work... |
def get_opts(opts):
"""
Validate options and apply defaults for options not supplied.
:param opts: dictionary mapping str->str.
:return: dictionary mapping str->Opt. All possible keys are present.
"""
defaults = {
'board': None,
'terrain': Opt.random,
'numbers': Opt.pres... | Validate options and apply defaults for options not supplied.
:param opts: dictionary mapping str->str.
:return: dictionary mapping str->Opt. All possible keys are present. | Below is the the instruction that describes the task:
### Input:
Validate options and apply defaults for options not supplied.
:param opts: dictionary mapping str->str.
:return: dictionary mapping str->Opt. All possible keys are present.
### Response:
def get_opts(opts):
"""
Validate options and a... |
def getOutputElementCount(self, name):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`.
"""
if name == 'categoriesOut':
return self.maxCategoryCount
elif name == 'categoryProbabilitiesOut':
return self.maxCategoryCount
elif name == 'bestPrototypeI... | Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`. | Below is the the instruction that describes the task:
### Input:
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`.
### Response:
def getOutputElementCount(self, name):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`.
"""
if name =... |
def setHolidayDates(self, cmd_dict=None, password="00000000"):
""" Serial call to set holiday list.
If a buffer dictionary is not supplied, the method will use
the class object buffer populated with assignHolidayDate.
Args:
cmd_dict (dict): Optional dictionary of holidays.
... | Serial call to set holiday list.
If a buffer dictionary is not supplied, the method will use
the class object buffer populated with assignHolidayDate.
Args:
cmd_dict (dict): Optional dictionary of holidays.
password (str): Optional password.
Returns:
... | Below is the the instruction that describes the task:
### Input:
Serial call to set holiday list.
If a buffer dictionary is not supplied, the method will use
the class object buffer populated with assignHolidayDate.
Args:
cmd_dict (dict): Optional dictionary of holidays.
... |
def from_dict(cls, d):
"""
Reconstructs the SimplestChemenvStrategy object from a dict representation of the SimplestChemenvStrategy object
created using the as_dict method.
:param d: dict representation of the SimplestChemenvStrategy object
:return: StructureEnvironments object
... | Reconstructs the SimplestChemenvStrategy object from a dict representation of the SimplestChemenvStrategy object
created using the as_dict method.
:param d: dict representation of the SimplestChemenvStrategy object
:return: StructureEnvironments object | Below is the the instruction that describes the task:
### Input:
Reconstructs the SimplestChemenvStrategy object from a dict representation of the SimplestChemenvStrategy object
created using the as_dict method.
:param d: dict representation of the SimplestChemenvStrategy object
:return: Str... |
def tiles(self):
""" Iterate over tile images of this layer
This is an optimised generator function that returns
(tile_x, tile_y, tile_image) tuples,
:rtype: Generator
:return: (x, y, image) tuples
"""
images = self.parent.images
for x, y, gid in [i for ... | Iterate over tile images of this layer
This is an optimised generator function that returns
(tile_x, tile_y, tile_image) tuples,
:rtype: Generator
:return: (x, y, image) tuples | Below is the the instruction that describes the task:
### Input:
Iterate over tile images of this layer
This is an optimised generator function that returns
(tile_x, tile_y, tile_image) tuples,
:rtype: Generator
:return: (x, y, image) tuples
### Response:
def tiles(self):
... |
def setup(self):
"""Get default configuration."""
self.allow = self.config['allow']
self.halt = self.config['halt']
self.skip = self.config['skip'] | Get default configuration. | Below is the the instruction that describes the task:
### Input:
Get default configuration.
### Response:
def setup(self):
"""Get default configuration."""
self.allow = self.config['allow']
self.halt = self.config['halt']
self.skip = self.config['skip'] |
def remove_all_locks(self):
"""Removes all locks and ensures their content is written to disk."""
locks = list(self._locks.items())
locks.sort(key=lambda l: l[1].get_last_access())
for l in locks:
self._remove_lock(l[0]) | Removes all locks and ensures their content is written to disk. | Below is the the instruction that describes the task:
### Input:
Removes all locks and ensures their content is written to disk.
### Response:
def remove_all_locks(self):
"""Removes all locks and ensures their content is written to disk."""
locks = list(self._locks.items())
locks.sort(key=l... |
def show_in_view(self, sourceview, matches, targetname=None):
""" Show search result in ncurses view.
"""
append = self.options.append_view or self.options.alter_view == 'append'
remove = self.options.alter_view == 'remove'
action_name = ', appending to' if append else ', removin... | Show search result in ncurses view. | Below is the the instruction that describes the task:
### Input:
Show search result in ncurses view.
### Response:
def show_in_view(self, sourceview, matches, targetname=None):
""" Show search result in ncurses view.
"""
append = self.options.append_view or self.options.alter_view == 'appen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.