code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def save_model(self, request, obj, form, change):
"""
Sends a tweet with the title/short_url if applicable.
"""
super(TweetableAdminMixin, self).save_model(request, obj, form, change)
if Api and request.POST.get("send_tweet", False):
auth_settings = get_auth_settings(... | Sends a tweet with the title/short_url if applicable. | Below is the the instruction that describes the task:
### Input:
Sends a tweet with the title/short_url if applicable.
### Response:
def save_model(self, request, obj, form, change):
"""
Sends a tweet with the title/short_url if applicable.
"""
super(TweetableAdminMixin, self).save_... |
def add_context_action(self, action):
"""
Adds a custom context menu action
:param action: action to add.
"""
self.main_tab_widget.context_actions.append(action)
for child_splitter in self.child_splitters:
child_splitter.add_context_action(action) | Adds a custom context menu action
:param action: action to add. | Below is the the instruction that describes the task:
### Input:
Adds a custom context menu action
:param action: action to add.
### Response:
def add_context_action(self, action):
"""
Adds a custom context menu action
:param action: action to add.
"""
self.main_ta... |
def capture_update_from_model(cls, table_name, record_id, *, update_fields=()):
"""
Create a fresh update record from the current model state in the database.
For read-write connected models, this will lead to the attempted update of the values of
a corresponding object in Salesforce.
... | Create a fresh update record from the current model state in the database.
For read-write connected models, this will lead to the attempted update of the values of
a corresponding object in Salesforce.
Args:
table_name (str): The name of the table backing the connected model (witho... | Below is the the instruction that describes the task:
### Input:
Create a fresh update record from the current model state in the database.
For read-write connected models, this will lead to the attempted update of the values of
a corresponding object in Salesforce.
Args:
table... |
def defvalkey(js, key, default=None, take_none=True):
"""
Returns js[key] if set, otherwise default. Note js[key] can be None.
:param js:
:param key:
:param default:
:param take_none:
:return:
"""
if js is None:
return default
if key not in js:
return default
... | Returns js[key] if set, otherwise default. Note js[key] can be None.
:param js:
:param key:
:param default:
:param take_none:
:return: | Below is the the instruction that describes the task:
### Input:
Returns js[key] if set, otherwise default. Note js[key] can be None.
:param js:
:param key:
:param default:
:param take_none:
:return:
### Response:
def defvalkey(js, key, default=None, take_none=True):
"""
Returns js[key]... |
def xsl_elements(self):
"""Find all "XSL" styled runs, normalize related paragraph and returns list of XslElements"""
def append_xsl_elements(xsl_elements, r, xsl):
if r is not None:
r.xpath('.//w:t', namespaces=self.namespaces)[0].text = xsl
xe = XslElement... | Find all "XSL" styled runs, normalize related paragraph and returns list of XslElements | Below is the the instruction that describes the task:
### Input:
Find all "XSL" styled runs, normalize related paragraph and returns list of XslElements
### Response:
def xsl_elements(self):
"""Find all "XSL" styled runs, normalize related paragraph and returns list of XslElements"""
def append_xs... |
def set_updated(self):
"""
Mark the module as updated.
We check if the actual content has changed and if so we trigger an
update in py3status.
"""
# get latest output
output = []
for method in self.methods.values():
data = method["last_output"]... | Mark the module as updated.
We check if the actual content has changed and if so we trigger an
update in py3status. | Below is the the instruction that describes the task:
### Input:
Mark the module as updated.
We check if the actual content has changed and if so we trigger an
update in py3status.
### Response:
def set_updated(self):
"""
Mark the module as updated.
We check if the actual co... |
def projScatter(lon, lat, **kwargs):
"""
Create a scatter plot on HEALPix projected axes.
Inputs: lon (deg), lat (deg)
"""
hp.projscatter(lon, lat, lonlat=True, **kwargs) | Create a scatter plot on HEALPix projected axes.
Inputs: lon (deg), lat (deg) | Below is the the instruction that describes the task:
### Input:
Create a scatter plot on HEALPix projected axes.
Inputs: lon (deg), lat (deg)
### Response:
def projScatter(lon, lat, **kwargs):
"""
Create a scatter plot on HEALPix projected axes.
Inputs: lon (deg), lat (deg)
"""
hp.projscat... |
async def set_custom_eq(self, target: str, value: str) -> None:
"""Set custom EQ settings."""
params = {"settings": [{"target": target, "value": value}]}
return await self.services["audio"]["setCustomEqualizerSettings"](params) | Set custom EQ settings. | Below is the the instruction that describes the task:
### Input:
Set custom EQ settings.
### Response:
async def set_custom_eq(self, target: str, value: str) -> None:
"""Set custom EQ settings."""
params = {"settings": [{"target": target, "value": value}]}
return await self.services["audio"... |
def create_hit(MaxAssignments=None, AutoApprovalDelayInSeconds=None, LifetimeInSeconds=None, AssignmentDurationInSeconds=None, Reward=None, Title=None, Keywords=None, Description=None, Question=None, RequesterAnnotation=None, QualificationRequirements=None, UniqueRequestToken=None, AssignmentReviewPolicy=None, HITRevie... | The CreateHIT operation creates a new Human Intelligence Task (HIT). The new HIT is made available for Workers to find and accept on the Amazon Mechanical Turk website.
This operation allows you to specify a new HIT by passing in values for the properties of the HIT, such as its title, reward amount and number of a... | Below is the the instruction that describes the task:
### Input:
The CreateHIT operation creates a new Human Intelligence Task (HIT). The new HIT is made available for Workers to find and accept on the Amazon Mechanical Turk website.
This operation allows you to specify a new HIT by passing in values for the pr... |
def register_service(cls, primary_key_type):
"""Register an API service endpoint.
:param cls: The class to register
:param str primary_key_type: The type (as a string) of the primary_key
field
"""
view_func = cls.as_view(cls.__name__.lower()) # pylint: disable=no-m... | Register an API service endpoint.
:param cls: The class to register
:param str primary_key_type: The type (as a string) of the primary_key
field | Below is the the instruction that describes the task:
### Input:
Register an API service endpoint.
:param cls: The class to register
:param str primary_key_type: The type (as a string) of the primary_key
field
### Response:
def register_service(cls, primary_key_type):
... |
def cat_extract(tar, member, targetpath):
"""Extract a regular file member using cat for async-like I/O
Mostly adapted from tarfile.py.
"""
assert member.isreg()
# Fetch the TarInfo object for the given name and build the
# destination pathname, replacing forward slashes to platform
# spe... | Extract a regular file member using cat for async-like I/O
Mostly adapted from tarfile.py. | Below is the the instruction that describes the task:
### Input:
Extract a regular file member using cat for async-like I/O
Mostly adapted from tarfile.py.
### Response:
def cat_extract(tar, member, targetpath):
"""Extract a regular file member using cat for async-like I/O
Mostly adapted from tarfile... |
def _merge_constraints(constraints, overrides):
"""Merge the constraints avoiding duplicates
Change constraints in place.
"""
for o in overrides:
i = 0
while i < len(constraints):
c = constraints[i]
if _same(o, c):
constraints[i].update(o)
... | Merge the constraints avoiding duplicates
Change constraints in place. | Below is the the instruction that describes the task:
### Input:
Merge the constraints avoiding duplicates
Change constraints in place.
### Response:
def _merge_constraints(constraints, overrides):
"""Merge the constraints avoiding duplicates
Change constraints in place.
"""
for o in overrides:... |
def densenet121(num_classes=1000, pretrained='imagenet'):
r"""Densenet-121 model from
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
"""
model = models.densenet121(pretrained=False)
if pretrained is not None:
settings = pretrained_settings['densenet121'][... | r"""Densenet-121 model from
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>` | Below is the the instruction that describes the task:
### Input:
r"""Densenet-121 model from
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
### Response:
def densenet121(num_classes=1000, pretrained='imagenet'):
r"""Densenet-121 model from
`"Densely Connected Convol... |
def get_preferred_partition(self, broker, sibling_distance):
"""The preferred partition belongs to the topic with the minimum
(also negative) distance between destination and source.
:param broker: Destination broker
:param sibling_distance: dict {topic: distance} negative distance sho... | The preferred partition belongs to the topic with the minimum
(also negative) distance between destination and source.
:param broker: Destination broker
:param sibling_distance: dict {topic: distance} negative distance should
mean that destination broker has got less partition of a... | Below is the the instruction that describes the task:
### Input:
The preferred partition belongs to the topic with the minimum
(also negative) distance between destination and source.
:param broker: Destination broker
:param sibling_distance: dict {topic: distance} negative distance should... |
def audit(**kwargs):
"""
use this decorator to audit an operation
"""
def wrap(fn):
@functools.wraps(fn)
def advice(parent_object, *args, **kw):
request = parent_object.request
wijziging = request.audit_manager.create_revision()
result = fn(parent_o... | use this decorator to audit an operation | Below is the the instruction that describes the task:
### Input:
use this decorator to audit an operation
### Response:
def audit(**kwargs):
"""
use this decorator to audit an operation
"""
def wrap(fn):
@functools.wraps(fn)
def advice(parent_object, *args, **kw):
requ... |
def reset_all_to_coefficients(self):
""" Resets the IOSystem and all extensions to coefficients.
This method calls reset_to_coefficients for the IOSystem and for
all Extensions in the system
Note
-----
The system can not be reconstructed after this steps
becaus... | Resets the IOSystem and all extensions to coefficients.
This method calls reset_to_coefficients for the IOSystem and for
all Extensions in the system
Note
-----
The system can not be reconstructed after this steps
because all absolute data is removed. Save the Y data i... | Below is the the instruction that describes the task:
### Input:
Resets the IOSystem and all extensions to coefficients.
This method calls reset_to_coefficients for the IOSystem and for
all Extensions in the system
Note
-----
The system can not be reconstructed after this ... |
def angle(self, center1_x, center1_y, center2_x, center2_y):
"""
compute the rotation angle of the dipole
:return:
"""
phi_G = np.arctan2(center2_y - center1_y, center2_x - center1_x)
return phi_G | compute the rotation angle of the dipole
:return: | Below is the the instruction that describes the task:
### Input:
compute the rotation angle of the dipole
:return:
### Response:
def angle(self, center1_x, center1_y, center2_x, center2_y):
"""
compute the rotation angle of the dipole
:return:
"""
phi_G = np.arctan2(... |
def stream_via(self, reactor, host, port,
socks_endpoint,
use_tls=False):
"""
This returns an `IStreamClientEndpoint`_ that will connect to
the given ``host``, ``port`` via Tor -- and via this
parciular circuit.
We match the streams up using... | This returns an `IStreamClientEndpoint`_ that will connect to
the given ``host``, ``port`` via Tor -- and via this
parciular circuit.
We match the streams up using their source-ports, so even if
there are many streams in-flight to the same destination they
will align correctly. ... | Below is the the instruction that describes the task:
### Input:
This returns an `IStreamClientEndpoint`_ that will connect to
the given ``host``, ``port`` via Tor -- and via this
parciular circuit.
We match the streams up using their source-ports, so even if
there are many streams ... |
def _get_logger_for_instance(self, instance: typing.Any) -> logging.Logger:
"""Get logger for log calls.
:param instance: Owner class instance. Filled only if instance created, else None.
:type instance: typing.Optional[owner]
:return: logger instance
:rtype: logging.Logger
... | Get logger for log calls.
:param instance: Owner class instance. Filled only if instance created, else None.
:type instance: typing.Optional[owner]
:return: logger instance
:rtype: logging.Logger | Below is the the instruction that describes the task:
### Input:
Get logger for log calls.
:param instance: Owner class instance. Filled only if instance created, else None.
:type instance: typing.Optional[owner]
:return: logger instance
:rtype: logging.Logger
### Response:
def _ge... |
def find_by_extension(extension):
"""
Find and return a format by extension.
:param extension: A string describing the extension of the format.
"""
for format in FORMATS:
if extension in format.extensions:
return format
raise UnknownFormat('No format found with extension "%... | Find and return a format by extension.
:param extension: A string describing the extension of the format. | Below is the the instruction that describes the task:
### Input:
Find and return a format by extension.
:param extension: A string describing the extension of the format.
### Response:
def find_by_extension(extension):
"""
Find and return a format by extension.
:param extension: A string describi... |
def tags(self):
"""
A dictionary that maps tag names to :class:`Revision` objects.
Here's an example based on a mirror of the git project's repository:
>>> from pprint import pprint
>>> from vcs_repo_mgr.backends.git import GitRepo
>>> repository = GitRepo(remote='https... | A dictionary that maps tag names to :class:`Revision` objects.
Here's an example based on a mirror of the git project's repository:
>>> from pprint import pprint
>>> from vcs_repo_mgr.backends.git import GitRepo
>>> repository = GitRepo(remote='https://github.com/git/git.git')
... | Below is the the instruction that describes the task:
### Input:
A dictionary that maps tag names to :class:`Revision` objects.
Here's an example based on a mirror of the git project's repository:
>>> from pprint import pprint
>>> from vcs_repo_mgr.backends.git import GitRepo
>>> r... |
def print_block_num_row(block_num, cliques, next_cliques):
"""Print out a row of padding and a row with the block number. Includes
the branches prior to this block number."""
n_cliques = len(cliques)
if n_cliques == 0:
print('| {}'.format(block_num))
return
def mapper(clique):
... | Print out a row of padding and a row with the block number. Includes
the branches prior to this block number. | Below is the the instruction that describes the task:
### Input:
Print out a row of padding and a row with the block number. Includes
the branches prior to this block number.
### Response:
def print_block_num_row(block_num, cliques, next_cliques):
"""Print out a row of padding and a row with the block numb... |
def _ast_op_concat_to_code(self, opr, *, ignore_whitespace, **kwargs):
"""Convert an AST concatenate op to python source code."""
hoist_target = OP_CONCAT if ignore_whitespace else OP_WS_CONCAT
operands = self._hoist_operands(opr.operands, lambda t: isinstance(t, OptreeNode) and t.opnode.operator is hoist_t... | Convert an AST concatenate op to python source code. | Below is the the instruction that describes the task:
### Input:
Convert an AST concatenate op to python source code.
### Response:
def _ast_op_concat_to_code(self, opr, *, ignore_whitespace, **kwargs):
"""Convert an AST concatenate op to python source code."""
hoist_target = OP_CONCAT if ignore_whitespace... |
def interpolate_xarray_linear(xpoints, ypoints, values, shape, chunks=CHUNK_SIZE):
"""Interpolate linearly, generating a dask array."""
from scipy.interpolate.interpnd import (LinearNDInterpolator,
_ndim_coords_from_arrays)
if isinstance(chunks, (list, tuple)):
... | Interpolate linearly, generating a dask array. | Below is the the instruction that describes the task:
### Input:
Interpolate linearly, generating a dask array.
### Response:
def interpolate_xarray_linear(xpoints, ypoints, values, shape, chunks=CHUNK_SIZE):
"""Interpolate linearly, generating a dask array."""
from scipy.interpolate.interpnd import (Linea... |
def run(arguments):
"""Main function for command line usage"""
parser = argparse.ArgumentParser(
description="Exports font icons as PNG images."
)
parser.add_argument(
'--list',
action='store_true',
help="list all available icon names and exit"
)
parser.add_argume... | Main function for command line usage | Below is the the instruction that describes the task:
### Input:
Main function for command line usage
### Response:
def run(arguments):
"""Main function for command line usage"""
parser = argparse.ArgumentParser(
description="Exports font icons as PNG images."
)
parser.add_argument(
... |
def confd_state_rest_listen_tcp_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
rest = ET.SubElement(confd_state, "rest")
listen = ET.SubElem... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def confd_state_rest_listen_tcp_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.c... |
def moments(self):
"""The first two time delay weighted statistical moments of the
MA coefficients."""
moment1 = statstools.calc_mean_time(self.delays, self.coefs)
moment2 = statstools.calc_mean_time_deviation(
self.delays, self.coefs, moment1)
return numpy.array([mom... | The first two time delay weighted statistical moments of the
MA coefficients. | Below is the the instruction that describes the task:
### Input:
The first two time delay weighted statistical moments of the
MA coefficients.
### Response:
def moments(self):
"""The first two time delay weighted statistical moments of the
MA coefficients."""
moment1 = statstools.ca... |
def interm_range_type(self) -> Sequence[str]:
'''The range type of each intermediate fluent in canonical order.
Returns:
Sequence[str]: A tuple of range types representing
the range of each fluent.
'''
fluents = self.domain.intermediate_fluents
ordering =... | The range type of each intermediate fluent in canonical order.
Returns:
Sequence[str]: A tuple of range types representing
the range of each fluent. | Below is the the instruction that describes the task:
### Input:
The range type of each intermediate fluent in canonical order.
Returns:
Sequence[str]: A tuple of range types representing
the range of each fluent.
### Response:
def interm_range_type(self) -> Sequence[str]:
... |
def _init_tag_params(self, tag, params):
"""
Alternative constructor used when the tag parameters are added to the
HTMLElement (HTMLElement(tag, params)).
This method just creates string and then pass it to the
:meth:`_init_tag`.
Args:
tag (str): HTML tag as... | Alternative constructor used when the tag parameters are added to the
HTMLElement (HTMLElement(tag, params)).
This method just creates string and then pass it to the
:meth:`_init_tag`.
Args:
tag (str): HTML tag as string.
params (dict): HTML tag parameters as di... | Below is the the instruction that describes the task:
### Input:
Alternative constructor used when the tag parameters are added to the
HTMLElement (HTMLElement(tag, params)).
This method just creates string and then pass it to the
:meth:`_init_tag`.
Args:
tag (str): HTM... |
def checkPortIsOpen(remoteServerHost=ServerHost, port = Port):
'''
Checks if the specified port is open
:param remoteServerHost: the host address
:param port: port which needs to be checked
:return: ``True`` if port is open, ``False`` otherwise
'''
remoteServerIP = socket.gethostbyname(remo... | Checks if the specified port is open
:param remoteServerHost: the host address
:param port: port which needs to be checked
:return: ``True`` if port is open, ``False`` otherwise | Below is the the instruction that describes the task:
### Input:
Checks if the specified port is open
:param remoteServerHost: the host address
:param port: port which needs to be checked
:return: ``True`` if port is open, ``False`` otherwise
### Response:
def checkPortIsOpen(remoteServerHost=ServerHos... |
def check_cmake_exists(cmake_command):
"""
Check whether CMake is installed. If not, print
informative error message and quits.
"""
from subprocess import Popen, PIPE
p = Popen(
'{0} --version'.format(cmake_command),
shell=True,
stdin=PIPE,
stdout=PIPE)
if no... | Check whether CMake is installed. If not, print
informative error message and quits. | Below is the the instruction that describes the task:
### Input:
Check whether CMake is installed. If not, print
informative error message and quits.
### Response:
def check_cmake_exists(cmake_command):
"""
Check whether CMake is installed. If not, print
informative error message and quits.
"""... |
def occurrence(self, file_name=None, path=None, date=None):
"""Add a file Occurrence.
Args:
file_name (str, optional): The file name for this occurrence.
path (str, optional): The file path for this occurrence.
date (str, optional): The datetime expression for this o... | Add a file Occurrence.
Args:
file_name (str, optional): The file name for this occurrence.
path (str, optional): The file path for this occurrence.
date (str, optional): The datetime expression for this occurrence.
Returns:
obj: An instance of Occurrence... | Below is the the instruction that describes the task:
### Input:
Add a file Occurrence.
Args:
file_name (str, optional): The file name for this occurrence.
path (str, optional): The file path for this occurrence.
date (str, optional): The datetime expression for this occ... |
def _addPort(n: LNode, lp: LPort, intf: Interface,
reverseDirection=False):
"""
add port to LPort for interface
"""
origin = originObjOfPort(intf)
d = intf._direction
d = PortTypeFromDir(d)
if reverseDirection:
d = PortType.opposite(d)
new_lp = LPort(lp, d, lp.side... | add port to LPort for interface | Below is the the instruction that describes the task:
### Input:
add port to LPort for interface
### Response:
def _addPort(n: LNode, lp: LPort, intf: Interface,
reverseDirection=False):
"""
add port to LPort for interface
"""
origin = originObjOfPort(intf)
d = intf._direction
... |
def periodic_callback(self):
"""Periodic cleanup tasks to maintain this adapter, should be called every second. """
if self.stopped:
return
# Check if we should start scanning again
if not self.scanning and len(self.connections.get_connections()) == 0:
self._log... | Periodic cleanup tasks to maintain this adapter, should be called every second. | Below is the the instruction that describes the task:
### Input:
Periodic cleanup tasks to maintain this adapter, should be called every second.
### Response:
def periodic_callback(self):
"""Periodic cleanup tasks to maintain this adapter, should be called every second. """
if self.stopped:
... |
def atlas_find_missing_zonefile_availability( peer_table=None, con=None, path=None, missing_zonefile_info=None ):
"""
Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missing from
... | Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missing from
our clique (and we'll re-sync our neighborss' inventories
every so often to make sure we detect when zonefiles
becom... | Below is the the instruction that describes the task:
### Input:
Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missing from
our clique (and we'll re-sync our neighborss' inventori... |
def _getCharFont(self, font_files, code_point):
"""
Returns font files containing given code point.
"""
return_font_files = []
for font_file in font_files:
face = ft.Face(font_file)
if face.get_char_index(code_point):
return_font_files.appe... | Returns font files containing given code point. | Below is the the instruction that describes the task:
### Input:
Returns font files containing given code point.
### Response:
def _getCharFont(self, font_files, code_point):
"""
Returns font files containing given code point.
"""
return_font_files = []
for font_file in font... |
def Zabransky_quasi_polynomial_integral(T, Tc, a1, a2, a3, a4, a5, a6):
r'''Calculates the integral of liquid heat capacity using the
quasi-polynomial model developed in [1]_.
Parameters
----------
T : float
Temperature [K]
a1-a6 : float
Coefficients
Returns
-------
... | r'''Calculates the integral of liquid heat capacity using the
quasi-polynomial model developed in [1]_.
Parameters
----------
T : float
Temperature [K]
a1-a6 : float
Coefficients
Returns
-------
H : float
Difference in enthalpy from 0 K, [J/mol]
Notes
... | Below is the the instruction that describes the task:
### Input:
r'''Calculates the integral of liquid heat capacity using the
quasi-polynomial model developed in [1]_.
Parameters
----------
T : float
Temperature [K]
a1-a6 : float
Coefficients
Returns
-------
H : ... |
def _open_fp(self, fp):
# type: (BinaryIO) -> None
'''
An internal method to open an existing ISO for inspection and
modification. Note that the file object passed in here must stay open
for the lifetime of this object, as the PyCdlib class uses it internally
to do writi... | An internal method to open an existing ISO for inspection and
modification. Note that the file object passed in here must stay open
for the lifetime of this object, as the PyCdlib class uses it internally
to do writing and reading operations.
Parameters:
fp - The file object c... | Below is the the instruction that describes the task:
### Input:
An internal method to open an existing ISO for inspection and
modification. Note that the file object passed in here must stay open
for the lifetime of this object, as the PyCdlib class uses it internally
to do writing and rea... |
def SetDayOfWeekHasService(self, dow, has_service=True):
"""Set service as running (or not) on a day of the week. By default the
service does not run on any days.
Args:
dow: 0 for Monday through 6 for Sunday
has_service: True if this service operates on dow, False if it does not.
Returns:
... | Set service as running (or not) on a day of the week. By default the
service does not run on any days.
Args:
dow: 0 for Monday through 6 for Sunday
has_service: True if this service operates on dow, False if it does not.
Returns:
None | Below is the the instruction that describes the task:
### Input:
Set service as running (or not) on a day of the week. By default the
service does not run on any days.
Args:
dow: 0 for Monday through 6 for Sunday
has_service: True if this service operates on dow, False if it does not.
Retu... |
def future_check_request(self, name, update=None):
"""Check if the request exists.
Used internally by future_get_request. This method is aware of
synchronisation in progress and if inspection of the server is allowed.
Parameters
----------
name : str
Name of... | Check if the request exists.
Used internally by future_get_request. This method is aware of
synchronisation in progress and if inspection of the server is allowed.
Parameters
----------
name : str
Name of the request to verify.
update : bool or None, optiona... | Below is the the instruction that describes the task:
### Input:
Check if the request exists.
Used internally by future_get_request. This method is aware of
synchronisation in progress and if inspection of the server is allowed.
Parameters
----------
name : str
... |
def client_has_user_consent(self):
"""
Check if already exists user consent for some client.
Return bool.
"""
value = False
try:
uc = UserConsent.objects.get(user=self.request.user, client=self.client)
if (set(self.params['scope']).issubset(uc.sco... | Check if already exists user consent for some client.
Return bool. | Below is the the instruction that describes the task:
### Input:
Check if already exists user consent for some client.
Return bool.
### Response:
def client_has_user_consent(self):
"""
Check if already exists user consent for some client.
Return bool.
"""
value = F... |
def note_on(self, channel, note, velocity):
"""Return bytes for a 'note_on' event."""
return self.midi_event(NOTE_ON, channel, note, velocity) | Return bytes for a 'note_on' event. | Below is the the instruction that describes the task:
### Input:
Return bytes for a 'note_on' event.
### Response:
def note_on(self, channel, note, velocity):
"""Return bytes for a 'note_on' event."""
return self.midi_event(NOTE_ON, channel, note, velocity) |
def joint(node):
"""Merge the bodies of primal and adjoint into a single function.
Args:
node: A module with the primal and adjoint function definitions as returned
by `reverse_ad`.
Returns:
func: A `Module` node with a single function definition containing the
combined primal and adjoin... | Merge the bodies of primal and adjoint into a single function.
Args:
node: A module with the primal and adjoint function definitions as returned
by `reverse_ad`.
Returns:
func: A `Module` node with a single function definition containing the
combined primal and adjoint. | Below is the the instruction that describes the task:
### Input:
Merge the bodies of primal and adjoint into a single function.
Args:
node: A module with the primal and adjoint function definitions as returned
by `reverse_ad`.
Returns:
func: A `Module` node with a single function definition co... |
def load_spitzer_catalog(show_progress=False): # pragma: no cover
"""
Load a 4.5 micron Spitzer catalog.
The image from which this catalog was derived is returned by
:func:`load_spitzer_image`.
Parameters
----------
show_progress : bool, optional
Whether to display a progress ba... | Load a 4.5 micron Spitzer catalog.
The image from which this catalog was derived is returned by
:func:`load_spitzer_image`.
Parameters
----------
show_progress : bool, optional
Whether to display a progress bar during the download (default
is `False`).
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
Load a 4.5 micron Spitzer catalog.
The image from which this catalog was derived is returned by
:func:`load_spitzer_image`.
Parameters
----------
show_progress : bool, optional
Whether to display a progress bar during the... |
def _num_samples(x):
"""Return number of samples in array-like x."""
if not hasattr(x, '__len__') and not hasattr(x, 'shape'):
if hasattr(x, '__array__'):
x = np.asarray(x)
else:
raise TypeError("Expected sequence or array-like, got %r" % x)
return x.shape[0] if hasat... | Return number of samples in array-like x. | Below is the the instruction that describes the task:
### Input:
Return number of samples in array-like x.
### Response:
def _num_samples(x):
"""Return number of samples in array-like x."""
if not hasattr(x, '__len__') and not hasattr(x, 'shape'):
if hasattr(x, '__array__'):
x = np.asar... |
def handle_data(self, data):
"""Callback when the data of a tag has been collected."""
# Only process the data when we are in an active a tag and have an URL.
if not self.active_url:
return
# The visible text can have a final slash so strip it off
if data.strip('/') ... | Callback when the data of a tag has been collected. | Below is the the instruction that describes the task:
### Input:
Callback when the data of a tag has been collected.
### Response:
def handle_data(self, data):
"""Callback when the data of a tag has been collected."""
# Only process the data when we are in an active a tag and have an URL.
i... |
def gamma_centered(cls, kpts=(1, 1, 1), use_symmetries=True, use_time_reversal=True):
"""
Convenient static constructor for an automatic Gamma centered Kpoint grid.
Args:
kpts: Subdivisions N_1, N_2 and N_3 along reciprocal lattice vectors.
use_symmetries: False if spati... | Convenient static constructor for an automatic Gamma centered Kpoint grid.
Args:
kpts: Subdivisions N_1, N_2 and N_3 along reciprocal lattice vectors.
use_symmetries: False if spatial symmetries should not be used
to reduce the number of independent k-points.
... | Below is the the instruction that describes the task:
### Input:
Convenient static constructor for an automatic Gamma centered Kpoint grid.
Args:
kpts: Subdivisions N_1, N_2 and N_3 along reciprocal lattice vectors.
use_symmetries: False if spatial symmetries should not be used
... |
def remove_origin(self, account_id, origin_id):
"""Removes an origin pull mapping with the given origin pull ID.
:param int account_id: the CDN account ID from which the mapping should
be deleted.
:param int origin_id: the origin pull mapping ID to delete.
... | Removes an origin pull mapping with the given origin pull ID.
:param int account_id: the CDN account ID from which the mapping should
be deleted.
:param int origin_id: the origin pull mapping ID to delete. | Below is the the instruction that describes the task:
### Input:
Removes an origin pull mapping with the given origin pull ID.
:param int account_id: the CDN account ID from which the mapping should
be deleted.
:param int origin_id: the origin pull mapping ID to delet... |
def groups(self):
"""Set of groups defined in the roster.
:Return: the groups
:ReturnType: `set` of `unicode`
"""
groups = set()
for item in self._items:
groups |= item.groups
return groups | Set of groups defined in the roster.
:Return: the groups
:ReturnType: `set` of `unicode` | Below is the the instruction that describes the task:
### Input:
Set of groups defined in the roster.
:Return: the groups
:ReturnType: `set` of `unicode`
### Response:
def groups(self):
"""Set of groups defined in the roster.
:Return: the groups
:ReturnType: `set` of `unic... |
def setupTable_cmap(self):
"""
Make the cmap table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "cmap" not in self.tables:
return
... | Make the cmap table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired. | Below is the the instruction that describes the task:
### Input:
Make the cmap table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
### Response:
def setupTable_cmap(self):
"""... |
def _cb_created(self, payload, duplicated):
"""Indirect callback (via Client) for point & subscription creation responses"""
if payload[P_RESOURCE] in _POINT_TYPE_TO_CLASS:
store = self.__new_feeds if payload[P_RESOURCE] == R_FEED else self.__new_controls
cls = _POINT_TYPE_TO_CLA... | Indirect callback (via Client) for point & subscription creation responses | Below is the the instruction that describes the task:
### Input:
Indirect callback (via Client) for point & subscription creation responses
### Response:
def _cb_created(self, payload, duplicated):
"""Indirect callback (via Client) for point & subscription creation responses"""
if payload[P_RESOURC... |
def translate_addresstype(f):
"""decorator to translate the addressType field.
translate the value of the addressType field of the API response into a
translated type.
"""
@wraps(f)
def wr(r, pc):
at = r["addressType"]
try:
r.update({"addressType": POSTCODE_API_TYPED... | decorator to translate the addressType field.
translate the value of the addressType field of the API response into a
translated type. | Below is the the instruction that describes the task:
### Input:
decorator to translate the addressType field.
translate the value of the addressType field of the API response into a
translated type.
### Response:
def translate_addresstype(f):
"""decorator to translate the addressType field.
tran... |
def update_task_redundancy(config, task_id, redundancy):
"""Update task redudancy for a project."""
if task_id is None:
msg = ("Are you sure you want to update all the tasks redundancy?")
if click.confirm(msg):
res = _update_tasks_redundancy(config, task_id, redundancy)
c... | Update task redudancy for a project. | Below is the the instruction that describes the task:
### Input:
Update task redudancy for a project.
### Response:
def update_task_redundancy(config, task_id, redundancy):
"""Update task redudancy for a project."""
if task_id is None:
msg = ("Are you sure you want to update all the tasks redundanc... |
def update_col(self, column_name, series):
"""
Add or replace a column in the underlying DataFrame.
Parameters
----------
column_name : str
Column to add or replace.
series : pandas.Series or sequence
Column data.
"""
logger.debug... | Add or replace a column in the underlying DataFrame.
Parameters
----------
column_name : str
Column to add or replace.
series : pandas.Series or sequence
Column data. | Below is the the instruction that describes the task:
### Input:
Add or replace a column in the underlying DataFrame.
Parameters
----------
column_name : str
Column to add or replace.
series : pandas.Series or sequence
Column data.
### Response:
def update_c... |
def appendpickle(table, source=None, protocol=-1, write_header=False):
"""
Append data to an existing pickle file. I.e.,
as :func:`petl.io.pickle.topickle` but the file is opened in append mode.
Note that no attempt is made to check that the fields or row lengths are
consistent with the existing da... | Append data to an existing pickle file. I.e.,
as :func:`petl.io.pickle.topickle` but the file is opened in append mode.
Note that no attempt is made to check that the fields or row lengths are
consistent with the existing data, the data rows from the table are simply
appended to the file. | Below is the the instruction that describes the task:
### Input:
Append data to an existing pickle file. I.e.,
as :func:`petl.io.pickle.topickle` but the file is opened in append mode.
Note that no attempt is made to check that the fields or row lengths are
consistent with the existing data, the data r... |
def show_feature_destibution(self, data = None):
"""!
@brief Shows feature distribution.
@details Only features in 1D, 2D, 3D space can be visualized.
@param[in] data (list): List of points that will be used for visualization, if it not specified than feature will be displa... | !
@brief Shows feature distribution.
@details Only features in 1D, 2D, 3D space can be visualized.
@param[in] data (list): List of points that will be used for visualization, if it not specified than feature will be displayed only. | Below is the the instruction that describes the task:
### Input:
!
@brief Shows feature distribution.
@details Only features in 1D, 2D, 3D space can be visualized.
@param[in] data (list): List of points that will be used for visualization, if it not specified than feature will b... |
def lookup_endpoint(cli):
"""Looks up the application endpoint from dotcloud"""
url = '/applications/{0}/environment'.format(APPNAME)
environ = cli.user.get(url).item
port = environ['DOTCLOUD_SATELLITE_ZMQ_PORT']
host = socket.gethostbyname(environ['DOTCLOUD_SATELLITE_ZMQ_HOST'])
return "tcp://{... | Looks up the application endpoint from dotcloud | Below is the the instruction that describes the task:
### Input:
Looks up the application endpoint from dotcloud
### Response:
def lookup_endpoint(cli):
"""Looks up the application endpoint from dotcloud"""
url = '/applications/{0}/environment'.format(APPNAME)
environ = cli.user.get(url).item
port ... |
def Decompress(self, compressed_data):
"""Decompresses the compressed data.
Args:
compressed_data (bytes): compressed data.
Returns:
tuple(bytes, bytes): uncompressed data and remaining compressed data.
Raises:
BackEndError: if the zlib compressed stream cannot be decompressed.
... | Decompresses the compressed data.
Args:
compressed_data (bytes): compressed data.
Returns:
tuple(bytes, bytes): uncompressed data and remaining compressed data.
Raises:
BackEndError: if the zlib compressed stream cannot be decompressed. | Below is the the instruction that describes the task:
### Input:
Decompresses the compressed data.
Args:
compressed_data (bytes): compressed data.
Returns:
tuple(bytes, bytes): uncompressed data and remaining compressed data.
Raises:
BackEndError: if the zlib compressed stream canno... |
def add_book_series(self, title, volume=None):
"""
:param volume: the volume of the book
:type volume: string
:param title: the title of the book
:type title: string
"""
book_series = {}
if title is not None:
book_series['title'] = title
... | :param volume: the volume of the book
:type volume: string
:param title: the title of the book
:type title: string | Below is the the instruction that describes the task:
### Input:
:param volume: the volume of the book
:type volume: string
:param title: the title of the book
:type title: string
### Response:
def add_book_series(self, title, volume=None):
"""
:param volume: the volume of ... |
def parse_complex(tree_to_parse, xpath_root, xpath_map, complex_key):
"""
Creates and returns a Dictionary data structure parsed from the metadata.
:param tree_to_parse: the XML tree compatible with element_utils to be parsed
:param xpath_root: the XPATH location of the structure inside the parent eleme... | Creates and returns a Dictionary data structure parsed from the metadata.
:param tree_to_parse: the XML tree compatible with element_utils to be parsed
:param xpath_root: the XPATH location of the structure inside the parent element
:param xpath_map: a dict of XPATHs corresponding to a complex definition
... | Below is the the instruction that describes the task:
### Input:
Creates and returns a Dictionary data structure parsed from the metadata.
:param tree_to_parse: the XML tree compatible with element_utils to be parsed
:param xpath_root: the XPATH location of the structure inside the parent element
:param... |
def _process_panel_configuration(self, config):
"""Add, remove and set default panels on the dashboard."""
try:
dashboard = config.get('PANEL_DASHBOARD')
if not dashboard:
LOG.warning("Skipping %s because it doesn't have "
"PANEL_DASHBO... | Add, remove and set default panels on the dashboard. | Below is the the instruction that describes the task:
### Input:
Add, remove and set default panels on the dashboard.
### Response:
def _process_panel_configuration(self, config):
"""Add, remove and set default panels on the dashboard."""
try:
dashboard = config.get('PANEL_DASHBOARD')
... |
def updateData(self, data):
""" Updates the data used by the renderer.
"""
# pylab.ion()
fig = pylab.figure(1)
n_agent = len(data)
idx = 1
for i, adata in enumerate(data):
saxis = fig.add_subplot(3, n_agent, i + 1)
saxis.plot(adata[0])
... | Updates the data used by the renderer. | Below is the the instruction that describes the task:
### Input:
Updates the data used by the renderer.
### Response:
def updateData(self, data):
""" Updates the data used by the renderer.
"""
# pylab.ion()
fig = pylab.figure(1)
n_agent = len(data)
idx = 1
f... |
def is_prefix(cls, path):
"""
Check if a path is a valid prefix
Args:
path(str): path to be checked
Returns:
bool: True if the given path is a prefix
"""
lagofile = paths.Paths(path).prefix_lagofile()
return os.path.isfile(lagofile) | Check if a path is a valid prefix
Args:
path(str): path to be checked
Returns:
bool: True if the given path is a prefix | Below is the the instruction that describes the task:
### Input:
Check if a path is a valid prefix
Args:
path(str): path to be checked
Returns:
bool: True if the given path is a prefix
### Response:
def is_prefix(cls, path):
"""
Check if a path is a valid p... |
def predict(self, h=5):
""" Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
Returns
----------
- pd.DataFrame with predicted values
"""
... | Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
Returns
----------
- pd.DataFrame with predicted values | Below is the the instruction that describes the task:
### Input:
Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
Returns
----------
- pd.DataFrame with p... |
def callback(self, request, **kwargs):
"""
Called from the Service when the user accept to activate it
"""
try:
client = self.get_evernote_client()
# finally we save the user auth token
# As we already stored the object ServicesActivated
... | Called from the Service when the user accept to activate it | Below is the the instruction that describes the task:
### Input:
Called from the Service when the user accept to activate it
### Response:
def callback(self, request, **kwargs):
"""
Called from the Service when the user accept to activate it
"""
try:
client = self.ge... |
def download_data(self, configuration, output_file):
"""
Выполняет указанный в конфигурации запрос и отдает файл на скачивание
:param configuration: Конфгурация запроса
:param output_file: Место, куда надо скачать файл
:return:
"""
params = configuration
r... | Выполняет указанный в конфигурации запрос и отдает файл на скачивание
:param configuration: Конфгурация запроса
:param output_file: Место, куда надо скачать файл
:return: | Below is the the instruction that describes the task:
### Input:
Выполняет указанный в конфигурации запрос и отдает файл на скачивание
:param configuration: Конфгурация запроса
:param output_file: Место, куда надо скачать файл
:return:
### Response:
def download_data(self, configuration, ou... |
def make_app():
"""Helper function that creates a plnt app."""
from plnt import Plnt
database_uri = os.environ.get("PLNT_DATABASE_URI")
app = Plnt(database_uri or "sqlite:////tmp/plnt.db")
app.bind_to_context()
return app | Helper function that creates a plnt app. | Below is the the instruction that describes the task:
### Input:
Helper function that creates a plnt app.
### Response:
def make_app():
"""Helper function that creates a plnt app."""
from plnt import Plnt
database_uri = os.environ.get("PLNT_DATABASE_URI")
app = Plnt(database_uri or "sqlite:////tmp... |
def with_env(self, **environment_variables):
"""
Return new Command object that will be run with additional
environment variables.
Specify environment variables as follows:
new_cmd = old_cmd.with_env(PYTHON_PATH=".", ENV_PORT="2022")
"""
new_env_vars = {
... | Return new Command object that will be run with additional
environment variables.
Specify environment variables as follows:
new_cmd = old_cmd.with_env(PYTHON_PATH=".", ENV_PORT="2022") | Below is the the instruction that describes the task:
### Input:
Return new Command object that will be run with additional
environment variables.
Specify environment variables as follows:
new_cmd = old_cmd.with_env(PYTHON_PATH=".", ENV_PORT="2022")
### Response:
def with_env(self, **... |
def post_fork_child(self, fingerprint, jvm_options, classpath, stdout, stderr):
"""Post-fork() child callback for ProcessManager.daemon_spawn()."""
java = SubprocessExecutor(self._distribution)
subproc = java.spawn(classpath=classpath,
main='com.martiansoftware.nailgun.NGServer',
... | Post-fork() child callback for ProcessManager.daemon_spawn(). | Below is the the instruction that describes the task:
### Input:
Post-fork() child callback for ProcessManager.daemon_spawn().
### Response:
def post_fork_child(self, fingerprint, jvm_options, classpath, stdout, stderr):
"""Post-fork() child callback for ProcessManager.daemon_spawn()."""
java = SubprocessE... |
def insert(self, key, item):
"""
Insert item into hash table with specified key and item.
If key is already present returns -1 and leaves existing item unchanged
Returns 0 on success.
"""
return lib.zhashx_insert(self._as_parameter_, key, item) | Insert item into hash table with specified key and item.
If key is already present returns -1 and leaves existing item unchanged
Returns 0 on success. | Below is the the instruction that describes the task:
### Input:
Insert item into hash table with specified key and item.
If key is already present returns -1 and leaves existing item unchanged
Returns 0 on success.
### Response:
def insert(self, key, item):
"""
Insert item into hash table with spe... |
def check_path(self, path):
"""
turns path into an absolute path and checks that it exists, then
returns it as a string.
"""
path = os.path.abspath(path)
if os.path.exists(path):
return path
else:
utils.die("input file does not exists:\n {... | turns path into an absolute path and checks that it exists, then
returns it as a string. | Below is the the instruction that describes the task:
### Input:
turns path into an absolute path and checks that it exists, then
returns it as a string.
### Response:
def check_path(self, path):
"""
turns path into an absolute path and checks that it exists, then
returns it as a st... |
def generate(self, more_content=None, all_members=False):
# type: (Any, str, bool, bool) -> None
"""Generate reST for the object given by *self.name*, and possibly for
its members.
If *more_content* is given, include that content.
If *all_members* is True, document all members.
... | Generate reST for the object given by *self.name*, and possibly for
its members.
If *more_content* is given, include that content.
If *all_members* is True, document all members. | Below is the the instruction that describes the task:
### Input:
Generate reST for the object given by *self.name*, and possibly for
its members.
If *more_content* is given, include that content.
If *all_members* is True, document all members.
### Response:
def generate(self, more_content=... |
def rm_docs(self):
"""Remove converted docs."""
for filename in self.created:
if os.path.exists(filename):
os.unlink(filename) | Remove converted docs. | Below is the the instruction that describes the task:
### Input:
Remove converted docs.
### Response:
def rm_docs(self):
"""Remove converted docs."""
for filename in self.created:
if os.path.exists(filename):
os.unlink(filename) |
def from_string(cls, cl_function, dependencies=()):
"""Parse the given CL function into a SimpleCLFunction object.
Args:
cl_function (str): the function we wish to turn into an object
dependencies (list or tuple of CLLibrary): The list of CL libraries this function depends on
... | Parse the given CL function into a SimpleCLFunction object.
Args:
cl_function (str): the function we wish to turn into an object
dependencies (list or tuple of CLLibrary): The list of CL libraries this function depends on
Returns:
SimpleCLFunction: the CL data type ... | Below is the the instruction that describes the task:
### Input:
Parse the given CL function into a SimpleCLFunction object.
Args:
cl_function (str): the function we wish to turn into an object
dependencies (list or tuple of CLLibrary): The list of CL libraries this function depends... |
def copy_result(self, selection):
"""Returns result
If selection consists of one cell only and result is a bitmap then
the bitmap is returned.
Otherwise the method returns string representations of the result
for the given selection in a tab separated string.
"""
... | Returns result
If selection consists of one cell only and result is a bitmap then
the bitmap is returned.
Otherwise the method returns string representations of the result
for the given selection in a tab separated string. | Below is the the instruction that describes the task:
### Input:
Returns result
If selection consists of one cell only and result is a bitmap then
the bitmap is returned.
Otherwise the method returns string representations of the result
for the given selection in a tab separated str... |
def _set_openflow_interface_cfg(self, v, load=False):
"""
Setter method for openflow_interface_cfg, mapped from YANG variable /interface/hundredgigabitethernet/openflow_interface_cfg (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_openflow_interface_cfg is co... | Setter method for openflow_interface_cfg, mapped from YANG variable /interface/hundredgigabitethernet/openflow_interface_cfg (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_openflow_interface_cfg is considered as a private
method. Backends looking to populate thi... | Below is the the instruction that describes the task:
### Input:
Setter method for openflow_interface_cfg, mapped from YANG variable /interface/hundredgigabitethernet/openflow_interface_cfg (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_openflow_interface_cfg is... |
def register_method(func, name=None, deprecated=False):
"""Register a method of calculating an average spectrogram.
Parameters
----------
func : `callable`
function to execute
name : `str`, optional
name of the method, defaults to ``func.__name__``
deprecated : `bool`, optiona... | Register a method of calculating an average spectrogram.
Parameters
----------
func : `callable`
function to execute
name : `str`, optional
name of the method, defaults to ``func.__name__``
deprecated : `bool`, optional
whether this method is deprecated (`True`) or not (`F... | Below is the the instruction that describes the task:
### Input:
Register a method of calculating an average spectrogram.
Parameters
----------
func : `callable`
function to execute
name : `str`, optional
name of the method, defaults to ``func.__name__``
deprecated : `bool`, o... |
def close(self):
"""Close the file. Can be called multiple times."""
if not self.closed:
# be sure to flush data to disk before closing the file
self.flush()
err = _snd.sf_close(self._file)
self._file = None
_error_check(err) | Close the file. Can be called multiple times. | Below is the the instruction that describes the task:
### Input:
Close the file. Can be called multiple times.
### Response:
def close(self):
"""Close the file. Can be called multiple times."""
if not self.closed:
# be sure to flush data to disk before closing the file
sel... |
def get_and_update_setting(self, name, default=None, user=True):
'''Look for a setting in the environment (first priority) and then
the settings file (second). If something is found, the settings
file is updated. The order of operations works as follows:
1. The user config file is used as a ca... | Look for a setting in the environment (first priority) and then
the settings file (second). If something is found, the settings
file is updated. The order of operations works as follows:
1. The user config file is used as a cache for the variable
2. the environment variable always takes pri... | Below is the the instruction that describes the task:
### Input:
Look for a setting in the environment (first priority) and then
the settings file (second). If something is found, the settings
file is updated. The order of operations works as follows:
1. The user config file is used as a cache... |
def compute_neighbors(
self,
n_neighbors: int = 30,
knn: bool = True,
n_pcs: Optional[int] = None,
use_rep: Optional[str] = None,
method: str = 'umap',
random_state: Optional[Union[RandomState, int]] = 0,
write_knn_indices: bool = False,
metric: st... | \
Compute distances and connectivities of neighbors.
Parameters
----------
n_neighbors
Use this number of nearest neighbors.
knn
Restrict result to `n_neighbors` nearest neighbors.
{n_pcs}
{use_rep}
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
\
Compute distances and connectivities of neighbors.
Parameters
----------
n_neighbors
Use this number of nearest neighbors.
knn
Restrict result to `n_neighbors` nearest neighbors.
... |
def plot_grouped_gos(self, fout_img=None, exclude_hdrs=None, **kws_usr):
"""One Plot containing all user GOs (yellow or green) and header GO IDs(green or purple)."""
# kws_plt -> go2color go2bordercolor
kws_plt, kws_dag = self._get_kws_plt(self.grprobj.usrgos, **kws_usr)
pltgosusr = self... | One Plot containing all user GOs (yellow or green) and header GO IDs(green or purple). | Below is the the instruction that describes the task:
### Input:
One Plot containing all user GOs (yellow or green) and header GO IDs(green or purple).
### Response:
def plot_grouped_gos(self, fout_img=None, exclude_hdrs=None, **kws_usr):
"""One Plot containing all user GOs (yellow or green) and header GO ... |
def gauss_hermite_nodes(orders, sigma, mu=None):
'''
Computes the weights and nodes for Gauss Hermite quadrature.
Parameters
----------
orders : int, list, array
The order of integration used in the quadrature routine
sigma : array-like
If one dimensional, the variance of the no... | Computes the weights and nodes for Gauss Hermite quadrature.
Parameters
----------
orders : int, list, array
The order of integration used in the quadrature routine
sigma : array-like
If one dimensional, the variance of the normal distribution being
approximated. If multidimensi... | Below is the the instruction that describes the task:
### Input:
Computes the weights and nodes for Gauss Hermite quadrature.
Parameters
----------
orders : int, list, array
The order of integration used in the quadrature routine
sigma : array-like
If one dimensional, the variance o... |
def _ReverseHostname(self, hostname):
"""Reverses the hostname and strips the leading dot.
The hostname entry is reversed:
moc.elgoog.www.
Should be:
www.google.com
Args:
hostname (str): reversed hostname.
Returns:
str: hostname without a leading dot.
"""
if not ho... | Reverses the hostname and strips the leading dot.
The hostname entry is reversed:
moc.elgoog.www.
Should be:
www.google.com
Args:
hostname (str): reversed hostname.
Returns:
str: hostname without a leading dot. | Below is the the instruction that describes the task:
### Input:
Reverses the hostname and strips the leading dot.
The hostname entry is reversed:
moc.elgoog.www.
Should be:
www.google.com
Args:
hostname (str): reversed hostname.
Returns:
str: hostname without a leading do... |
def spawn_container(addr, env_cls=Environment,
mgr_cls=EnvManager, set_seed=True, *args, **kwargs):
"""Spawn a new environment in a given address as a coroutine.
Arguments and keyword arguments are passed down to the created environment
at initialization time.
If `setproctitle <htt... | Spawn a new environment in a given address as a coroutine.
Arguments and keyword arguments are passed down to the created environment
at initialization time.
If `setproctitle <https://pypi.python.org/pypi/setproctitle>`_ is
installed, this function renames the title of the process to start with
'c... | Below is the the instruction that describes the task:
### Input:
Spawn a new environment in a given address as a coroutine.
Arguments and keyword arguments are passed down to the created environment
at initialization time.
If `setproctitle <https://pypi.python.org/pypi/setproctitle>`_ is
installed... |
def log(self, timer_name, node):
''' logs a event in the timer '''
timestamp = time.time()
if hasattr(self, timer_name):
getattr(self, timer_name).append({
"node":node,
"time":timestamp})
else:
setattr(self, timer_name, [{"node":nod... | logs a event in the timer | Below is the the instruction that describes the task:
### Input:
logs a event in the timer
### Response:
def log(self, timer_name, node):
''' logs a event in the timer '''
timestamp = time.time()
if hasattr(self, timer_name):
getattr(self, timer_name).append({
"n... |
def validate_state_locations(self):
"""
Names of all state locations must be unique.
"""
names = map(lambda loc: loc["name"], self.locations)
assert len(names) == len(set(names)), "Names of state locations must be unique" | Names of all state locations must be unique. | Below is the the instruction that describes the task:
### Input:
Names of all state locations must be unique.
### Response:
def validate_state_locations(self):
"""
Names of all state locations must be unique.
"""
names = map(lambda loc: loc["name"], self.locations)
assert len(names) == len(set(... |
def lineReceived(self, line):
"""
Called when a line is received.
We expect a length in bytes or an empty line for keep-alive. If
we got a length, switch to raw mode to receive that amount of bytes.
"""
if line and line.isdigit():
self._expectedLength = int(l... | Called when a line is received.
We expect a length in bytes or an empty line for keep-alive. If
we got a length, switch to raw mode to receive that amount of bytes. | Below is the the instruction that describes the task:
### Input:
Called when a line is received.
We expect a length in bytes or an empty line for keep-alive. If
we got a length, switch to raw mode to receive that amount of bytes.
### Response:
def lineReceived(self, line):
"""
Call... |
async def send(self, parameters: RTCRtpSendParameters):
"""
Attempt to set the parameters controlling the sending of media.
:param: parameters: The :class:`RTCRtpParameters` for the sender.
"""
if not self.__started:
self.__cname = parameters.rtcp.cname
s... | Attempt to set the parameters controlling the sending of media.
:param: parameters: The :class:`RTCRtpParameters` for the sender. | Below is the the instruction that describes the task:
### Input:
Attempt to set the parameters controlling the sending of media.
:param: parameters: The :class:`RTCRtpParameters` for the sender.
### Response:
async def send(self, parameters: RTCRtpSendParameters):
"""
Attempt to set the pa... |
def sum_in_date(x='date', y='net_sales', filter_dict=None, model='WikiItem', app=DEFAULT_APP, sort=True, limit=100000):
"""
Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts.
FIXME: Tests need models with a date fiel... | Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts.
FIXME: Tests need models with a date field:
Examples:
>> x, y = sum_in_date(y='net_sales', filter_dict={'model__startswith': 'LC60'}, model='Permission', limit=5, ... | Below is the the instruction that describes the task:
### Input:
Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts.
FIXME: Tests need models with a date field:
Examples:
>> x, y = sum_in_date(y='net_sales', fil... |
def view_dupl_sources(token, dstore):
"""
Show the sources with the same ID and the truly duplicated sources
"""
fields = ['source_id', 'code', 'gidx1', 'gidx2', 'num_ruptures']
dic = group_array(dstore['source_info'].value[fields], 'source_id')
sameid = []
dupl = []
for source_id, group... | Show the sources with the same ID and the truly duplicated sources | Below is the the instruction that describes the task:
### Input:
Show the sources with the same ID and the truly duplicated sources
### Response:
def view_dupl_sources(token, dstore):
"""
Show the sources with the same ID and the truly duplicated sources
"""
fields = ['source_id', 'code', 'gidx1', ... |
def _defaults(self, keys=None):
"""create an empty record"""
d = {}
keys = self._keys if keys is None else keys
for key in keys:
d[key] = None
return d | create an empty record | Below is the the instruction that describes the task:
### Input:
create an empty record
### Response:
def _defaults(self, keys=None):
"""create an empty record"""
d = {}
keys = self._keys if keys is None else keys
for key in keys:
d[key] = None
return d |
def config_maker(project_name, path):
"""Creates a config file based on the project name"""
with open(skeleton_path("config.py"), "r") as config_source:
config_content = config_source.read()
config_content = config_content.replace("__PROJECT_NAME__", project_name)
with open(path, "w") as conf... | Creates a config file based on the project name | Below is the the instruction that describes the task:
### Input:
Creates a config file based on the project name
### Response:
def config_maker(project_name, path):
"""Creates a config file based on the project name"""
with open(skeleton_path("config.py"), "r") as config_source:
config_content = c... |
def tail_of_file(filename, n, ansi2html=False):
"""Reads a n lines from f with an offset of offset lines. """
avg_line_length = 74
to_read = n
with open(filename) as f:
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
... | Reads a n lines from f with an offset of offset lines. | Below is the the instruction that describes the task:
### Input:
Reads a n lines from f with an offset of offset lines.
### Response:
def tail_of_file(filename, n, ansi2html=False):
"""Reads a n lines from f with an offset of offset lines. """
avg_line_length = 74
to_read = n
with open(filename) a... |
def zone_absent(name, resource_group, connection_auth=None):
'''
.. versionadded:: Fluorine
Ensure a DNS zone does not exist in the resource group.
:param name:
Name of the DNS zone.
:param resource_group:
The resource group assigned to the DNS zone.
:param connection_auth:
... | .. versionadded:: Fluorine
Ensure a DNS zone does not exist in the resource group.
:param name:
Name of the DNS zone.
:param resource_group:
The resource group assigned to the DNS zone.
:param connection_auth:
A dict with subscription and authentication parameters to be used ... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: Fluorine
Ensure a DNS zone does not exist in the resource group.
:param name:
Name of the DNS zone.
:param resource_group:
The resource group assigned to the DNS zone.
:param connection_auth:
... |
def _add_notification_config_to_xml(node, element_name, configs):
"""
Internal function that builds the XML sub-structure for a given
kind of notification configuration.
"""
for config in configs:
config_node = s3_xml.SubElement(node, element_name)
if 'Id' in config:
id... | Internal function that builds the XML sub-structure for a given
kind of notification configuration. | Below is the the instruction that describes the task:
### Input:
Internal function that builds the XML sub-structure for a given
kind of notification configuration.
### Response:
def _add_notification_config_to_xml(node, element_name, configs):
"""
Internal function that builds the XML sub-structure fo... |
def giant_text_sqltype(dialect: Dialect) -> str:
"""
Returns the SQL column type used to make very large text columns for a
given dialect.
Args:
dialect: a SQLAlchemy :class:`Dialect`
Returns:
the SQL data type of "giant text", typically 'LONGTEXT' for MySQL
and 'NVARCHAR(MA... | Returns the SQL column type used to make very large text columns for a
given dialect.
Args:
dialect: a SQLAlchemy :class:`Dialect`
Returns:
the SQL data type of "giant text", typically 'LONGTEXT' for MySQL
and 'NVARCHAR(MAX)' for SQL Server. | Below is the the instruction that describes the task:
### Input:
Returns the SQL column type used to make very large text columns for a
given dialect.
Args:
dialect: a SQLAlchemy :class:`Dialect`
Returns:
the SQL data type of "giant text", typically 'LONGTEXT' for MySQL
and 'NVA... |
def window(self, window_name):
"""
Switches focus to the specified window.
:Args:
- window_name: The name or window handle of the window to switch to.
:Usage:
::
driver.switch_to.window('main')
"""
if self._driver.w3c:
s... | Switches focus to the specified window.
:Args:
- window_name: The name or window handle of the window to switch to.
:Usage:
::
driver.switch_to.window('main') | Below is the the instruction that describes the task:
### Input:
Switches focus to the specified window.
:Args:
- window_name: The name or window handle of the window to switch to.
:Usage:
::
driver.switch_to.window('main')
### Response:
def window(self, wind... |
def _FetchMostRecentGraphSeriesFromTheLegacyDB(
label,
report_type,
token = None
):
"""Fetches the latest graph-series for a client label from the legacy DB.
Args:
label: Client label to fetch data for.
report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for.
token: ACL token ... | Fetches the latest graph-series for a client label from the legacy DB.
Args:
label: Client label to fetch data for.
report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for.
token: ACL token to use for reading from the DB.
Raises:
AFF4AttributeTypeError: If an unexpected report-data t... | Below is the the instruction that describes the task:
### Input:
Fetches the latest graph-series for a client label from the legacy DB.
Args:
label: Client label to fetch data for.
report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for.
token: ACL token to use for reading from the DB.
... |
def suppress_output(reverse=False):
"""
Suppress output
"""
if reverse:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
else:
sys.stdout = os.devnull
sys.stderr = os.devnull | Suppress output | Below is the the instruction that describes the task:
### Input:
Suppress output
### Response:
def suppress_output(reverse=False):
"""
Suppress output
"""
if reverse:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
else:
sys.stdout = os.devnull
sys.stderr... |
def install_python(name, version=None, install_args=None, override_args=False):
'''
Instructs Chocolatey to install a package via Python's easy_install.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defa... | Instructs Chocolatey to install a package via Python's easy_install.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defaults to latest version
available.
install_args
A list of install argume... | Below is the the instruction that describes the task:
### Input:
Instructs Chocolatey to install a package via Python's easy_install.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defaults to latest version
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.