code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def set_pubkey(self, pkey):
"""
Set the public key of the certificate
:param pkey: The public key
:return: ``None``
"""
set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
_openssl_assert(set_result == 1) | Set the public key of the certificate
:param pkey: The public key
:return: ``None`` | Below is the the instruction that describes the task:
### Input:
Set the public key of the certificate
:param pkey: The public key
:return: ``None``
### Response:
def set_pubkey(self, pkey):
"""
Set the public key of the certificate
:param pkey: The public key
:ret... |
def write(self):
"""Write the s2 page to the corresponding source file.
It always writes the (serialized) config first, and then the
content (normally markdown). The destination file is in the
source_dir of the site.
"""
if not os.path.isdir(self._dirs['source_dir']):
... | Write the s2 page to the corresponding source file.
It always writes the (serialized) config first, and then the
content (normally markdown). The destination file is in the
source_dir of the site. | Below is the the instruction that describes the task:
### Input:
Write the s2 page to the corresponding source file.
It always writes the (serialized) config first, and then the
content (normally markdown). The destination file is in the
source_dir of the site.
### Response:
def write(self... |
def _get_grouper(self, obj, validate=True):
"""
Parameters
----------
obj : the subject object
validate : boolean, default True
if True, validate the grouper
Returns
-------
a tuple of binner, grouper, obj (possibly sorted)
"""
... | Parameters
----------
obj : the subject object
validate : boolean, default True
if True, validate the grouper
Returns
-------
a tuple of binner, grouper, obj (possibly sorted) | Below is the the instruction that describes the task:
### Input:
Parameters
----------
obj : the subject object
validate : boolean, default True
if True, validate the grouper
Returns
-------
a tuple of binner, grouper, obj (possibly sorted)
### Response: ... |
def subdict(name, *keys, **kw):
"""
Subdict key.
Takes a `name`, any number of keys as args and keyword argument `trafaret`.
Use it like:
def check_passwords_equal(data):
if data['password'] != data['password_confirm']:
return t.DataError('Passwords are not equal')
... | Subdict key.
Takes a `name`, any number of keys as args and keyword argument `trafaret`.
Use it like:
def check_passwords_equal(data):
if data['password'] != data['password_confirm']:
return t.DataError('Passwords are not equal')
return data['password']
... | Below is the the instruction that describes the task:
### Input:
Subdict key.
Takes a `name`, any number of keys as args and keyword argument `trafaret`.
Use it like:
def check_passwords_equal(data):
if data['password'] != data['password_confirm']:
return t.DataError('P... |
def select_layout(self, layout_type):
"""
Select one of the predefined layouts.
"""
assert layout_type in LayoutTypes._ALL
# When there is only one pane, always choose EVEN_HORIZONTAL,
# Otherwise, we create VSplit/HSplit instances with an empty list of
# childre... | Select one of the predefined layouts. | Below is the the instruction that describes the task:
### Input:
Select one of the predefined layouts.
### Response:
def select_layout(self, layout_type):
"""
Select one of the predefined layouts.
"""
assert layout_type in LayoutTypes._ALL
# When there is only one pane, alw... |
def get_cookie_header(jar, request):
"""
Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtype: str
"""
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie') | Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtype: str | Below is the the instruction that describes the task:
### Input:
Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtype: str
### Response:
def get_cookie_header(jar, request):
"""
Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtyp... |
def set(
self,
key,
value,
loader_identifier=None,
tomlfy=False,
dotted_lookup=True,
is_secret=False,
):
"""Set a value storing references for the loader
:param key: The key to store
:param value: The value to store
:param load... | Set a value storing references for the loader
:param key: The key to store
:param value: The value to store
:param loader_identifier: Optional loader name e.g: toml, yaml etc.
:param tomlfy: Bool define if value is parsed by toml (defaults False)
:param is_secret: Bool define if... | Below is the the instruction that describes the task:
### Input:
Set a value storing references for the loader
:param key: The key to store
:param value: The value to store
:param loader_identifier: Optional loader name e.g: toml, yaml etc.
:param tomlfy: Bool define if value is par... |
def pretty_repr(instance):
"""
A function assignable to the ``__repr__`` dunder method, so that
the ``prettyprinter`` definition for the type is used to provide
repr output. Usage:
.. code:: python
from prettyprinter import pretty_repr
class MyClass:
__repr__ = pretty_... | A function assignable to the ``__repr__`` dunder method, so that
the ``prettyprinter`` definition for the type is used to provide
repr output. Usage:
.. code:: python
from prettyprinter import pretty_repr
class MyClass:
__repr__ = pretty_repr | Below is the the instruction that describes the task:
### Input:
A function assignable to the ``__repr__`` dunder method, so that
the ``prettyprinter`` definition for the type is used to provide
repr output. Usage:
.. code:: python
from prettyprinter import pretty_repr
class MyClass:
... |
def delete_group(self, group_id):
"""
Removes a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
"""
response = self._perform_request(
url='/um/groups/%s' % group_id,
method='DELETE')
return response | Removes a group.
:param group_id: The unique ID of the group.
:type group_id: ``str`` | Below is the the instruction that describes the task:
### Input:
Removes a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
### Response:
def delete_group(self, group_id):
"""
Removes a group.
:param group_id: The unique ID of the... |
def _logtrick_gen(bounds):
"""Generate warping functions and new bounds for the log trick."""
# Test which parameters we can apply the log trick too
ispos = np.array([isinstance(b, bt.Positive) for b in bounds], dtype=bool)
nispos = ~ispos
# Functions that implement the log trick
def logx(x):
... | Generate warping functions and new bounds for the log trick. | Below is the the instruction that describes the task:
### Input:
Generate warping functions and new bounds for the log trick.
### Response:
def _logtrick_gen(bounds):
"""Generate warping functions and new bounds for the log trick."""
# Test which parameters we can apply the log trick too
ispos = np.arr... |
def plot_nb(self,xdata,ydata=[],logScale=False):
'''Graphs a line plot and embeds it in a Jupyter notebook. See 'help(figure.plot)' for more info.'''
self.plot(xdata,ydata,logScale) | Graphs a line plot and embeds it in a Jupyter notebook. See 'help(figure.plot)' for more info. | Below is the the instruction that describes the task:
### Input:
Graphs a line plot and embeds it in a Jupyter notebook. See 'help(figure.plot)' for more info.
### Response:
def plot_nb(self,xdata,ydata=[],logScale=False):
'''Graphs a line plot and embeds it in a Jupyter notebook. See 'help(figure.plot)' f... |
def _list_queues(self, prefix=None, marker=None, max_results=None,
include=None, timeout=None, _context=None):
'''
Returns a list of queues under the specified account. Makes a single list
request to the service. Used internally by the list_queues method.
:param st... | Returns a list of queues under the specified account. Makes a single list
request to the service. Used internally by the list_queues method.
:param str prefix:
Filters the results to return only queues with names that begin
with the specified prefix.
:param str marker:
... | Below is the the instruction that describes the task:
### Input:
Returns a list of queues under the specified account. Makes a single list
request to the service. Used internally by the list_queues method.
:param str prefix:
Filters the results to return only queues with names that beg... |
def legend_aesthetics(self, layer, plot):
"""
Return the aesthetics that contribute to the legend
Parameters
----------
layer : Layer
Layer whose legend is to be drawn
plot : ggplot
Plot object
Returns
-------
matched : li... | Return the aesthetics that contribute to the legend
Parameters
----------
layer : Layer
Layer whose legend is to be drawn
plot : ggplot
Plot object
Returns
-------
matched : list
List of the names of the aethetics that contrib... | Below is the the instruction that describes the task:
### Input:
Return the aesthetics that contribute to the legend
Parameters
----------
layer : Layer
Layer whose legend is to be drawn
plot : ggplot
Plot object
Returns
-------
match... |
def run_training(sub_id: int, run_seed: int, run_options, process_queue):
"""
Launches training session.
:param process_queue: Queue used to send signal back to main.
:param sub_id: Unique id for training session.
:param run_seed: Random seed used for training.
:param run_options: Command line a... | Launches training session.
:param process_queue: Queue used to send signal back to main.
:param sub_id: Unique id for training session.
:param run_seed: Random seed used for training.
:param run_options: Command line arguments for training. | Below is the the instruction that describes the task:
### Input:
Launches training session.
:param process_queue: Queue used to send signal back to main.
:param sub_id: Unique id for training session.
:param run_seed: Random seed used for training.
:param run_options: Command line arguments for trai... |
def boxplot(self, **vargs):
"""Plots a boxplot for the table.
Every column must be numerical.
Kwargs:
vargs: Additional arguments that get passed into `plt.boxplot`.
See http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplot
for addition... | Plots a boxplot for the table.
Every column must be numerical.
Kwargs:
vargs: Additional arguments that get passed into `plt.boxplot`.
See http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplot
for additional arguments that can be passed into va... | Below is the the instruction that describes the task:
### Input:
Plots a boxplot for the table.
Every column must be numerical.
Kwargs:
vargs: Additional arguments that get passed into `plt.boxplot`.
See http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplo... |
def get_source(source):
"""Return a pip-installable source
If the source is a url to a package's tar file,
this will download the source and extract it to a temporary directory.
If the source is neither a url nor a local path, and is not provided
as PACKAGE_NAME==PACKAGE_VERSION, the provided sour... | Return a pip-installable source
If the source is a url to a package's tar file,
this will download the source and extract it to a temporary directory.
If the source is neither a url nor a local path, and is not provided
as PACKAGE_NAME==PACKAGE_VERSION, the provided source string
will be regarded ... | Below is the the instruction that describes the task:
### Input:
Return a pip-installable source
If the source is a url to a package's tar file,
this will download the source and extract it to a temporary directory.
If the source is neither a url nor a local path, and is not provided
as PACKAGE_NA... |
def variance(numbers, type='population'):
"""
Calculates the population or sample variance of a list of numbers.
A large number means the results are all over the place, while a
small number means the results are comparatively close to the average.
Args:
numbers: a list of integers or floa... | Calculates the population or sample variance of a list of numbers.
A large number means the results are all over the place, while a
small number means the results are comparatively close to the average.
Args:
numbers: a list of integers or floating point numbers to compare.
type: string, ... | Below is the the instruction that describes the task:
### Input:
Calculates the population or sample variance of a list of numbers.
A large number means the results are all over the place, while a
small number means the results are comparatively close to the average.
Args:
numbers: a list of i... |
def EQ100(T, A=0, B=0, C=0, D=0, E=0, F=0, G=0, order=0):
r'''DIPPR Equation # 100. Used in calculating the molar heat capacities
of liquids and solids, liquid thermal conductivity, and solid density.
All parameters default to zero. As this is a straightforward polynomial,
no restrictions on parameters ... | r'''DIPPR Equation # 100. Used in calculating the molar heat capacities
of liquids and solids, liquid thermal conductivity, and solid density.
All parameters default to zero. As this is a straightforward polynomial,
no restrictions on parameters apply. Note that high-order polynomials like
this may need... | Below is the the instruction that describes the task:
### Input:
r'''DIPPR Equation # 100. Used in calculating the molar heat capacities
of liquids and solids, liquid thermal conductivity, and solid density.
All parameters default to zero. As this is a straightforward polynomial,
no restrictions on para... |
def package_releases(self, package_name):
"""Query PYPI via XMLRPC interface for a pkg's available versions"""
if self.debug:
self.logger.debug("DEBUG: querying PyPI for versions of " \
+ package_name)
return self.xmlrpc.package_releases(package_name) | Query PYPI via XMLRPC interface for a pkg's available versions | Below is the the instruction that describes the task:
### Input:
Query PYPI via XMLRPC interface for a pkg's available versions
### Response:
def package_releases(self, package_name):
"""Query PYPI via XMLRPC interface for a pkg's available versions"""
if self.debug:
self.logger.debug("... |
def _run_suite(self, test_suite):
""" run tests in test_suite
Args:
test_suite: unittest.TestSuite()
Returns:
list: tests_results
"""
tests_results = []
for testcase in test_suite:
testcase_name = testcase.config.get("name")
... | run tests in test_suite
Args:
test_suite: unittest.TestSuite()
Returns:
list: tests_results | Below is the the instruction that describes the task:
### Input:
run tests in test_suite
Args:
test_suite: unittest.TestSuite()
Returns:
list: tests_results
### Response:
def _run_suite(self, test_suite):
""" run tests in test_suite
Args:
test_... |
def send_message_event(self, room_id, event_type, content, txn_id=None,
timestamp=None):
"""Perform PUT /rooms/$room_id/send/$event_type
Args:
room_id (str): The room ID to send the message event in.
event_type (str): The event type to send.
... | Perform PUT /rooms/$room_id/send/$event_type
Args:
room_id (str): The room ID to send the message event in.
event_type (str): The event type to send.
content (dict): The JSON content to send.
txn_id (int): Optional. The transaction ID to use.
timestam... | Below is the the instruction that describes the task:
### Input:
Perform PUT /rooms/$room_id/send/$event_type
Args:
room_id (str): The room ID to send the message event in.
event_type (str): The event type to send.
content (dict): The JSON content to send.
tx... |
def __read_single_fasta_query_lines(f):
'''
Read and return sequence of lines (including newlines) that
represent a single FASTA query record. The provided file is
expected to be blocking.
Returns None if there are no more query sequences in the file.
'''
def readline():
l = f.read... | Read and return sequence of lines (including newlines) that
represent a single FASTA query record. The provided file is
expected to be blocking.
Returns None if there are no more query sequences in the file. | Below is the the instruction that describes the task:
### Input:
Read and return sequence of lines (including newlines) that
represent a single FASTA query record. The provided file is
expected to be blocking.
Returns None if there are no more query sequences in the file.
### Response:
def __read_sing... |
def run_process(self, analysis, action_name, message='__nomessagetoken__'):
"""Executes an process in the analysis with the given message.
It also handles the start and stop signals in case an process_id
is given.
This method is similar to the method in databench.Analysis.
"""
... | Executes an process in the analysis with the given message.
It also handles the start and stop signals in case an process_id
is given.
This method is similar to the method in databench.Analysis. | Below is the the instruction that describes the task:
### Input:
Executes an process in the analysis with the given message.
It also handles the start and stop signals in case an process_id
is given.
This method is similar to the method in databench.Analysis.
### Response:
def run_process... |
def create_finder(project, name, pyname, only_calls=False, imports=True,
unsure=None, docs=False, instance=None, in_hierarchy=False,
keywords=True):
"""A factory for `Finder`
Based on the arguments it creates a list of filters. `instance`
argument is needed only when yo... | A factory for `Finder`
Based on the arguments it creates a list of filters. `instance`
argument is needed only when you want implicit interfaces to be
considered. | Below is the the instruction that describes the task:
### Input:
A factory for `Finder`
Based on the arguments it creates a list of filters. `instance`
argument is needed only when you want implicit interfaces to be
considered.
### Response:
def create_finder(project, name, pyname, only_calls=False, ... |
def json_encode(obj, serialize):
""" Handle encoding complex types. """
if hasattr(obj, 'to_dict'):
return obj.to_dict(serialize=serialize)
elif isinstance(obj, datetime):
return obj.date().isoformat()
elif isinstance(obj, date):
return obj.isoformat()
elif isinstance(obj, Pr... | Handle encoding complex types. | Below is the the instruction that describes the task:
### Input:
Handle encoding complex types.
### Response:
def json_encode(obj, serialize):
""" Handle encoding complex types. """
if hasattr(obj, 'to_dict'):
return obj.to_dict(serialize=serialize)
elif isinstance(obj, datetime):
retur... |
def show(self, imgs, ax=None):
""" Visualize the persistence image
"""
ax = ax or plt.gca()
if type(imgs) is not list:
imgs = [imgs]
for i, img in enumerate(imgs):
ax.imshow(img, cmap=plt.get_cmap("plasma"))
ax.axis("off") | Visualize the persistence image | Below is the the instruction that describes the task:
### Input:
Visualize the persistence image
### Response:
def show(self, imgs, ax=None):
""" Visualize the persistence image
"""
ax = ax or plt.gca()
if type(imgs) is not list:
imgs = [imgs]
for i, img in e... |
def load(self, filepath):
"""Load configuration from existing file.
:param str filepath: Path to existing config file.
:raises: ValueError if supplied config file is invalid.
"""
try:
self._config.read(filepath)
self.long_running_operation_timeout = self.... | Load configuration from existing file.
:param str filepath: Path to existing config file.
:raises: ValueError if supplied config file is invalid. | Below is the the instruction that describes the task:
### Input:
Load configuration from existing file.
:param str filepath: Path to existing config file.
:raises: ValueError if supplied config file is invalid.
### Response:
def load(self, filepath):
"""Load configuration from existing fil... |
def classify(self, encoding, num=1):
"""
Classify with basic one-hot local incoding
"""
probDist = numpy.exp(encoding) / numpy.sum(numpy.exp(encoding))
sortIdx = numpy.argsort(probDist)
return sortIdx[-num:].tolist() | Classify with basic one-hot local incoding | Below is the the instruction that describes the task:
### Input:
Classify with basic one-hot local incoding
### Response:
def classify(self, encoding, num=1):
"""
Classify with basic one-hot local incoding
"""
probDist = numpy.exp(encoding) / numpy.sum(numpy.exp(encoding))
sortIdx = numpy.argso... |
def getReadAlignmentId(self, gaAlignment):
"""
Returns a string ID suitable for use in the specified GA
ReadAlignment object in this ReadGroupSet.
"""
compoundId = datamodel.ReadAlignmentCompoundId(
self.getCompoundId(), gaAlignment.fragment_name)
return str(c... | Returns a string ID suitable for use in the specified GA
ReadAlignment object in this ReadGroupSet. | Below is the the instruction that describes the task:
### Input:
Returns a string ID suitable for use in the specified GA
ReadAlignment object in this ReadGroupSet.
### Response:
def getReadAlignmentId(self, gaAlignment):
"""
Returns a string ID suitable for use in the specified GA
... |
def delete_files(self, dataset_key, names):
"""Delete dataset file(s)
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param names: The list of names for files to be deleted
:type names: list of str
:raises RestApiException: If a se... | Delete dataset file(s)
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param names: The list of names for files to be deleted
:type names: list of str
:raises RestApiException: If a server error occurs
Examples
--------
... | Below is the the instruction that describes the task:
### Input:
Delete dataset file(s)
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param names: The list of names for files to be deleted
:type names: list of str
:raises RestApiExce... |
def stop(self, timeout=600000):
"""Gracefully stop the Worker and all of its consumers and
workers.
Parameters:
timeout(int): The number of milliseconds to wait for
everything to shut down.
"""
self.broker.emit_before("worker_shutdown", self)
self.l... | Gracefully stop the Worker and all of its consumers and
workers.
Parameters:
timeout(int): The number of milliseconds to wait for
everything to shut down. | Below is the the instruction that describes the task:
### Input:
Gracefully stop the Worker and all of its consumers and
workers.
Parameters:
timeout(int): The number of milliseconds to wait for
everything to shut down.
### Response:
def stop(self, timeout=600000):
""... |
def install(self, force=False, overrides={}):
"""
Install the wheel into site-packages.
"""
# Utility to get the target directory for a particular key
def get_path(key):
return overrides.get(key) or self.install_paths[key]
# The base target location is eithe... | Install the wheel into site-packages. | Below is the the instruction that describes the task:
### Input:
Install the wheel into site-packages.
### Response:
def install(self, force=False, overrides={}):
"""
Install the wheel into site-packages.
"""
# Utility to get the target directory for a particular key
def ge... |
def run(self):
""" Computes cleared offers and bids.
"""
# Start the clock.
t0 = time.time()
# Manage reactive power offers/bids.
haveQ = self._isReactiveMarket()
# Withhold offers/bids outwith optional price limits.
self._withholdOffbids()
# Co... | Computes cleared offers and bids. | Below is the the instruction that describes the task:
### Input:
Computes cleared offers and bids.
### Response:
def run(self):
""" Computes cleared offers and bids.
"""
# Start the clock.
t0 = time.time()
# Manage reactive power offers/bids.
haveQ = self._isReactiv... |
def decode(hashcode, delta=False):
"""
decode a hashcode and get center coordinate, and distance between center and outer border
"""
lat, lon, lat_length, lon_length = _decode_c2i(hashcode)
if hasattr(float, "fromhex"):
latitude_delta = 90.0/(1 << lat_length)
longitude_delta = 180.... | decode a hashcode and get center coordinate, and distance between center and outer border | Below is the the instruction that describes the task:
### Input:
decode a hashcode and get center coordinate, and distance between center and outer border
### Response:
def decode(hashcode, delta=False):
"""
decode a hashcode and get center coordinate, and distance between center and outer border
"""
... |
def lookup_folder(event, filesystem):
"""Lookup the parent folder in the filesystem content."""
for dirent in filesystem[event.parent_inode]:
if dirent.type == 'd' and dirent.allocated:
return ntpath.join(dirent.path, event.name) | Lookup the parent folder in the filesystem content. | Below is the the instruction that describes the task:
### Input:
Lookup the parent folder in the filesystem content.
### Response:
def lookup_folder(event, filesystem):
"""Lookup the parent folder in the filesystem content."""
for dirent in filesystem[event.parent_inode]:
if dirent.type == 'd' and ... |
def translate_doc(self, d, field_mapping=None, map_identifiers=None, **kwargs):
"""
Translate a solr document (i.e. a single result row)
"""
if field_mapping is not None:
self.map_doc(d, field_mapping)
subject = self.translate_obj(d, M.SUBJECT)
obj = self.tran... | Translate a solr document (i.e. a single result row) | Below is the the instruction that describes the task:
### Input:
Translate a solr document (i.e. a single result row)
### Response:
def translate_doc(self, d, field_mapping=None, map_identifiers=None, **kwargs):
"""
Translate a solr document (i.e. a single result row)
"""
if field_m... |
def execute_node(self, node, verbatim_exe = False):
""" Execute this node immediately on the local machine
"""
node.executed = True
# Check that the PFN is for a file or path
if node.executable.needs_fetching:
try:
# The pfn may have been marked local... | Execute this node immediately on the local machine | Below is the the instruction that describes the task:
### Input:
Execute this node immediately on the local machine
### Response:
def execute_node(self, node, verbatim_exe = False):
""" Execute this node immediately on the local machine
"""
node.executed = True
# Check that the PFN... |
def check_input(self, token):
"""
Performs checks on the input token. Raises an exception if unsupported.
:param token: the token to check
:type token: Token
"""
if token is None:
raise Exception(self.full_name + ": No token provided!")
if isinstance(... | Performs checks on the input token. Raises an exception if unsupported.
:param token: the token to check
:type token: Token | Below is the the instruction that describes the task:
### Input:
Performs checks on the input token. Raises an exception if unsupported.
:param token: the token to check
:type token: Token
### Response:
def check_input(self, token):
"""
Performs checks on the input token. Raises an... |
def stream_url(url):
"""
Read response of specified url into memory and return to caller. No persistence to disk.
:return: response content if accessing the URL succeeds, False otherwise
"""
try:
response = urllib2.urlopen(url)
response_content = response.read()
return response_content
except (u... | Read response of specified url into memory and return to caller. No persistence to disk.
:return: response content if accessing the URL succeeds, False otherwise | Below is the the instruction that describes the task:
### Input:
Read response of specified url into memory and return to caller. No persistence to disk.
:return: response content if accessing the URL succeeds, False otherwise
### Response:
def stream_url(url):
"""
Read response of specified url into memory ... |
def write(self, gpio, level):
"""
Sets the gpio level.
gpio:= 0-53.
level:= 0, 1.
If PWM or servo pulses are active on the gpio they are
switched off.
...
pi.set_mode(17, pigpio.OUTPUT)
pi.write(17,0)
print(pi.read(17))
0
... | Sets the gpio level.
gpio:= 0-53.
level:= 0, 1.
If PWM or servo pulses are active on the gpio they are
switched off.
...
pi.set_mode(17, pigpio.OUTPUT)
pi.write(17,0)
print(pi.read(17))
0
pi.write(17,1)
print(pi.read(17))
... | Below is the the instruction that describes the task:
### Input:
Sets the gpio level.
gpio:= 0-53.
level:= 0, 1.
If PWM or servo pulses are active on the gpio they are
switched off.
...
pi.set_mode(17, pigpio.OUTPUT)
pi.write(17,0)
print(pi.read(17... |
def update(self, pbar, width):
'Updates the progress bar and its subcomponents'
left, marker, right = (format_updatable(i, pbar) for i in
(self.left, self.marker, self.right))
width -= len(left) + len(right)
if pbar.finished: return '%s%s%s' % (left, wid... | Updates the progress bar and its subcomponents | Below is the the instruction that describes the task:
### Input:
Updates the progress bar and its subcomponents
### Response:
def update(self, pbar, width):
'Updates the progress bar and its subcomponents'
left, marker, right = (format_updatable(i, pbar) for i in
(se... |
def get_graphviz(self, engine="automatic", graph_attr=None, node_attr=None, edge_attr=None):
"""
Generate flow graph in the DOT language.
Args:
engine: Layout command used. ['dot', 'neato', 'twopi', 'circo', 'fdp', 'sfdp', 'patchwork', 'osage']
graph_attr: Mapping of (at... | Generate flow graph in the DOT language.
Args:
engine: Layout command used. ['dot', 'neato', 'twopi', 'circo', 'fdp', 'sfdp', 'patchwork', 'osage']
graph_attr: Mapping of (attribute, value) pairs for the graph.
node_attr: Mapping of (attribute, value) pairs set for all nodes... | Below is the the instruction that describes the task:
### Input:
Generate flow graph in the DOT language.
Args:
engine: Layout command used. ['dot', 'neato', 'twopi', 'circo', 'fdp', 'sfdp', 'patchwork', 'osage']
graph_attr: Mapping of (attribute, value) pairs for the graph.
... |
def refresh(self):
""" Update this ItemList by re-downloading it from the server
:rtype: ItemList
:returns: this ItemList, after the refresh
:raises: APIError if the API request is not successful
"""
refreshed = self.client.get_item_list(self.url())
self.item_... | Update this ItemList by re-downloading it from the server
:rtype: ItemList
:returns: this ItemList, after the refresh
:raises: APIError if the API request is not successful | Below is the the instruction that describes the task:
### Input:
Update this ItemList by re-downloading it from the server
:rtype: ItemList
:returns: this ItemList, after the refresh
:raises: APIError if the API request is not successful
### Response:
def refresh(self):
""" Update... |
def chmod(path, mode, recursive=True):
""" alternative to os.
"""
if recursive:
cmd = 'chmod -R %s %s' % (mode, path)
else:
cmd = 'chmod %s %s' % (mode, path)
return sh(cmd) | alternative to os. | Below is the the instruction that describes the task:
### Input:
alternative to os.
### Response:
def chmod(path, mode, recursive=True):
""" alternative to os.
"""
if recursive:
cmd = 'chmod -R %s %s' % (mode, path)
else:
cmd = 'chmod %s %s' % (mode, path)
return sh(cmd) |
def extract_bundle(self, resource, timeout=-1):
"""
Extracts the existing bundle on the appliance and creates all the artifacts.
Args:
resource (dict): Artifact Bundle to extract.
timeout:
Timeout in seconds. Waits for task completion by default. The time... | Extracts the existing bundle on the appliance and creates all the artifacts.
Args:
resource (dict): Artifact Bundle to extract.
timeout:
Timeout in seconds. Waits for task completion by default. The timeout does not abort the operation in
OneView, it just... | Below is the the instruction that describes the task:
### Input:
Extracts the existing bundle on the appliance and creates all the artifacts.
Args:
resource (dict): Artifact Bundle to extract.
timeout:
Timeout in seconds. Waits for task completion by default. The tim... |
def get_params(self, deep=False):
"""
returns a dict of all of the object's user-facing parameters
Parameters
----------
deep : boolean, default: False
when True, also gets non-user-facing paramters
Returns
-------
dict
"""
at... | returns a dict of all of the object's user-facing parameters
Parameters
----------
deep : boolean, default: False
when True, also gets non-user-facing paramters
Returns
-------
dict | Below is the the instruction that describes the task:
### Input:
returns a dict of all of the object's user-facing parameters
Parameters
----------
deep : boolean, default: False
when True, also gets non-user-facing paramters
Returns
-------
dict
### Res... |
def _init_metadata(self):
"""stub"""
self._zone_conditions_metadata = {
'zone_matches': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
'zone_conditions'),
'element_label': 'zone conditions... | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def _init_metadata(self):
"""stub"""
self._zone_conditions_metadata = {
'zone_matches': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
... |
def list_rules(self, chainname):
"""Returns a list of Rules in the specified chain.
"""
data = self.__run([self.__iptables_save, '-t', self.__name, '-c'])
return netfilter.parser.parse_rules(data, chainname) | Returns a list of Rules in the specified chain. | Below is the the instruction that describes the task:
### Input:
Returns a list of Rules in the specified chain.
### Response:
def list_rules(self, chainname):
"""Returns a list of Rules in the specified chain.
"""
data = self.__run([self.__iptables_save, '-t', self.__name, '-c'])
r... |
def resource_listing(cls, request) -> [(200, 'Ok', ResourceListingModel)]:
'''Return the list of all available resources on the system.
Resources are filtered according to the permission system, so querying
this resource as different users may bare different results.'''
apis = [api.get_... | Return the list of all available resources on the system.
Resources are filtered according to the permission system, so querying
this resource as different users may bare different results. | Below is the the instruction that describes the task:
### Input:
Return the list of all available resources on the system.
Resources are filtered according to the permission system, so querying
this resource as different users may bare different results.
### Response:
def resource_listing(cls, req... |
def ensure_unique_obs_ids_in_wide_data(obs_id_col, wide_data):
"""
Ensures that there is one observation per row in wide_data. Raises a
helpful ValueError if otherwise.
Parameters
----------
obs_id_col : str.
Denotes the column in `wide_data` that contains the observation ID
val... | Ensures that there is one observation per row in wide_data. Raises a
helpful ValueError if otherwise.
Parameters
----------
obs_id_col : str.
Denotes the column in `wide_data` that contains the observation ID
values for each row.
wide_data : pandas dataframe.
Contains one ro... | Below is the the instruction that describes the task:
### Input:
Ensures that there is one observation per row in wide_data. Raises a
helpful ValueError if otherwise.
Parameters
----------
obs_id_col : str.
Denotes the column in `wide_data` that contains the observation ID
values fo... |
def _enrollment_search(regid, verbose, transcriptable, changed_since_date):
"""
See SWS Enrollment search resource spec at:
https://wiki.cac.washington.edu/x/_qjeAw
:return: search result json data
"""
url = "{}{}&{}".format(enrollment_search_url_prefix,
regid,
... | See SWS Enrollment search resource spec at:
https://wiki.cac.washington.edu/x/_qjeAw
:return: search result json data | Below is the the instruction that describes the task:
### Input:
See SWS Enrollment search resource spec at:
https://wiki.cac.washington.edu/x/_qjeAw
:return: search result json data
### Response:
def _enrollment_search(regid, verbose, transcriptable, changed_since_date):
"""
See SWS Enrollment sea... |
def get_full_time_interval(self):
"""Give the full time interval of the file. Note that the real interval
can be longer because the sound file attached can be longer.
:returns: Tuple of the form: ``(min_time, max_time)``.
"""
return (0, 0) if not self.timeslots else\
... | Give the full time interval of the file. Note that the real interval
can be longer because the sound file attached can be longer.
:returns: Tuple of the form: ``(min_time, max_time)``. | Below is the the instruction that describes the task:
### Input:
Give the full time interval of the file. Note that the real interval
can be longer because the sound file attached can be longer.
:returns: Tuple of the form: ``(min_time, max_time)``.
### Response:
def get_full_time_interval(self):
... |
def _select_ps(p):
# There are more generic ways of doing this but profiling
# revealed that selecting these points is one of the slow
# things that is easy to change. This is about 11 times
# faster than the generic algorithm it is replacing.
#
# it is possible that different break points could... | returns the points to use for interpolating p | Below is the the instruction that describes the task:
### Input:
returns the points to use for interpolating p
### Response:
def _select_ps(p):
# There are more generic ways of doing this but profiling
# revealed that selecting these points is one of the slow
# things that is easy to change. This is ab... |
def sendResult(self, future):
"""Send back results to broker for distribution to parent task."""
# Greenlets cannot be pickled
future.greenlet = None
assert future._ended(), "The results are not valid"
self.socket.sendResult(future) | Send back results to broker for distribution to parent task. | Below is the the instruction that describes the task:
### Input:
Send back results to broker for distribution to parent task.
### Response:
def sendResult(self, future):
"""Send back results to broker for distribution to parent task."""
# Greenlets cannot be pickled
future.greenlet = None
... |
def positive_float(string):
"""Convert string to positive float."""
error_msg = 'Positive float required, {string} given.'.format(string=string)
try:
value = float(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value < 0:
raise ArgumentTypeError(error_msg)
... | Convert string to positive float. | Below is the the instruction that describes the task:
### Input:
Convert string to positive float.
### Response:
def positive_float(string):
"""Convert string to positive float."""
error_msg = 'Positive float required, {string} given.'.format(string=string)
try:
value = float(string)
except... |
def new(namespace, name, wdl, synopsis,
documentation=None, api_url=fapi.PROD_API_ROOT):
"""Create new FireCloud method.
If the namespace + name already exists, a new snapshot is created.
Args:
namespace (str): Method namespace for this method
name (str): Me... | Create new FireCloud method.
If the namespace + name already exists, a new snapshot is created.
Args:
namespace (str): Method namespace for this method
name (str): Method name
wdl (file): WDL description
synopsis (str): Short description of task
... | Below is the the instruction that describes the task:
### Input:
Create new FireCloud method.
If the namespace + name already exists, a new snapshot is created.
Args:
namespace (str): Method namespace for this method
name (str): Method name
wdl (file): WDL descr... |
def expand_region(tuple_of_s, a, b, start=0, stop=None):
'''Apply expend_slice on a tuple of slices'''
return tuple(expand_slice(s, a, b, start=start, stop=stop)
for s in tuple_of_s) | Apply expend_slice on a tuple of slices | Below is the the instruction that describes the task:
### Input:
Apply expend_slice on a tuple of slices
### Response:
def expand_region(tuple_of_s, a, b, start=0, stop=None):
'''Apply expend_slice on a tuple of slices'''
return tuple(expand_slice(s, a, b, start=start, stop=stop)
for s in ... |
def help_string():
"""Generate help string with contents of registry."""
help_str = """
Registry contents:
------------------
Models:
%s
HParams:
%s
RangedHParams:
%s
Problems:
%s
Optimizers:
%s
Attacks:
%s
Attack HParams:
%s
Pruning HParams:
%s
Pruning Strategies:
%s
Env Problems:
%s
... | Generate help string with contents of registry. | Below is the the instruction that describes the task:
### Input:
Generate help string with contents of registry.
### Response:
def help_string():
"""Generate help string with contents of registry."""
help_str = """
Registry contents:
------------------
Models:
%s
HParams:
%s
RangedHParams:
%s
Probl... |
def clear_cookie(self, name: str, path: str = "/", domain: str = None) -> None:
"""Deletes the cookie with the given name.
Due to limitations of the cookie protocol, you must pass the same
path and domain to clear a cookie as were used when that cookie
was set (but there is no way to fi... | Deletes the cookie with the given name.
Due to limitations of the cookie protocol, you must pass the same
path and domain to clear a cookie as were used when that cookie
was set (but there is no way to find out on the server side
which values were used for a given cookie).
Simi... | Below is the the instruction that describes the task:
### Input:
Deletes the cookie with the given name.
Due to limitations of the cookie protocol, you must pass the same
path and domain to clear a cookie as were used when that cookie
was set (but there is no way to find out on the server s... |
def _on_trigger(self, my_task):
"""
May be called to fire the Join before the incoming branches are
completed.
"""
for task in my_task.workflow.task_tree._find_any(self):
if task.thread_id != my_task.thread_id:
continue
self._do_join(task) | May be called to fire the Join before the incoming branches are
completed. | Below is the the instruction that describes the task:
### Input:
May be called to fire the Join before the incoming branches are
completed.
### Response:
def _on_trigger(self, my_task):
"""
May be called to fire the Join before the incoming branches are
completed.
"""
... |
def correct_maybe_zipped(fileloc):
"""
If the path contains a folder with a .zip suffix, then
the folder is treated as a zip archive and path to zip is returned.
"""
_, archive, filename = re.search(
r'((.*\.zip){})?(.*)'.format(re.escape(os.sep)), fileloc).groups()
if archive and zipfi... | If the path contains a folder with a .zip suffix, then
the folder is treated as a zip archive and path to zip is returned. | Below is the the instruction that describes the task:
### Input:
If the path contains a folder with a .zip suffix, then
the folder is treated as a zip archive and path to zip is returned.
### Response:
def correct_maybe_zipped(fileloc):
"""
If the path contains a folder with a .zip suffix, then
the... |
def _run_sql(self, sql, params, raw=True, output=False):
"""Prepares and runs an SQL query for the history database.
Parameters
----------
sql : str
Any filtering expressions to go after SELECT ... FROM ...
params : tuple
Parameters passed to the SQL query (t... | Prepares and runs an SQL query for the history database.
Parameters
----------
sql : str
Any filtering expressions to go after SELECT ... FROM ...
params : tuple
Parameters passed to the SQL query (to replace "?")
raw, output : bool
See :meth:`get_r... | Below is the the instruction that describes the task:
### Input:
Prepares and runs an SQL query for the history database.
Parameters
----------
sql : str
Any filtering expressions to go after SELECT ... FROM ...
params : tuple
Parameters passed to the SQL query (... |
def readme_for(self, subpath):
"""
Returns the full path for the README file for the specified
subpath, or the root filename if subpath is None.
Raises ReadmeNotFoundError if a README for the specified subpath
does not exist.
Raises werkzeug.exceptions.NotFound if the r... | Returns the full path for the README file for the specified
subpath, or the root filename if subpath is None.
Raises ReadmeNotFoundError if a README for the specified subpath
does not exist.
Raises werkzeug.exceptions.NotFound if the resulting path
would fall out of the root di... | Below is the the instruction that describes the task:
### Input:
Returns the full path for the README file for the specified
subpath, or the root filename if subpath is None.
Raises ReadmeNotFoundError if a README for the specified subpath
does not exist.
Raises werkzeug.exceptions... |
def convert_timedelta(obj):
"""Returns a TIME column as a timedelta object:
>>> timedelta_or_None('25:06:17')
datetime.timedelta(1, 3977)
>>> timedelta_or_None('-25:06:17')
datetime.timedelta(-2, 83177)
Illegal values are returned as None:
>>> timedelta_or_None('random crap') is... | Returns a TIME column as a timedelta object:
>>> timedelta_or_None('25:06:17')
datetime.timedelta(1, 3977)
>>> timedelta_or_None('-25:06:17')
datetime.timedelta(-2, 83177)
Illegal values are returned as None:
>>> timedelta_or_None('random crap') is None
True
Note that MyS... | Below is the the instruction that describes the task:
### Input:
Returns a TIME column as a timedelta object:
>>> timedelta_or_None('25:06:17')
datetime.timedelta(1, 3977)
>>> timedelta_or_None('-25:06:17')
datetime.timedelta(-2, 83177)
Illegal values are returned as None:
>>> t... |
def read_ermapper(self, ifile):
'''Read in a DEM file and associated .ers file'''
ers_index = ifile.find('.ers')
if ers_index > 0:
data_file = ifile[0:ers_index]
header_file = ifile
else:
data_file = ifile
header_file = ifile + '.ers'
... | Read in a DEM file and associated .ers file | Below is the the instruction that describes the task:
### Input:
Read in a DEM file and associated .ers file
### Response:
def read_ermapper(self, ifile):
'''Read in a DEM file and associated .ers file'''
ers_index = ifile.find('.ers')
if ers_index > 0:
data_file = ifile[0:ers_i... |
def fetch():
"""
Downloads the Lenz, Hensley & Doré (2017) dust map, placing it in the
default :obj:`dustmaps` data directory.
"""
doi = '10.7910/DVN/AFJNWJ'
fname = os.path.join(
data_dir(),
'lenz2017',
'ebv_lhd.hpx.fits')
fetch_utils.dataverse_download_doi(
... | Downloads the Lenz, Hensley & Doré (2017) dust map, placing it in the
default :obj:`dustmaps` data directory. | Below is the the instruction that describes the task:
### Input:
Downloads the Lenz, Hensley & Doré (2017) dust map, placing it in the
default :obj:`dustmaps` data directory.
### Response:
def fetch():
"""
Downloads the Lenz, Hensley & Doré (2017) dust map, placing it in the
default :obj:`dustmaps`... |
def remove(self, function, update=True):
""" Remove a function from the chain.
"""
self._funcs.remove(function)
self._remove_dep(function)
if update:
self._update() | Remove a function from the chain. | Below is the the instruction that describes the task:
### Input:
Remove a function from the chain.
### Response:
def remove(self, function, update=True):
""" Remove a function from the chain.
"""
self._funcs.remove(function)
self._remove_dep(function)
if update:
... |
def validate_type(prop, value, expected):
""" Default validation for all types """
# Validate on expected type(s), but ignore None: defaults handled elsewhere
if value is not None and not isinstance(value, expected):
_validation_error(prop, type(value).__name__, None, expected) | Default validation for all types | Below is the the instruction that describes the task:
### Input:
Default validation for all types
### Response:
def validate_type(prop, value, expected):
""" Default validation for all types """
# Validate on expected type(s), but ignore None: defaults handled elsewhere
if value is not None and not is... |
def DCM_update(IMU, ATT, MAG, GPS):
'''implement full DCM system'''
global dcm_state
if dcm_state is None:
dcm_state = DCM_State(ATT.Roll, ATT.Pitch, ATT.Yaw)
mag = Vector3(MAG.MagX, MAG.MagY, MAG.MagZ)
gyro = Vector3(IMU.GyrX, IMU.GyrY, IMU.GyrZ)
accel = Vector3(IMU.AccX, IMU.AccY, ... | implement full DCM system | Below is the the instruction that describes the task:
### Input:
implement full DCM system
### Response:
def DCM_update(IMU, ATT, MAG, GPS):
'''implement full DCM system'''
global dcm_state
if dcm_state is None:
dcm_state = DCM_State(ATT.Roll, ATT.Pitch, ATT.Yaw)
mag = Vector3(MAG.MagX, ... |
def tf_step(self, time, variables, arguments, fn_reference=None, **kwargs):
"""
Creates the TensorFlow operations for performing an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
arguments: Dict of arguments for callable... | Creates the TensorFlow operations for performing an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
arguments: Dict of arguments for callables, like fn_loss.
fn_reference: A callable returning the reference values, in case of... | Below is the the instruction that describes the task:
### Input:
Creates the TensorFlow operations for performing an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
arguments: Dict of arguments for callables, like fn_loss.
... |
def bin_width_doane(a):
"""Compute accuracy (bin width) based on Doane's formula
References
----------
- `<https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width>`_
- `<https://stats.stackexchange.com/questions/55134/
doanes-formula-for-histogram-binning>`_
"""
bad = np.isna... | Compute accuracy (bin width) based on Doane's formula
References
----------
- `<https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width>`_
- `<https://stats.stackexchange.com/questions/55134/
doanes-formula-for-histogram-binning>`_ | Below is the the instruction that describes the task:
### Input:
Compute accuracy (bin width) based on Doane's formula
References
----------
- `<https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width>`_
- `<https://stats.stackexchange.com/questions/55134/
doanes-formula-for-histogra... |
def common_items_ratio(pronac, dt):
"""
Calculates the common items on projects in a cultural segment,
calculates the uncommon items on projects in a cultural segment and
verify if a project is an outlier compared to the other projects
in his segment.
"""
segment_id = get_segment_id(str(pron... | Calculates the common items on projects in a cultural segment,
calculates the uncommon items on projects in a cultural segment and
verify if a project is an outlier compared to the other projects
in his segment. | Below is the the instruction that describes the task:
### Input:
Calculates the common items on projects in a cultural segment,
calculates the uncommon items on projects in a cultural segment and
verify if a project is an outlier compared to the other projects
in his segment.
### Response:
def common_i... |
def predict(model, X, joint_contribution=False):
""" Returns a triple (prediction, bias, feature_contributions), such
that prediction ≈ bias + feature_contributions.
Parameters
----------
model : DecisionTreeRegressor, DecisionTreeClassifier,
ExtraTreeRegressor, ExtraTreeClassifier,
... | Returns a triple (prediction, bias, feature_contributions), such
that prediction ≈ bias + feature_contributions.
Parameters
----------
model : DecisionTreeRegressor, DecisionTreeClassifier,
ExtraTreeRegressor, ExtraTreeClassifier,
RandomForestRegressor, RandomForestClassifier,
Ex... | Below is the the instruction that describes the task:
### Input:
Returns a triple (prediction, bias, feature_contributions), such
that prediction ≈ bias + feature_contributions.
Parameters
----------
model : DecisionTreeRegressor, DecisionTreeClassifier,
ExtraTreeRegressor, ExtraTreeClassifi... |
def pause():
"""Tell iTunes to pause"""
if not settings.platformCompatible():
return False
(output, error) = subprocess.Popen(["osascript", "-e", PAUSE], stdout=subprocess.PIPE).communicate() | Tell iTunes to pause | Below is the the instruction that describes the task:
### Input:
Tell iTunes to pause
### Response:
def pause():
"""Tell iTunes to pause"""
if not settings.platformCompatible():
return False
(output, error) = subprocess.Popen(["osascript", "-e", PAUSE], stdout=subprocess.PIPE).communicate() |
def create_parser(self, prog_name, subcommand):
"""
Create and return the ``ArgumentParser`` which will be used to
parse the arguments to this command.
"""
parser = ArgumentParser(
description=self.description,
epilog=self.epilog,
add_... | Create and return the ``ArgumentParser`` which will be used to
parse the arguments to this command. | Below is the the instruction that describes the task:
### Input:
Create and return the ``ArgumentParser`` which will be used to
parse the arguments to this command.
### Response:
def create_parser(self, prog_name, subcommand):
"""
Create and return the ``ArgumentParser`` which will be used ... |
def lcv(var, assignment, csp):
"Least-constraining-values heuristic."
return sorted(csp.choices(var),
key=lambda val: csp.nconflicts(var, val, assignment)) | Least-constraining-values heuristic. | Below is the the instruction that describes the task:
### Input:
Least-constraining-values heuristic.
### Response:
def lcv(var, assignment, csp):
"Least-constraining-values heuristic."
return sorted(csp.choices(var),
key=lambda val: csp.nconflicts(var, val, assignment)) |
def wait_for_service_endpoint(service_name, timeout_sec=120):
"""Checks the service url if available it returns true, on expiration
it returns false"""
master_count = len(get_all_masters())
return time_wait(lambda: service_available_predicate(service_name),
timeout_seconds=timeout_... | Checks the service url if available it returns true, on expiration
it returns false | Below is the the instruction that describes the task:
### Input:
Checks the service url if available it returns true, on expiration
it returns false
### Response:
def wait_for_service_endpoint(service_name, timeout_sec=120):
"""Checks the service url if available it returns true, on expiration
it retur... |
def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
salt '*' sysctl.persist coretemp_load NO config=/boot/loader.conf
'''
nlines... | Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
salt '*' sysctl.persist coretemp_load NO config=/boot/loader.conf | Below is the the instruction that describes the task:
### Input:
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
salt '*' sysctl.persist coretemp_load NO config=/boot/loader.conf
### Response: ... |
def get_value_from_environment(
section_name,
key_name,
envname_pad=ENVNAME_PAD,
logger=logging.getLogger('ProsperCommon'),
):
"""check environment for key/value pair
Args:
section_name (str): section name
key_name (str): key to look up
envname_pad (str):... | check environment for key/value pair
Args:
section_name (str): section name
key_name (str): key to look up
envname_pad (str): namespace padding
logger (:obj:`logging.logger`): logging handle
Returns:
str: value in environment | Below is the the instruction that describes the task:
### Input:
check environment for key/value pair
Args:
section_name (str): section name
key_name (str): key to look up
envname_pad (str): namespace padding
logger (:obj:`logging.logger`): logging handle
Returns:
s... |
def pad(num, n=2, sign=False):
'''returns n digit string representation of the num'''
s = unicode(abs(num))
if len(s) < n:
s = '0' * (n - len(s)) + s
if not sign:
return s
if num >= 0:
return '+' + s
else:
return '-' + s | returns n digit string representation of the num | Below is the the instruction that describes the task:
### Input:
returns n digit string representation of the num
### Response:
def pad(num, n=2, sign=False):
'''returns n digit string representation of the num'''
s = unicode(abs(num))
if len(s) < n:
s = '0' * (n - len(s)) + s
if not sign:
... |
def runSetup():
"""
Calls setup(). This function exists so the setup() invocation preceded more internal
functionality. The `version` module is imported dynamically by importVersion() below.
"""
boto = 'boto==2.48.0'
boto3 = 'boto3>=1.7.50, <2.0'
futures = 'futures==3.1.1'
pycryptodome =... | Calls setup(). This function exists so the setup() invocation preceded more internal
functionality. The `version` module is imported dynamically by importVersion() below. | Below is the the instruction that describes the task:
### Input:
Calls setup(). This function exists so the setup() invocation preceded more internal
functionality. The `version` module is imported dynamically by importVersion() below.
### Response:
def runSetup():
"""
Calls setup(). This function exis... |
def sync(self):
"""Sync this model with latest data on the saltant server.
Note that in addition to returning the updated object, it also
updates the existing object.
Returns:
:class:`saltant.models.user.User`:
This user instance after syncing.
"""
... | Sync this model with latest data on the saltant server.
Note that in addition to returning the updated object, it also
updates the existing object.
Returns:
:class:`saltant.models.user.User`:
This user instance after syncing. | Below is the the instruction that describes the task:
### Input:
Sync this model with latest data on the saltant server.
Note that in addition to returning the updated object, it also
updates the existing object.
Returns:
:class:`saltant.models.user.User`:
This ... |
def prune(args):
"""
%prog prune best.edges
Prune overlap graph.
"""
from collections import defaultdict
p = OptionParser(prune.__doc__)
add_graph_options(p)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bestedges, = args
G = read... | %prog prune best.edges
Prune overlap graph. | Below is the the instruction that describes the task:
### Input:
%prog prune best.edges
Prune overlap graph.
### Response:
def prune(args):
"""
%prog prune best.edges
Prune overlap graph.
"""
from collections import defaultdict
p = OptionParser(prune.__doc__)
add_graph_options(p)... |
def get_unit(self, ureg, unit_variations):
"""
Get the first match unit metric object supported by pint library
given a variation of unit metric names (Ex:['HOUR', 'hour']).
:param ureg: unit registry which units are defined and handled
:type ureg: pint.registry.UnitRegistry obj... | Get the first match unit metric object supported by pint library
given a variation of unit metric names (Ex:['HOUR', 'hour']).
:param ureg: unit registry which units are defined and handled
:type ureg: pint.registry.UnitRegistry object
:param unit_variations: A list of strings with nam... | Below is the the instruction that describes the task:
### Input:
Get the first match unit metric object supported by pint library
given a variation of unit metric names (Ex:['HOUR', 'hour']).
:param ureg: unit registry which units are defined and handled
:type ureg: pint.registry.UnitRegist... |
def get_social_login(self, adapter, app, token, response):
"""
:param adapter: allauth.socialaccount Adapter subclass.
Usually OAuthAdapter or Auth2Adapter
:param app: `allauth.socialaccount.SocialApp` instance
:param token: `allauth.socialaccount.SocialToken` instance
... | :param adapter: allauth.socialaccount Adapter subclass.
Usually OAuthAdapter or Auth2Adapter
:param app: `allauth.socialaccount.SocialApp` instance
:param token: `allauth.socialaccount.SocialToken` instance
:param response: Provider's response for OAuth1. Not used in the
:ret... | Below is the the instruction that describes the task:
### Input:
:param adapter: allauth.socialaccount Adapter subclass.
Usually OAuthAdapter or Auth2Adapter
:param app: `allauth.socialaccount.SocialApp` instance
:param token: `allauth.socialaccount.SocialToken` instance
:param r... |
def get_asides(self, block):
"""
Return instances for all of the asides that will decorate this `block`.
Arguments:
block (:class:`.XBlock`): The block to render retrieve asides for.
Returns:
List of XBlockAside instances
"""
aside_instances = [
... | Return instances for all of the asides that will decorate this `block`.
Arguments:
block (:class:`.XBlock`): The block to render retrieve asides for.
Returns:
List of XBlockAside instances | Below is the the instruction that describes the task:
### Input:
Return instances for all of the asides that will decorate this `block`.
Arguments:
block (:class:`.XBlock`): The block to render retrieve asides for.
Returns:
List of XBlockAside instances
### Response:
def g... |
def _clear(reason, idle_pool, using_pool, channel_pool, conn_id):
"""
clear the bad connection
:param reason:
:param idle_pool:
:param using_pool:
:param channel_pool:
:param conn_id:
:return:
"""
with _lock():
try:
... | clear the bad connection
:param reason:
:param idle_pool:
:param using_pool:
:param channel_pool:
:param conn_id:
:return: | Below is the the instruction that describes the task:
### Input:
clear the bad connection
:param reason:
:param idle_pool:
:param using_pool:
:param channel_pool:
:param conn_id:
:return:
### Response:
def _clear(reason, idle_pool, using_pool, channel_pool, conn_id):... |
def get_as_boolean_with_default(self, key, default_value):
"""
Converts map element into a boolean or returns default value if conversion is not possible.
:param key: an index of element to get.
:param default_value: the default value
:return: boolean value ot the element or d... | Converts map element into a boolean or returns default value if conversion is not possible.
:param key: an index of element to get.
:param default_value: the default value
:return: boolean value ot the element or default value if conversion is not supported. | Below is the the instruction that describes the task:
### Input:
Converts map element into a boolean or returns default value if conversion is not possible.
:param key: an index of element to get.
:param default_value: the default value
:return: boolean value ot the element or default val... |
def get_stats(
self,
instance,
base_url,
object_type,
max_detailed,
filters,
limit_vhosts,
custom_tags,
auth=None,
ssl_verify=True,
):
"""
instance: the check instance
base_url: the url of the rabbitmq management... | instance: the check instance
base_url: the url of the rabbitmq management api (e.g. http://localhost:15672/api)
object_type: either QUEUE_TYPE or NODE_TYPE or EXCHANGE_TYPE
max_detailed: the limit of objects to collect for this type
filters: explicit or regexes filters of specified queue... | Below is the the instruction that describes the task:
### Input:
instance: the check instance
base_url: the url of the rabbitmq management api (e.g. http://localhost:15672/api)
object_type: either QUEUE_TYPE or NODE_TYPE or EXCHANGE_TYPE
max_detailed: the limit of objects to collect for this... |
def _check_ip(self, ip):
"""Here all the workload happens. Read the files, check if the ip is in there and report the results.
If the lock file is found, which gets created when lists are getting updated, the script starts to sleep 10
seconds before checking again. Also reads the source file dat... | Here all the workload happens. Read the files, check if the ip is in there and report the results.
If the lock file is found, which gets created when lists are getting updated, the script starts to sleep 10
seconds before checking again. Also reads the source file date and checks, if its too old (ignore... | Below is the the instruction that describes the task:
### Input:
Here all the workload happens. Read the files, check if the ip is in there and report the results.
If the lock file is found, which gets created when lists are getting updated, the script starts to sleep 10
seconds before checking agai... |
def notify(self, *args, **kwargs):
'''Call all the callback handlers with given arguments.'''
for handler in tuple(self.handlers):
handler(*args, **kwargs) | Call all the callback handlers with given arguments. | Below is the the instruction that describes the task:
### Input:
Call all the callback handlers with given arguments.
### Response:
def notify(self, *args, **kwargs):
'''Call all the callback handlers with given arguments.'''
for handler in tuple(self.handlers):
handler(*args, **kwargs) |
def send_image(self, sender, receiver_type, receiver_id, media_id):
"""
发送图片消息
详情请参考
https://qydev.weixin.qq.com/wiki/index.php?title=企业会话接口说明
:param sender: 发送人
:param receiver_type: 接收人类型:single|group,分别表示:单聊|群聊
:param receiver_id: 接收人的值,为userid|chatid,分别表示:成员... | 发送图片消息
详情请参考
https://qydev.weixin.qq.com/wiki/index.php?title=企业会话接口说明
:param sender: 发送人
:param receiver_type: 接收人类型:single|group,分别表示:单聊|群聊
:param receiver_id: 接收人的值,为userid|chatid,分别表示:成员id|会话id
:param media_id: 图片媒体文件id,可以调用上传素材文件接口获取
:return: 返回的 JSON 数据包 | Below is the the instruction that describes the task:
### Input:
发送图片消息
详情请参考
https://qydev.weixin.qq.com/wiki/index.php?title=企业会话接口说明
:param sender: 发送人
:param receiver_type: 接收人类型:single|group,分别表示:单聊|群聊
:param receiver_id: 接收人的值,为userid|chatid,分别表示:成员id|会话id
:pa... |
def get_context(self):
" Get context to render the template. "
return {
'content_type_name' : str(self.name),
'content_type_verbose_name' : self.verbose_name,
'content_type_verbose_name_plural' : self.verbose_name_plural,
'object' : self.ob... | Get context to render the template. | Below is the the instruction that describes the task:
### Input:
Get context to render the template.
### Response:
def get_context(self):
" Get context to render the template. "
return {
'content_type_name' : str(self.name),
'content_type_verbose_name' : self.verbose... |
def ncbi_geneid(self):
"""
Retrieve this feature's NCBI GeneID if it's present.
NCBI GFF3 files contain gene IDs encoded in **Dbxref** attributes
(example: `Dbxref=GeneID:103504972`). This function locates and returns
the GeneID if present, or returns `None` otherwise.
"... | Retrieve this feature's NCBI GeneID if it's present.
NCBI GFF3 files contain gene IDs encoded in **Dbxref** attributes
(example: `Dbxref=GeneID:103504972`). This function locates and returns
the GeneID if present, or returns `None` otherwise. | Below is the the instruction that describes the task:
### Input:
Retrieve this feature's NCBI GeneID if it's present.
NCBI GFF3 files contain gene IDs encoded in **Dbxref** attributes
(example: `Dbxref=GeneID:103504972`). This function locates and returns
the GeneID if present, or returns `... |
def OnSelectReader(self, reader):
"""Called when a reader is selected by clicking on the reader
tree control or toolbar."""
SimpleSCardAppEventObserver.OnSelectReader(self, reader)
self.feedbacktext.SetLabel('Selected reader: ' + repr(reader)) | Called when a reader is selected by clicking on the reader
tree control or toolbar. | Below is the the instruction that describes the task:
### Input:
Called when a reader is selected by clicking on the reader
tree control or toolbar.
### Response:
def OnSelectReader(self, reader):
"""Called when a reader is selected by clicking on the reader
tree control or toolbar."""
... |
def list_lbaas_l7policies(self, retrieve_all=True, **_params):
"""Fetches a list of all L7 policies for a listener."""
return self.list('l7policies', self.lbaas_l7policies_path,
retrieve_all, **_params) | Fetches a list of all L7 policies for a listener. | Below is the the instruction that describes the task:
### Input:
Fetches a list of all L7 policies for a listener.
### Response:
def list_lbaas_l7policies(self, retrieve_all=True, **_params):
"""Fetches a list of all L7 policies for a listener."""
return self.list('l7policies', self.lbaas_l7policie... |
def progress(status_code):
"""Translate PROGRESS status codes from GnuPG to messages."""
lookup = {
'pk_dsa': 'DSA key generation',
'pk_elg': 'Elgamal key generation',
'primegen': 'Prime generation',
'need_entropy': 'Waiting for new entropy in the RNG',
'tick': 'Generic t... | Translate PROGRESS status codes from GnuPG to messages. | Below is the the instruction that describes the task:
### Input:
Translate PROGRESS status codes from GnuPG to messages.
### Response:
def progress(status_code):
"""Translate PROGRESS status codes from GnuPG to messages."""
lookup = {
'pk_dsa': 'DSA key generation',
'pk_elg': 'Elgamal key g... |
def postParse(self, instring, loc, token_list):
"""Create a list from the tokens
:param instring:
:param loc:
:param token_list:
:return:
"""
cleaned_token_list = [token for tokens in (token.tokens if isinstance(token, ConfigInclude) else [token]
... | Create a list from the tokens
:param instring:
:param loc:
:param token_list:
:return: | Below is the the instruction that describes the task:
### Input:
Create a list from the tokens
:param instring:
:param loc:
:param token_list:
:return:
### Response:
def postParse(self, instring, loc, token_list):
"""Create a list from the tokens
:param instring:
... |
def tfidf_corpus(docs=CORPUS):
""" Count the words in a corpus and return a TfidfVectorizer() as well as all the TFIDF vecgtors for the corpus
Args:
docs (iterable of strs): a sequence of documents (strings)
Returns:
(TfidfVectorizer, tfidf_vectors)
"""
vectorizer = TfidfVectorizer()
... | Count the words in a corpus and return a TfidfVectorizer() as well as all the TFIDF vecgtors for the corpus
Args:
docs (iterable of strs): a sequence of documents (strings)
Returns:
(TfidfVectorizer, tfidf_vectors) | Below is the the instruction that describes the task:
### Input:
Count the words in a corpus and return a TfidfVectorizer() as well as all the TFIDF vecgtors for the corpus
Args:
docs (iterable of strs): a sequence of documents (strings)
Returns:
(TfidfVectorizer, tfidf_vectors)
### Response: ... |
def _parse(yr, mo, day):
"""
Basic parser to deal with date format of the Kp file.
"""
yr = '20'+yr
yr = int(yr)
mo = int(mo)
day = int(day)
return pds.datetime(yr, mo, day) | Basic parser to deal with date format of the Kp file. | Below is the the instruction that describes the task:
### Input:
Basic parser to deal with date format of the Kp file.
### Response:
def _parse(yr, mo, day):
"""
Basic parser to deal with date format of the Kp file.
"""
yr = '20'+yr
yr = int(yr)
mo = int(mo)
day = int(day)
retu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.