code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def OnOpen(self, event):
"""File open event handler"""
# If changes have taken place save of old grid
if undo.stack().haschanged():
save_choice = self.interfaces.get_save_request_from_user()
if save_choice is None:
# Cancelled close operation
... | File open event handler | Below is the the instruction that describes the task:
### Input:
File open event handler
### Response:
def OnOpen(self, event):
"""File open event handler"""
# If changes have taken place save of old grid
if undo.stack().haschanged():
save_choice = self.interfaces.get_save_requ... |
def preprocess_legislation(legislation_json):
'''
Preprocess the legislation parameters to add prices and amounts from national accounts
'''
import os
import pkg_resources
import pandas as pd
# Add fuel prices to the tree
default_config_files_directory = os.path.join(
pkg_resou... | Preprocess the legislation parameters to add prices and amounts from national accounts | Below is the the instruction that describes the task:
### Input:
Preprocess the legislation parameters to add prices and amounts from national accounts
### Response:
def preprocess_legislation(legislation_json):
'''
Preprocess the legislation parameters to add prices and amounts from national accounts
... |
def contains_no_backer(self, addr):
"""
Tests if the address is contained in any page of paged memory, without considering memory backers.
:param int addr: The address to test.
:return: True if the address is included in one of the pages, False otherwise.
:rtype: bool
""... | Tests if the address is contained in any page of paged memory, without considering memory backers.
:param int addr: The address to test.
:return: True if the address is included in one of the pages, False otherwise.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Tests if the address is contained in any page of paged memory, without considering memory backers.
:param int addr: The address to test.
:return: True if the address is included in one of the pages, False otherwise.
:rtype: bo... |
def lambda_return(reward, value, length, discount, lambda_):
"""TD-lambda returns."""
timestep = tf.range(reward.shape[1].value)
mask = tf.cast(timestep[None, :] < length[:, None], tf.float32)
sequence = mask * reward + discount * value * (1 - lambda_)
discount = mask * discount * lambda_
sequence = tf.stac... | TD-lambda returns. | Below is the the instruction that describes the task:
### Input:
TD-lambda returns.
### Response:
def lambda_return(reward, value, length, discount, lambda_):
"""TD-lambda returns."""
timestep = tf.range(reward.shape[1].value)
mask = tf.cast(timestep[None, :] < length[:, None], tf.float32)
sequence = mask ... |
def virtual_machines_list_all(**kwargs):
'''
.. versionadded:: 2019.2.0
List all virtual machines within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list_all
'''
result = {}
compconn = __utils__['azurearm.get_client']('comput... | .. versionadded:: 2019.2.0
List all virtual machines within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list_all | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2019.2.0
List all virtual machines within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list_all
### Response:
def virtual_machines_list_all(**kwargs):
'''
... |
def synthesize(vers, opts):
""" Synthesize a capability enabled version response
This is a very limited emulation for relatively recent feature sets
"""
parsed_version = parse_version(vers["version"])
vers["capabilities"] = {}
for name in opts["optional"]:
vers["capabilities"][name] ... | Synthesize a capability enabled version response
This is a very limited emulation for relatively recent feature sets | Below is the the instruction that describes the task:
### Input:
Synthesize a capability enabled version response
This is a very limited emulation for relatively recent feature sets
### Response:
def synthesize(vers, opts):
""" Synthesize a capability enabled version response
This is a very lim... |
def sliver_reader(filename_end_mask="*[0-9].mhd", sliver_reference_dir="~/data/medical/orig/sliver07/training/", read_orig=True, read_seg=False):
"""
Generator for reading sliver data from directory structure.
:param filename_end_mask: file selection can be controlled with this parameter
:param sliver_... | Generator for reading sliver data from directory structure.
:param filename_end_mask: file selection can be controlled with this parameter
:param sliver_reference_dir: directory with sliver .mhd and .raw files
:param read_orig: read image data if is set True
:param read_seg: read segmentation data if i... | Below is the the instruction that describes the task:
### Input:
Generator for reading sliver data from directory structure.
:param filename_end_mask: file selection can be controlled with this parameter
:param sliver_reference_dir: directory with sliver .mhd and .raw files
:param read_orig: read image... |
def anyword_substring_search_inner(query_word, target_words):
""" return True if ANY target_word matches a query_word
"""
for target_word in target_words:
if(target_word.startswith(query_word)):
return query_word
return False | return True if ANY target_word matches a query_word | Below is the the instruction that describes the task:
### Input:
return True if ANY target_word matches a query_word
### Response:
def anyword_substring_search_inner(query_word, target_words):
""" return True if ANY target_word matches a query_word
"""
for target_word in target_words:
if(targ... |
def find_tf_idf(file_names=['./../test/testdata'],prev_file_path=None, dump_path=None):
'''Function to create a TF-IDF list of dictionaries for a corpus of docs.
If you opt for dumping the data, you can provide a file_path with .tfidfpkl extension(standard made for better understanding)
and also re-generate... | Function to create a TF-IDF list of dictionaries for a corpus of docs.
If you opt for dumping the data, you can provide a file_path with .tfidfpkl extension(standard made for better understanding)
and also re-generate a new tfidf list which overrides over an old one by mentioning its path.
@Args:
--
... | Below is the the instruction that describes the task:
### Input:
Function to create a TF-IDF list of dictionaries for a corpus of docs.
If you opt for dumping the data, you can provide a file_path with .tfidfpkl extension(standard made for better understanding)
and also re-generate a new tfidf list which ov... |
def cbpdnmd_ystep(k):
"""Do the Y step of the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables.
"""
if mp_W.shape[0] > 1:
W = mp_W[k]
else:
W = mp_W
AXU0 = mp_DX[k] - mp_S[k] + mp_Z... | Do the Y step of the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables. | Below is the the instruction that describes the task:
### Input:
Do the Y step of the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables.
### Response:
def cbpdnmd_ystep(k):
"""Do the Y step of the cbpdn stage. ... |
def get(self, sid):
"""
Constructs a SessionContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.session.SessionContext
:rtype: twilio.rest.proxy.v1.service.session.SessionContext
"""
return SessionContext(sel... | Constructs a SessionContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.session.SessionContext
:rtype: twilio.rest.proxy.v1.service.session.SessionContext | Below is the the instruction that describes the task:
### Input:
Constructs a SessionContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.session.SessionContext
:rtype: twilio.rest.proxy.v1.service.session.SessionContext
### Response:
d... |
def choose_colour(self, title="Select Colour", **kwargs):
"""
Show a Colour Chooser dialog
Usage: C{dialog.choose_colour(title="Select Colour")}
@param title: window title for the dialog
@return:
@rtype: C{DialogData(int, Optional[ColourData])}
"... | Show a Colour Chooser dialog
Usage: C{dialog.choose_colour(title="Select Colour")}
@param title: window title for the dialog
@return:
@rtype: C{DialogData(int, Optional[ColourData])} | Below is the the instruction that describes the task:
### Input:
Show a Colour Chooser dialog
Usage: C{dialog.choose_colour(title="Select Colour")}
@param title: window title for the dialog
@return:
@rtype: C{DialogData(int, Optional[ColourData])}
### Response:
def... |
def _validate_first_message(cls, msg):
"""Check the first message matches the expected handshake.
Note:
The handshake is provided as :py:attr:`RTM_HANDSHAKE`.
Arguments:
msg (:py:class:`aiohttp.Message`): The message to validate.
Raises:
:py:class:`SlackA... | Check the first message matches the expected handshake.
Note:
The handshake is provided as :py:attr:`RTM_HANDSHAKE`.
Arguments:
msg (:py:class:`aiohttp.Message`): The message to validate.
Raises:
:py:class:`SlackApiError`: If the data doesn't match the
... | Below is the the instruction that describes the task:
### Input:
Check the first message matches the expected handshake.
Note:
The handshake is provided as :py:attr:`RTM_HANDSHAKE`.
Arguments:
msg (:py:class:`aiohttp.Message`): The message to validate.
Raises:
... |
def _validateListedSubdirsExist(self, component):
''' Return true if all the subdirectories which this component lists in
its module.json file exist (although their validity is otherwise
not checked).
If they don't, warning messages are printed.
'''
lib_subdi... | Return true if all the subdirectories which this component lists in
its module.json file exist (although their validity is otherwise
not checked).
If they don't, warning messages are printed. | Below is the the instruction that describes the task:
### Input:
Return true if all the subdirectories which this component lists in
its module.json file exist (although their validity is otherwise
not checked).
If they don't, warning messages are printed.
### Response:
def _va... |
def _increment_504_stat(self, request):
'''
Increments the 504 stat counters
@param request: The scrapy request in the spider
'''
for key in self.stats_dict:
if key == 'lifetime':
unique = request.url + str(time.time())
self.stats_dict... | Increments the 504 stat counters
@param request: The scrapy request in the spider | Below is the the instruction that describes the task:
### Input:
Increments the 504 stat counters
@param request: The scrapy request in the spider
### Response:
def _increment_504_stat(self, request):
'''
Increments the 504 stat counters
@param request: The scrapy request in the s... |
def layer_uri(self, layer_name):
"""Get layer URI.
:param layer_name: The name of the layer to fetch.
:type layer_name: str
:return: The URI to the layer.
:rtype: str
.. versionadded:: 4.0
"""
layers = self.layers()
for layer, extension in produ... | Get layer URI.
:param layer_name: The name of the layer to fetch.
:type layer_name: str
:return: The URI to the layer.
:rtype: str
.. versionadded:: 4.0 | Below is the the instruction that describes the task:
### Input:
Get layer URI.
:param layer_name: The name of the layer to fetch.
:type layer_name: str
:return: The URI to the layer.
:rtype: str
.. versionadded:: 4.0
### Response:
def layer_uri(self, layer_name):
... |
def variability_threshold(featuresdir,
outfile,
magbins=DEFAULT_MAGBINS,
maxobjects=None,
timecols=None,
magcols=None,
errcols=None,
lcfor... | This generates a list of objects with stetson J, IQR, and 1.0/eta
above some threshold value to select them as potential variable stars.
Use this to pare down the objects to review and put through
period-finding. This does the thresholding per magnitude bin; this should be
better than one single cut th... | Below is the the instruction that describes the task:
### Input:
This generates a list of objects with stetson J, IQR, and 1.0/eta
above some threshold value to select them as potential variable stars.
Use this to pare down the objects to review and put through
period-finding. This does the thresholdin... |
def _get_names(self):
"""Get the list of first names.
:return: A list of first name entries.
"""
names = self._read_name_file('names.json')
names = self._compute_weights(names)
return names | Get the list of first names.
:return: A list of first name entries. | Below is the the instruction that describes the task:
### Input:
Get the list of first names.
:return: A list of first name entries.
### Response:
def _get_names(self):
"""Get the list of first names.
:return: A list of first name entries.
"""
names = self._read_name_file(... |
def main():
""" Get arguments and call the execution function"""
if len(sys.argv) < 6:
print("Usage: %s server_url username password namespace' \
' classname" % sys.argv[0])
print('Using internal defaults')
server_url = SERVER_URL
namespace = TEST_NAMESPACE
... | Get arguments and call the execution function | Below is the the instruction that describes the task:
### Input:
Get arguments and call the execution function
### Response:
def main():
""" Get arguments and call the execution function"""
if len(sys.argv) < 6:
print("Usage: %s server_url username password namespace' \
' classname" ... |
def added(self):
'''
Returns all keys that have been added.
If the keys are in child dictionaries they will be represented with
. notation
'''
def _added(diffs, prefix):
keys = []
for key in diffs.keys():
if isinstance(diffs[key], ... | Returns all keys that have been added.
If the keys are in child dictionaries they will be represented with
. notation | Below is the the instruction that describes the task:
### Input:
Returns all keys that have been added.
If the keys are in child dictionaries they will be represented with
. notation
### Response:
def added(self):
'''
Returns all keys that have been added.
If the keys are ... |
def replace(path, value, **kwargs):
"""
Replace an existing path. This works on any valid path if the path already
exists. Valid only in :cb_bmeth:`mutate_in`
:param path: The path to replace
:param value: The new value
"""
return _gen_4spec(LCB_SDCMD_REPLACE, path, value,
... | Replace an existing path. This works on any valid path if the path already
exists. Valid only in :cb_bmeth:`mutate_in`
:param path: The path to replace
:param value: The new value | Below is the the instruction that describes the task:
### Input:
Replace an existing path. This works on any valid path if the path already
exists. Valid only in :cb_bmeth:`mutate_in`
:param path: The path to replace
:param value: The new value
### Response:
def replace(path, value, **kwargs):
"""... |
def pyside_load_ui(uifile, base_instance=None):
"""Provide PyQt4.uic.loadUi functionality to PySide
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Note:
pysideuic is required for this to work with PySide.
... | Provide PyQt4.uic.loadUi functionality to PySide
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Note:
pysideuic is required for this to work with PySide.
This seems to work correctly in Maya as well as outsid... | Below is the the instruction that describes the task:
### Input:
Provide PyQt4.uic.loadUi functionality to PySide
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Note:
pysideuic is required for this to work with Py... |
def find_types(observatory, match=None, trend=None,
connection=None, **connection_kw):
"""Find the available data types for a given observatory.
See also
--------
gwdatafind.http.HTTPConnection.find_types
FflConnection.find_types
for details on the underlying method(s)
""... | Find the available data types for a given observatory.
See also
--------
gwdatafind.http.HTTPConnection.find_types
FflConnection.find_types
for details on the underlying method(s) | Below is the the instruction that describes the task:
### Input:
Find the available data types for a given observatory.
See also
--------
gwdatafind.http.HTTPConnection.find_types
FflConnection.find_types
for details on the underlying method(s)
### Response:
def find_types(observatory, mat... |
def get_scopes_for(self, user_provided_scopes):
""" Returns a list of scopes needed for each of the
scope_helpers provided, by adding the prefix to them if required
:param user_provided_scopes: a list of scopes or scope helpers
:type user_provided_scopes: list or tuple or str
:r... | Returns a list of scopes needed for each of the
scope_helpers provided, by adding the prefix to them if required
:param user_provided_scopes: a list of scopes or scope helpers
:type user_provided_scopes: list or tuple or str
:return: scopes with url prefix added
:rtype: list
... | Below is the the instruction that describes the task:
### Input:
Returns a list of scopes needed for each of the
scope_helpers provided, by adding the prefix to them if required
:param user_provided_scopes: a list of scopes or scope helpers
:type user_provided_scopes: list or tuple or str
... |
def get_route_name(resource_uri):
""" Get route name from RAML resource URI.
:param resource_uri: String representing RAML resource URI.
:returns string: String with route name, which is :resource_uri:
stripped of non-word characters.
"""
resource_uri = resource_uri.strip('/')
resource_... | Get route name from RAML resource URI.
:param resource_uri: String representing RAML resource URI.
:returns string: String with route name, which is :resource_uri:
stripped of non-word characters. | Below is the the instruction that describes the task:
### Input:
Get route name from RAML resource URI.
:param resource_uri: String representing RAML resource URI.
:returns string: String with route name, which is :resource_uri:
stripped of non-word characters.
### Response:
def get_route_name(res... |
def psd(tachogram_time, tachogram_data):
"""
-----
Brief
-----
Determination of the Power Spectral Density Function (Fourier Domain)
-----------
Description
-----------
The Power Spectral Density Function allows to perceive the behavior of a given signal in terms of its frequency.
... | -----
Brief
-----
Determination of the Power Spectral Density Function (Fourier Domain)
-----------
Description
-----------
The Power Spectral Density Function allows to perceive the behavior of a given signal in terms of its frequency.
This procedure costs the time resolution of the si... | Below is the the instruction that describes the task:
### Input:
-----
Brief
-----
Determination of the Power Spectral Density Function (Fourier Domain)
-----------
Description
-----------
The Power Spectral Density Function allows to perceive the behavior of a given signal in terms of ... |
def parsedeglat (latstr):
"""Parse a latitude formatted as sexagesimal degrees into an angle.
This function converts a textual representation of a latitude, measured in
degrees, into a floating point value measured in radians. The format of
*latstr* is very limited: it may not have leading or trailing ... | Parse a latitude formatted as sexagesimal degrees into an angle.
This function converts a textual representation of a latitude, measured in
degrees, into a floating point value measured in radians. The format of
*latstr* is very limited: it may not have leading or trailing whitespace,
and the component... | Below is the the instruction that describes the task:
### Input:
Parse a latitude formatted as sexagesimal degrees into an angle.
This function converts a textual representation of a latitude, measured in
degrees, into a floating point value measured in radians. The format of
*latstr* is very limited: ... |
def container_rename(name, newname, remote_addr=None,
cert=None, key=None, verify_cert=True):
'''
Rename a container
name :
Name of the container to Rename
newname :
The new name of the contianer
remote_addr :
An URL to a remote Server, you also have t... | Rename a container
name :
Name of the container to Rename
newname :
The new name of the contianer
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its a TCP Address!
Examples:
https://myserver.l... | Below is the the instruction that describes the task:
### Input:
Rename a container
name :
Name of the container to Rename
newname :
The new name of the contianer
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and... |
def next(self):
""" Next CapitainsCtsPassage (Interactive CapitainsCtsPassage)
"""
if self.nextId is not None:
return super(CapitainsCtsPassage, self).getTextualNode(subreference=self.nextId) | Next CapitainsCtsPassage (Interactive CapitainsCtsPassage) | Below is the the instruction that describes the task:
### Input:
Next CapitainsCtsPassage (Interactive CapitainsCtsPassage)
### Response:
def next(self):
""" Next CapitainsCtsPassage (Interactive CapitainsCtsPassage)
"""
if self.nextId is not None:
return super(CapitainsCtsPassa... |
def load_pos_model(lang="en", version="2"):
"""Return a part of speech tagger parameters for `lang` and of version `version`
Args:
lang (string): language code.
version (string): version of the parameters to be used.
"""
src_dir = "pos{}".format(version)
p = locate_resource(src_dir, lang)
fh = _ope... | Return a part of speech tagger parameters for `lang` and of version `version`
Args:
lang (string): language code.
version (string): version of the parameters to be used. | Below is the the instruction that describes the task:
### Input:
Return a part of speech tagger parameters for `lang` and of version `version`
Args:
lang (string): language code.
version (string): version of the parameters to be used.
### Response:
def load_pos_model(lang="en", version="2"):
"""Return... |
def set_visible_region(self, rectangles, count):
"""Suggests a new visible region to this frame buffer. This region
represents the area of the VM display which is a union of regions of
all top-level windows of the guest operating system running inside the
VM (if the Guest Additions for t... | Suggests a new visible region to this frame buffer. This region
represents the area of the VM display which is a union of regions of
all top-level windows of the guest operating system running inside the
VM (if the Guest Additions for this system support this
functionality). This informa... | Below is the the instruction that describes the task:
### Input:
Suggests a new visible region to this frame buffer. This region
represents the area of the VM display which is a union of regions of
all top-level windows of the guest operating system running inside the
VM (if the Guest Additi... |
def save_tc_to_nii(strCsvCnfg, lgcTest=False, lstRat=None, lgcMdlRsp=False,
strPathHrf=None, lgcSaveRam=False):
"""
Save empirical and fitted time courses to nii file format.
Parameters
----------
strCsvCnfg : str
Absolute file path of config file used for pRF fitting.
... | Save empirical and fitted time courses to nii file format.
Parameters
----------
strCsvCnfg : str
Absolute file path of config file used for pRF fitting.
lgcTest : boolean
Whether this is a test (pytest). If yes, absolute path of pyprf libary
will be prepended to config file pat... | Below is the the instruction that describes the task:
### Input:
Save empirical and fitted time courses to nii file format.
Parameters
----------
strCsvCnfg : str
Absolute file path of config file used for pRF fitting.
lgcTest : boolean
Whether this is a test (pytest). If yes, absol... |
def delete_alias(self, index, name, params=None):
"""
Delete specific alias.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_
:arg index: A comma-separated list of index names (supports wildcards);
use `_all` for all indices
:a... | Delete specific alias.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_
:arg index: A comma-separated list of index names (supports wildcards);
use `_all` for all indices
:arg name: A comma-separated list of aliases to delete (supports
... | Below is the the instruction that describes the task:
### Input:
Delete specific alias.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_
:arg index: A comma-separated list of index names (supports wildcards);
use `_all` for all indices
:ar... |
def send_response(self, body, set_content_type=True):
"""
Serialize and send ``body`` in the response.
:param dict body: the body to serialize
:param bool set_content_type: should the :http:header:`Content-Type`
header be set? Defaults to :data:`True`
"""
s... | Serialize and send ``body`` in the response.
:param dict body: the body to serialize
:param bool set_content_type: should the :http:header:`Content-Type`
header be set? Defaults to :data:`True` | Below is the the instruction that describes the task:
### Input:
Serialize and send ``body`` in the response.
:param dict body: the body to serialize
:param bool set_content_type: should the :http:header:`Content-Type`
header be set? Defaults to :data:`True`
### Response:
def send_res... |
def _check_keys(dictionary):
"""
checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries
"""
for key in dictionary:
if isinstance(dictionary[key], matlab.mio5_params.mat_struct):
dictionary[key] = _todict(dictionary[key])
... | checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries | Below is the the instruction that describes the task:
### Input:
checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries
### Response:
def _check_keys(dictionary):
"""
checks if entries in dictionary are mat-objects. If yes
todict is called to ... |
def is_duplicate_of(self, other):
"""Check if spectrum is duplicate of another."""
if super(Spectrum, self).is_duplicate_of(other):
return True
row_matches = 0
for ri, row in enumerate(self.get(self._KEYS.DATA, [])):
lambda1, flux1 = tuple(row[0:2])
if... | Check if spectrum is duplicate of another. | Below is the the instruction that describes the task:
### Input:
Check if spectrum is duplicate of another.
### Response:
def is_duplicate_of(self, other):
"""Check if spectrum is duplicate of another."""
if super(Spectrum, self).is_duplicate_of(other):
return True
row_matches =... |
def save(self, savefile):
"""Do the TTS API request and write result to file.
Args:
savefile (string): The path and file name to save the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
"""
with open(str(savefile), 'w... | Do the TTS API request and write result to file.
Args:
savefile (string): The path and file name to save the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request. | Below is the the instruction that describes the task:
### Input:
Do the TTS API request and write result to file.
Args:
savefile (string): The path and file name to save the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
### Response:
d... |
def _pick_state_im_name(state_name, im_name, use_full_path=False):
"""
If state_name or im_name is None, picks them interactively through Tk,
and then sets with or without the full path.
Parameters
----------
state_name : {string, None}
The name of the state. If None, selected t... | If state_name or im_name is None, picks them interactively through Tk,
and then sets with or without the full path.
Parameters
----------
state_name : {string, None}
The name of the state. If None, selected through Tk.
im_name : {string, None}
The name of the image. ... | Below is the the instruction that describes the task:
### Input:
If state_name or im_name is None, picks them interactively through Tk,
and then sets with or without the full path.
Parameters
----------
state_name : {string, None}
The name of the state. If None, selected through Tk.... |
def verify_ticket_signature(self, data, sig):
"""Verify ticket signature. """
try:
signature = base64.b64decode(sig)
except TypeError as e:
if hasattr(self, "debug"):
print("Exception in function base64.b64decode. File %s" % (__file__))
... | Verify ticket signature. | Below is the the instruction that describes the task:
### Input:
Verify ticket signature.
### Response:
def verify_ticket_signature(self, data, sig):
"""Verify ticket signature. """
try:
signature = base64.b64decode(sig)
except TypeError as e:
if hasattr(self, "debug... |
def new_connection(self):
"""Make a new connection."""
if not self.prepared: self.prepare()
con = sqlite3.connect(self.path, isolation_level=self.isolation)
con.row_factory = self.factory
if self.text_fact: con.text_factory = self.text_fact
return con | Make a new connection. | Below is the the instruction that describes the task:
### Input:
Make a new connection.
### Response:
def new_connection(self):
"""Make a new connection."""
if not self.prepared: self.prepare()
con = sqlite3.connect(self.path, isolation_level=self.isolation)
con.row_factory = self.f... |
def _affine_mult(c:FlowField,m:AffineMatrix)->FlowField:
"Multiply `c` by `m` - can adjust for rectangular shaped `c`."
if m is None: return c
size = c.flow.size()
h,w = c.size
m[0,1] *= h/w
m[1,0] *= w/h
c.flow = c.flow.view(-1,2)
c.flow = torch.addmm(m[:2,2], c.flow, m[:2,:2].t()).vie... | Multiply `c` by `m` - can adjust for rectangular shaped `c`. | Below is the the instruction that describes the task:
### Input:
Multiply `c` by `m` - can adjust for rectangular shaped `c`.
### Response:
def _affine_mult(c:FlowField,m:AffineMatrix)->FlowField:
"Multiply `c` by `m` - can adjust for rectangular shaped `c`."
if m is None: return c
size = c.flow.size()... |
def _session():
'''
Return the boto3 session to use for the KMS client.
If aws_kms:profile_name is set in the salt configuration, use that profile.
Otherwise, fall back on the default aws profile.
We use the boto3 profile system to avoid having to duplicate
individual boto3 configuration setti... | Return the boto3 session to use for the KMS client.
If aws_kms:profile_name is set in the salt configuration, use that profile.
Otherwise, fall back on the default aws profile.
We use the boto3 profile system to avoid having to duplicate
individual boto3 configuration settings in salt configuration. | Below is the the instruction that describes the task:
### Input:
Return the boto3 session to use for the KMS client.
If aws_kms:profile_name is set in the salt configuration, use that profile.
Otherwise, fall back on the default aws profile.
We use the boto3 profile system to avoid having to duplicate... |
def curl_couchdb(url, method='GET', base_url=BASE_URL, data=None):
'''
Launch a curl on CouchDB instance
'''
(username, password) = get_admin()
if username is None:
auth = None
else:
auth = (username, password)
if method == 'PUT':
req = requests.put('{}{}'.format... | Launch a curl on CouchDB instance | Below is the the instruction that describes the task:
### Input:
Launch a curl on CouchDB instance
### Response:
def curl_couchdb(url, method='GET', base_url=BASE_URL, data=None):
'''
Launch a curl on CouchDB instance
'''
(username, password) = get_admin()
if username is None:
auth ... |
def _infinite_iterator(self):
"""this iterator wraps the "_basic_iterator" when the configuration
specifies that the "number_of_submissions" is set to "forever".
Whenever the "_basic_iterator" is exhausted, it is called again to
restart the iteration. It is up to the implementation of t... | this iterator wraps the "_basic_iterator" when the configuration
specifies that the "number_of_submissions" is set to "forever".
Whenever the "_basic_iterator" is exhausted, it is called again to
restart the iteration. It is up to the implementation of the innermost
iterator to define w... | Below is the the instruction that describes the task:
### Input:
this iterator wraps the "_basic_iterator" when the configuration
specifies that the "number_of_submissions" is set to "forever".
Whenever the "_basic_iterator" is exhausted, it is called again to
restart the iteration. It is u... |
def binboolflip(item):
"""
Convert 0 or 1 to False or True (or vice versa).
The converter works as follows:
- 0 > False
- False > 0
- 1 > True
- True > 1
:type item: integer or boolean
:param item: The item to convert.
>>> binboolflip(0)
False
>>> binboolflip(False)
... | Convert 0 or 1 to False or True (or vice versa).
The converter works as follows:
- 0 > False
- False > 0
- 1 > True
- True > 1
:type item: integer or boolean
:param item: The item to convert.
>>> binboolflip(0)
False
>>> binboolflip(False)
0
>>> binboolflip(1)
Tr... | Below is the the instruction that describes the task:
### Input:
Convert 0 or 1 to False or True (or vice versa).
The converter works as follows:
- 0 > False
- False > 0
- 1 > True
- True > 1
:type item: integer or boolean
:param item: The item to convert.
>>> binboolflip(0)
F... |
def start_volume(name, force=False):
'''
Start a gluster volume
name
Volume name
force
Force the volume start even if the volume is started
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' glusterfs.start mycluster
'''
cmd = 'volu... | Start a gluster volume
name
Volume name
force
Force the volume start even if the volume is started
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' glusterfs.start mycluster | Below is the the instruction that describes the task:
### Input:
Start a gluster volume
name
Volume name
force
Force the volume start even if the volume is started
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' glusterfs.start mycluster
###... |
def _my_top_k(x, k):
"""GPU-compatible version of top-k that works for very small constant k.
Calls argmax repeatedly.
tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense,
seems not to be, so if we use tf.nn.top_k, then both the top_k and its
gradient go on cpu. Once this is not an issue,... | GPU-compatible version of top-k that works for very small constant k.
Calls argmax repeatedly.
tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense,
seems not to be, so if we use tf.nn.top_k, then both the top_k and its
gradient go on cpu. Once this is not an issue, this function becomes
o... | Below is the the instruction that describes the task:
### Input:
GPU-compatible version of top-k that works for very small constant k.
Calls argmax repeatedly.
tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense,
seems not to be, so if we use tf.nn.top_k, then both the top_k and its
grad... |
def shell(args):
" A helper command to be used for shell integration "
print
print "# Makesite integration "
print "# ==================== "
print "export MAKESITE_HOME=%s" % args.path
print "source %s" % op.join(settings.BASEDIR, 'shell.sh')
print | A helper command to be used for shell integration | Below is the the instruction that describes the task:
### Input:
A helper command to be used for shell integration
### Response:
def shell(args):
" A helper command to be used for shell integration "
print
print "# Makesite integration "
print "# ==================== "
print "export MAKESITE_HO... |
def get_label(self, label_name):
"""Return the user's label that has a given name.
:param label_name: The name to search for.
:type label_name: str
:return: A label that has a matching name or ``None`` if not found.
:rtype: :class:`pytodoist.todoist.Label`
>>> from pyto... | Return the user's label that has a given name.
:param label_name: The name to search for.
:type label_name: str
:return: A label that has a matching name or ``None`` if not found.
:rtype: :class:`pytodoist.todoist.Label`
>>> from pytodoist import todoist
>>> user = todo... | Below is the the instruction that describes the task:
### Input:
Return the user's label that has a given name.
:param label_name: The name to search for.
:type label_name: str
:return: A label that has a matching name or ``None`` if not found.
:rtype: :class:`pytodoist.todoist.Labe... |
def download(self, storagemodel:object, modeldefinition = None):
""" load blob from storage into StorageBlobModelInstance """
if (storagemodel.name is None):
# No content to download
raise AzureStorageWrapException(storagemodel, "StorageBlobModel does not contain content nor con... | load blob from storage into StorageBlobModelInstance | Below is the the instruction that describes the task:
### Input:
load blob from storage into StorageBlobModelInstance
### Response:
def download(self, storagemodel:object, modeldefinition = None):
""" load blob from storage into StorageBlobModelInstance """
if (storagemodel.name is None):
... |
def files_info(self, *, id: str, **kwargs) -> SlackResponse:
"""Gets information about a team file.
Args:
id (str): The file id. e.g. 'F1234467890'
"""
kwargs.update({"id": id})
return self.api_call("files.info", http_verb="GET", params=kwargs) | Gets information about a team file.
Args:
id (str): The file id. e.g. 'F1234467890' | Below is the the instruction that describes the task:
### Input:
Gets information about a team file.
Args:
id (str): The file id. e.g. 'F1234467890'
### Response:
def files_info(self, *, id: str, **kwargs) -> SlackResponse:
"""Gets information about a team file.
Args:
... |
def transform_language_code(code):
"""
Transform ISO language code (e.g. en-us) to the language name expected by SAPSF.
"""
if code is None:
return 'English'
components = code.split('-', 2)
language_code = components[0]
try:
country_code = components[1]
except IndexError... | Transform ISO language code (e.g. en-us) to the language name expected by SAPSF. | Below is the the instruction that describes the task:
### Input:
Transform ISO language code (e.g. en-us) to the language name expected by SAPSF.
### Response:
def transform_language_code(code):
"""
Transform ISO language code (e.g. en-us) to the language name expected by SAPSF.
"""
if code is None... |
def add_distinguished_name_list(list_name):
'''
Add a list of policy distinguished names.
list_name(str): The name of the specific policy distinguished name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList
'''
... | Add a list of policy distinguished names.
list_name(str): The name of the specific policy distinguished name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList | Below is the the instruction that describes the task:
### Input:
Add a list of policy distinguished names.
list_name(str): The name of the specific policy distinguished name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList
... |
def insert(self, key, value):
'''Adds a new key-value pair. Returns any discarded values.'''
# Add to history and catch expectorate
if len(self.history) == self.maxsize:
expectorate = self.history[0]
else:
expectorate = None
self.history.append((key, val... | Adds a new key-value pair. Returns any discarded values. | Below is the the instruction that describes the task:
### Input:
Adds a new key-value pair. Returns any discarded values.
### Response:
def insert(self, key, value):
'''Adds a new key-value pair. Returns any discarded values.'''
# Add to history and catch expectorate
if len(self.history) =... |
def absolute(self):
"""Calculate the absolute value element-wise.
Returns:
absolute (Timeseries):
Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2)
"""
return Timeseries(np.absolute(self), self.tspan, self.labels) | Calculate the absolute value element-wise.
Returns:
absolute (Timeseries):
Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2) | Below is the the instruction that describes the task:
### Input:
Calculate the absolute value element-wise.
Returns:
absolute (Timeseries):
Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2)
### Response:
def absolute(self):
"""Calculate the absolute value el... |
def setup(self):
"""
instantiates all report formats that have been added to this
reporter, and calls their setup methods.
"""
if self._formats:
# setup has been run already.
return
basedir = self.basedir
options = self.options
cr... | instantiates all report formats that have been added to this
reporter, and calls their setup methods. | Below is the the instruction that describes the task:
### Input:
instantiates all report formats that have been added to this
reporter, and calls their setup methods.
### Response:
def setup(self):
"""
instantiates all report formats that have been added to this
reporter, and calls ... |
def remove_extra_delims(expr, ldelim="(", rdelim=")"):
r"""
Remove unnecessary delimiters in mathematical expressions.
Delimiters (parenthesis, brackets, etc.) may be removed either because
there are multiple consecutive delimiters enclosing a single expressions or
because the delimiters are implie... | r"""
Remove unnecessary delimiters in mathematical expressions.
Delimiters (parenthesis, brackets, etc.) may be removed either because
there are multiple consecutive delimiters enclosing a single expressions or
because the delimiters are implied by operator precedence rules. Function
names must sta... | Below is the the instruction that describes the task:
### Input:
r"""
Remove unnecessary delimiters in mathematical expressions.
Delimiters (parenthesis, brackets, etc.) may be removed either because
there are multiple consecutive delimiters enclosing a single expressions or
because the delimiters ... |
def setPalette(self, palette):
"""
Sets the palette for this node to the inputed palette. If None is
provided, then the scene's palette will be used for this node.
:param palette | <XNodePalette> || None
"""
self._palette = XNodePalette(palette) if palette ... | Sets the palette for this node to the inputed palette. If None is
provided, then the scene's palette will be used for this node.
:param palette | <XNodePalette> || None | Below is the the instruction that describes the task:
### Input:
Sets the palette for this node to the inputed palette. If None is
provided, then the scene's palette will be used for this node.
:param palette | <XNodePalette> || None
### Response:
def setPalette(self, palette):
... |
def _unpack_batch_response(response):
"""Convert requests.Response -> [(headers, payload)].
Creates a generator of tuples of emulating the responses to
:meth:`requests.Session.request`.
:type response: :class:`requests.Response`
:param response: HTTP response / headers from a request.
"""
... | Convert requests.Response -> [(headers, payload)].
Creates a generator of tuples of emulating the responses to
:meth:`requests.Session.request`.
:type response: :class:`requests.Response`
:param response: HTTP response / headers from a request. | Below is the the instruction that describes the task:
### Input:
Convert requests.Response -> [(headers, payload)].
Creates a generator of tuples of emulating the responses to
:meth:`requests.Session.request`.
:type response: :class:`requests.Response`
:param response: HTTP response / headers from... |
def gen_rupture_getters(dstore, slc=slice(None),
concurrent_tasks=1, hdf5cache=None):
"""
:yields: RuptureGetters
"""
if dstore.parent:
dstore = dstore.parent
csm_info = dstore['csm_info']
trt_by_grp = csm_info.grp_by("trt")
samples = csm_info.get_samples_by_g... | :yields: RuptureGetters | Below is the the instruction that describes the task:
### Input:
:yields: RuptureGetters
### Response:
def gen_rupture_getters(dstore, slc=slice(None),
concurrent_tasks=1, hdf5cache=None):
"""
:yields: RuptureGetters
"""
if dstore.parent:
dstore = dstore.parent
c... |
def __make_http_query(self, params, topkey=''):
"""
Function to covert params into url encoded query string
:param dict params: Json string sent by Authy.
:param string topkey: params key
:return string: url encoded Query.
"""
if len(params) == 0:
ret... | Function to covert params into url encoded query string
:param dict params: Json string sent by Authy.
:param string topkey: params key
:return string: url encoded Query. | Below is the the instruction that describes the task:
### Input:
Function to covert params into url encoded query string
:param dict params: Json string sent by Authy.
:param string topkey: params key
:return string: url encoded Query.
### Response:
def __make_http_query(self, params, topk... |
def zero_nan(self, *cols):
"""
Converts zero values to nan values in selected columns
:param \*cols: names of the colums
:type \*cols: str, at least one
:example: ``ds.zero_nan("mycol1", "mycol2")``
"""
if len(cols) == 0:
self.warning("Can not nan ze... | Converts zero values to nan values in selected columns
:param \*cols: names of the colums
:type \*cols: str, at least one
:example: ``ds.zero_nan("mycol1", "mycol2")`` | Below is the the instruction that describes the task:
### Input:
Converts zero values to nan values in selected columns
:param \*cols: names of the colums
:type \*cols: str, at least one
:example: ``ds.zero_nan("mycol1", "mycol2")``
### Response:
def zero_nan(self, *cols):
"""
... |
def __calc_signed_volume(triangle):
""" Calculate signed volume of given triangle
:param list of list triangle:
:rtype float
"""
v321 = triangle[2][0] * triangle[1][1] * triangle[0][2]
v231 = triangle[1][0] * triangle[2][1] * triangle[0][2]
v312 = triangle[2][0] *... | Calculate signed volume of given triangle
:param list of list triangle:
:rtype float | Below is the the instruction that describes the task:
### Input:
Calculate signed volume of given triangle
:param list of list triangle:
:rtype float
### Response:
def __calc_signed_volume(triangle):
""" Calculate signed volume of given triangle
:param list of list triangle:
... |
def getSwapStats(self, dev):
"""Returns I/O stats for swap partition.
@param dev: Device name for swap partition.
@return: Dict of stats.
"""
if self._swapList is None:
self._initSwapInfo()
if dev in self._swapList:
return self.ge... | Returns I/O stats for swap partition.
@param dev: Device name for swap partition.
@return: Dict of stats. | Below is the the instruction that describes the task:
### Input:
Returns I/O stats for swap partition.
@param dev: Device name for swap partition.
@return: Dict of stats.
### Response:
def getSwapStats(self, dev):
"""Returns I/O stats for swap partition.
@param dev... |
def search(cls, search_string, values_of='', group=whoosh.qparser.OrGroup, match_substrings=True, limit=None):
"""Searches the fields for given search_string.
Returns the found records if 'values_of' is left empty,
else the values of the given columns.
:param search_string: The string t... | Searches the fields for given search_string.
Returns the found records if 'values_of' is left empty,
else the values of the given columns.
:param search_string: The string to search for.
:param values_of: If given, the method will not return the whole
records, ... | Below is the the instruction that describes the task:
### Input:
Searches the fields for given search_string.
Returns the found records if 'values_of' is left empty,
else the values of the given columns.
:param search_string: The string to search for.
:param values_of: If given, the... |
def store_mapping(self, path):
"""Store the current Id mappings into a TSV file."""
with open(path, "w") as writer:
for key, value in self.mapping.iteritems():
writer.write("{}\t{}\n".format(key, value)) | Store the current Id mappings into a TSV file. | Below is the the instruction that describes the task:
### Input:
Store the current Id mappings into a TSV file.
### Response:
def store_mapping(self, path):
"""Store the current Id mappings into a TSV file."""
with open(path, "w") as writer:
for key, value in self.mapping.iteritems():
... |
def delete_files_or_folders(self, request, files_queryset, folders_queryset):
"""
Action which deletes the selected files and/or folders.
This action first displays a confirmation page whichs shows all the
deleteable files and/or folders, or, if the user has no permission on
one... | Action which deletes the selected files and/or folders.
This action first displays a confirmation page whichs shows all the
deleteable files and/or folders, or, if the user has no permission on
one of the related childs (foreignkeys), a "permission denied" message.
Next, it deletes all... | Below is the the instruction that describes the task:
### Input:
Action which deletes the selected files and/or folders.
This action first displays a confirmation page whichs shows all the
deleteable files and/or folders, or, if the user has no permission on
one of the related childs (forei... |
def b64_encode(self):
"""
Generate a base64 encoded representation of this SPKI object.
:return: The base64 encoded string.
:rtype: :py:class:`bytes`
"""
encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
result = _ffi.string(encoded)
_lib.OPENSSL_free(e... | Generate a base64 encoded representation of this SPKI object.
:return: The base64 encoded string.
:rtype: :py:class:`bytes` | Below is the the instruction that describes the task:
### Input:
Generate a base64 encoded representation of this SPKI object.
:return: The base64 encoded string.
:rtype: :py:class:`bytes`
### Response:
def b64_encode(self):
"""
Generate a base64 encoded representation of this SPKI... |
def set_password(self, raw_password):
"""Calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` for the user.
If password is ``None``, calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_unusable_password`.
"""
if raw_password is None:
self.set_unusable_passwo... | Calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` for the user.
If password is ``None``, calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_unusable_password`. | Below is the the instruction that describes the task:
### Input:
Calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` for the user.
If password is ``None``, calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_unusable_password`.
### Response:
def set_password(self, raw_password):
... |
def enable_faulthandler(cls, signum=signal.SIGUSR1):
"""
Enable dumping thread stack traces when specified signals are received, similar to java's handling of SIGQUIT
Note: this must be called from the surviving process in case of daemonization.
Note that SIGQUIT does not work in all en... | Enable dumping thread stack traces when specified signals are received, similar to java's handling of SIGQUIT
Note: this must be called from the surviving process in case of daemonization.
Note that SIGQUIT does not work in all environments with a python process.
:param int|None signum: Signal... | Below is the the instruction that describes the task:
### Input:
Enable dumping thread stack traces when specified signals are received, similar to java's handling of SIGQUIT
Note: this must be called from the surviving process in case of daemonization.
Note that SIGQUIT does not work in all enviro... |
def def_alignment(self, year):
"""Returns the name of the defensive alignment the team ran in the
given year.
:year: Int representing the season year.
:returns: A string representing the defensive alignment.
"""
scheme_text = self._year_info_pq(year, 'Defensive Alignment... | Returns the name of the defensive alignment the team ran in the
given year.
:year: Int representing the season year.
:returns: A string representing the defensive alignment. | Below is the the instruction that describes the task:
### Input:
Returns the name of the defensive alignment the team ran in the
given year.
:year: Int representing the season year.
:returns: A string representing the defensive alignment.
### Response:
def def_alignment(self, year):
... |
def _inverse_lower_triangular(M):
"""
Take inverse of lower triangular (e.g. Cholesky) matrix. This function
broadcasts over the first index.
:param M: Tensor with lower triangular structure of shape DxNxN
:return: The inverse of the Cholesky decomposition. Same shape as input.
"""
if M.get... | Take inverse of lower triangular (e.g. Cholesky) matrix. This function
broadcasts over the first index.
:param M: Tensor with lower triangular structure of shape DxNxN
:return: The inverse of the Cholesky decomposition. Same shape as input. | Below is the the instruction that describes the task:
### Input:
Take inverse of lower triangular (e.g. Cholesky) matrix. This function
broadcasts over the first index.
:param M: Tensor with lower triangular structure of shape DxNxN
:return: The inverse of the Cholesky decomposition. Same shape as inpu... |
def extend(self, collection):
"""Merges collections. Ensure uniqueness of ids"""
l_ids = set([a.Id for a in self])
for acces in collection:
if not acces.Id in l_ids:
list.append(self,acces)
info = collection.get_info(Id=acces.Id)
if inf... | Merges collections. Ensure uniqueness of ids | Below is the the instruction that describes the task:
### Input:
Merges collections. Ensure uniqueness of ids
### Response:
def extend(self, collection):
"""Merges collections. Ensure uniqueness of ids"""
l_ids = set([a.Id for a in self])
for acces in collection:
if not acces.Id... |
def draw_interface(objects, callback, callback_text):
"""
Draws a ncurses interface. Based on the given object list, every object should have a "string" key, this is whats displayed on the screen, callback is called with the selected object.
Rest of the code is modified from:
https://stackov... | Draws a ncurses interface. Based on the given object list, every object should have a "string" key, this is whats displayed on the screen, callback is called with the selected object.
Rest of the code is modified from:
https://stackoverflow.com/a/30834868 | Below is the the instruction that describes the task:
### Input:
Draws a ncurses interface. Based on the given object list, every object should have a "string" key, this is whats displayed on the screen, callback is called with the selected object.
Rest of the code is modified from:
https://stackove... |
def create_user(**data):
"""Creates user with encrypted password"""
if 'username' not in data or 'password' not in data:
raise ValueError('username and password are required.')
# Hash the user password
data['password'] = generate_password_hash(
data.pop('password'),
method='pbkd... | Creates user with encrypted password | Below is the the instruction that describes the task:
### Input:
Creates user with encrypted password
### Response:
def create_user(**data):
"""Creates user with encrypted password"""
if 'username' not in data or 'password' not in data:
raise ValueError('username and password are required.')
#... |
def get_context(self, parent_context, data):
"""
Wrap the context data in a :class:`~django.template.Context` object.
:param parent_context: The context of the parent template.
:type parent_context: :class:`~django.template.Context`
:param data: The result from :func:`get_contex... | Wrap the context data in a :class:`~django.template.Context` object.
:param parent_context: The context of the parent template.
:type parent_context: :class:`~django.template.Context`
:param data: The result from :func:`get_context_data`
:type data: dict
:return: Context data.
... | Below is the the instruction that describes the task:
### Input:
Wrap the context data in a :class:`~django.template.Context` object.
:param parent_context: The context of the parent template.
:type parent_context: :class:`~django.template.Context`
:param data: The result from :func:`get_co... |
def stop_func_accept_retry_state(stop_func):
"""Wrap "stop" function to accept "retry_state" parameter."""
if not six.callable(stop_func):
return stop_func
if func_takes_retry_state(stop_func):
return stop_func
@_utils.wraps(stop_func)
def wrapped_stop_func(retry_state):
wa... | Wrap "stop" function to accept "retry_state" parameter. | Below is the the instruction that describes the task:
### Input:
Wrap "stop" function to accept "retry_state" parameter.
### Response:
def stop_func_accept_retry_state(stop_func):
"""Wrap "stop" function to accept "retry_state" parameter."""
if not six.callable(stop_func):
return stop_func
if ... |
def delete(self, url):
"""
To make a DELETE request to Falkonry API server
:param url: string
"""
response = requests.delete(
self.host + url,
headers={
'Authorization': 'Bearer ' + self.token,
'x-falkonry-source':self.sourceHea... | To make a DELETE request to Falkonry API server
:param url: string | Below is the the instruction that describes the task:
### Input:
To make a DELETE request to Falkonry API server
:param url: string
### Response:
def delete(self, url):
"""
To make a DELETE request to Falkonry API server
:param url: string
"""
response = requests.del... |
def _nsplit(self):
"""
Split `self` at the north pole, which is the same as in signed arithmetic.
:return: A list of split StridedIntervals
"""
north_pole_left = self.max_int(self.bits - 1) # 01111...1
north_pole_right = 2 ** (self.bits - 1) # 1000...0
# Is `se... | Split `self` at the north pole, which is the same as in signed arithmetic.
:return: A list of split StridedIntervals | Below is the the instruction that describes the task:
### Input:
Split `self` at the north pole, which is the same as in signed arithmetic.
:return: A list of split StridedIntervals
### Response:
def _nsplit(self):
"""
Split `self` at the north pole, which is the same as in signed arithmet... |
def show_progress(self, n, total_runs):
"""Displays a progressbar"""
if self.report_progress:
percentage, logger_name, log_level = self.report_progress
if logger_name == 'print':
logger = 'print'
else:
logger = logging.getLogger(logger_... | Displays a progressbar | Below is the the instruction that describes the task:
### Input:
Displays a progressbar
### Response:
def show_progress(self, n, total_runs):
"""Displays a progressbar"""
if self.report_progress:
percentage, logger_name, log_level = self.report_progress
if logger_name == 'pr... |
def getAnalysisRequestsBrains(self, **kwargs):
"""Return all the Analysis Requests brains linked to the Batch
kargs are passed directly to the catalog.
"""
kwargs['getBatchUID'] = self.UID()
catalog = getToolByName(self, CATALOG_ANALYSIS_REQUEST_LISTING)
brains = catalog(... | Return all the Analysis Requests brains linked to the Batch
kargs are passed directly to the catalog. | Below is the the instruction that describes the task:
### Input:
Return all the Analysis Requests brains linked to the Batch
kargs are passed directly to the catalog.
### Response:
def getAnalysisRequestsBrains(self, **kwargs):
"""Return all the Analysis Requests brains linked to the Batch
... |
def format_numeric_result(analysis, result, decimalmark='.', sciformat=1):
"""
Returns the formatted number part of a results value. This is
responsible for deciding the precision, and notation of numeric
values in accordance to the uncertainty. If a non-numeric
result value is given, the value wil... | Returns the formatted number part of a results value. This is
responsible for deciding the precision, and notation of numeric
values in accordance to the uncertainty. If a non-numeric
result value is given, the value will be returned unchanged.
The following rules apply:
If the "Calculate precisi... | Below is the the instruction that describes the task:
### Input:
Returns the formatted number part of a results value. This is
responsible for deciding the precision, and notation of numeric
values in accordance to the uncertainty. If a non-numeric
result value is given, the value will be returned unch... |
def sync(self, hooks=True, async_hooks=True):
"""Synchronize user repositories.
:param bool hooks: True for syncing hooks.
:param bool async_hooks: True for sending of an asynchronous task to
sync hooks.
.. note::
Syncing happens from GitHu... | Synchronize user repositories.
:param bool hooks: True for syncing hooks.
:param bool async_hooks: True for sending of an asynchronous task to
sync hooks.
.. note::
Syncing happens from GitHub's direction only. This means that we
consid... | Below is the the instruction that describes the task:
### Input:
Synchronize user repositories.
:param bool hooks: True for syncing hooks.
:param bool async_hooks: True for sending of an asynchronous task to
sync hooks.
.. note::
Syncing happen... |
def transfer(ctx, _to='address', _value='uint256', returns=STATUS):
""" Standardized Contract API:
function transfer(address _to, uint256 _value) returns (bool _success)
"""
log.DEV('In Fungible.transfer')
if ctx.accounts[ctx.msg_sender] >= _value:
ctx.accounts[ctx.ms... | Standardized Contract API:
function transfer(address _to, uint256 _value) returns (bool _success) | Below is the the instruction that describes the task:
### Input:
Standardized Contract API:
function transfer(address _to, uint256 _value) returns (bool _success)
### Response:
def transfer(ctx, _to='address', _value='uint256', returns=STATUS):
""" Standardized Contract API:
function transf... |
def has_unchecked_field(self, locator, **kwargs):
"""
Checks if the page or current node has a radio button or checkbox with the given label,
value, or id, that is currently unchecked.
Args:
locator (str): The label, name, or id of an unchecked field.
**kwargs: A... | Checks if the page or current node has a radio button or checkbox with the given label,
value, or id, that is currently unchecked.
Args:
locator (str): The label, name, or id of an unchecked field.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Return... | Below is the the instruction that describes the task:
### Input:
Checks if the page or current node has a radio button or checkbox with the given label,
value, or id, that is currently unchecked.
Args:
locator (str): The label, name, or id of an unchecked field.
**kwargs: Ar... |
def variance_inflation_factors(df):
'''
Computes the variance inflation factor (VIF) for each column in the df.
Returns a pandas Series of VIFs
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
corr = np.corrcoef(df, rowvar=0)
corr_inv = np.linalg.inv(corr)
vifs ... | Computes the variance inflation factor (VIF) for each column in the df.
Returns a pandas Series of VIFs
Args:
df: pandas DataFrame with columns to run diagnostics on | Below is the the instruction that describes the task:
### Input:
Computes the variance inflation factor (VIF) for each column in the df.
Returns a pandas Series of VIFs
Args:
df: pandas DataFrame with columns to run diagnostics on
### Response:
def variance_inflation_factors(df):
'''
Compu... |
def _ParseEntryArrayObject(self, file_object, file_offset):
"""Parses an entry array object.
Args:
file_object (dfvfs.FileIO): a file-like object.
file_offset (int): offset of the entry array object relative to the start
of the file-like object.
Returns:
systemd_journal_entry_a... | Parses an entry array object.
Args:
file_object (dfvfs.FileIO): a file-like object.
file_offset (int): offset of the entry array object relative to the start
of the file-like object.
Returns:
systemd_journal_entry_array_object: entry array object.
Raises:
ParseError: if ... | Below is the the instruction that describes the task:
### Input:
Parses an entry array object.
Args:
file_object (dfvfs.FileIO): a file-like object.
file_offset (int): offset of the entry array object relative to the start
of the file-like object.
Returns:
systemd_journal_entry... |
def weighted_n(self):
"""float count of returned rows adjusted for weighting."""
if not self.is_weighted:
return float(self.unweighted_n)
return float(sum(self._cube_dict["result"]["measures"]["count"]["data"])) | float count of returned rows adjusted for weighting. | Below is the the instruction that describes the task:
### Input:
float count of returned rows adjusted for weighting.
### Response:
def weighted_n(self):
"""float count of returned rows adjusted for weighting."""
if not self.is_weighted:
return float(self.unweighted_n)
return fl... |
def get_execution_info(self, driver_id, function_descriptor):
"""Get the FunctionExecutionInfo of a remote function.
Args:
driver_id: ID of the driver that the function belongs to.
function_descriptor: The FunctionDescriptor of the function to get.
Returns:
... | Get the FunctionExecutionInfo of a remote function.
Args:
driver_id: ID of the driver that the function belongs to.
function_descriptor: The FunctionDescriptor of the function to get.
Returns:
A FunctionExecutionInfo object. | Below is the the instruction that describes the task:
### Input:
Get the FunctionExecutionInfo of a remote function.
Args:
driver_id: ID of the driver that the function belongs to.
function_descriptor: The FunctionDescriptor of the function to get.
Returns:
A Fu... |
def start_replication(mysql_settings,
binlog_pos_memory=(None, 2),
**kwargs):
""" Start replication on server specified by *mysql_settings*
Args:
mysql_settings (dict): mysql settings that is used to connect to
mysql via pymys... | Start replication on server specified by *mysql_settings*
Args:
mysql_settings (dict): mysql settings that is used to connect to
mysql via pymysql
binlog_pos_memory (_bpm.BaseBinlogPosMemory):
Binlog Position Memory, it should be an instance of subclass ... | Below is the the instruction that describes the task:
### Input:
Start replication on server specified by *mysql_settings*
Args:
mysql_settings (dict): mysql settings that is used to connect to
mysql via pymysql
binlog_pos_memory (_bpm.BaseBinlogPosMemory):
... |
def find_file_in_zip(zip_file):
'''Returns the twb/tds file from a Tableau packaged file format. Packaged
files can contain cache entries which are also valid XML, so only look for
files with a .tds or .twb extension.
'''
candidate_files = filter(lambda x: x.split('.')[-1] in ('twb', 'tds'),
... | Returns the twb/tds file from a Tableau packaged file format. Packaged
files can contain cache entries which are also valid XML, so only look for
files with a .tds or .twb extension. | Below is the the instruction that describes the task:
### Input:
Returns the twb/tds file from a Tableau packaged file format. Packaged
files can contain cache entries which are also valid XML, so only look for
files with a .tds or .twb extension.
### Response:
def find_file_in_zip(zip_file):
'''Return... |
def _configure_interrupt(self, function_name, timeout, container, is_debugging):
"""
When a Lambda function is executing, we setup certain interrupt handlers to stop the execution.
Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though,
... | When a Lambda function is executing, we setup certain interrupt handlers to stop the execution.
Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though,
we don't enforce a timeout. But we setup a SIGINT interrupt to catch Ctrl+C and terminate the c... | Below is the the instruction that describes the task:
### Input:
When a Lambda function is executing, we setup certain interrupt handlers to stop the execution.
Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though,
we don't enforce a timeout... |
def fCPHASEs(self):
"""
Get a dictionary of CPHASE fidelities (normalized to unity) from the specs,
keyed by targets (qubit-qubit pairs).
:return: A dictionary of CPHASE fidelities, normalized to unity.
:rtype: Dict[tuple(int, int), float]
"""
return {tuple(es.ta... | Get a dictionary of CPHASE fidelities (normalized to unity) from the specs,
keyed by targets (qubit-qubit pairs).
:return: A dictionary of CPHASE fidelities, normalized to unity.
:rtype: Dict[tuple(int, int), float] | Below is the the instruction that describes the task:
### Input:
Get a dictionary of CPHASE fidelities (normalized to unity) from the specs,
keyed by targets (qubit-qubit pairs).
:return: A dictionary of CPHASE fidelities, normalized to unity.
:rtype: Dict[tuple(int, int), float]
### Respon... |
def error_codes(self):
"""ThreatConnect error codes."""
if self._error_codes is None:
from .tcex_error_codes import TcExErrorCodes
self._error_codes = TcExErrorCodes()
return self._error_codes | ThreatConnect error codes. | Below is the the instruction that describes the task:
### Input:
ThreatConnect error codes.
### Response:
def error_codes(self):
"""ThreatConnect error codes."""
if self._error_codes is None:
from .tcex_error_codes import TcExErrorCodes
self._error_codes = TcExErrorCodes()
... |
def convert_tuple_type(cls, name, value):
"""
Converts a tuple to RECORD that contains n fields, each will be converted
to its corresponding data type in bq and will be named 'field_<index>', where
index is determined by the order of the tuple elements defined in cassandra.
"""
... | Converts a tuple to RECORD that contains n fields, each will be converted
to its corresponding data type in bq and will be named 'field_<index>', where
index is determined by the order of the tuple elements defined in cassandra. | Below is the the instruction that describes the task:
### Input:
Converts a tuple to RECORD that contains n fields, each will be converted
to its corresponding data type in bq and will be named 'field_<index>', where
index is determined by the order of the tuple elements defined in cassandra.
### Re... |
def _check_vmware_player_requirements(self, player_version):
"""
Check minimum requirements to use VMware Player.
VIX 1.13 was the release for Player 6.
VIX 1.14 was the release for Player 7.
VIX 1.15 was the release for Workstation Player 12.
:param player_version: VMw... | Check minimum requirements to use VMware Player.
VIX 1.13 was the release for Player 6.
VIX 1.14 was the release for Player 7.
VIX 1.15 was the release for Workstation Player 12.
:param player_version: VMware Player major version. | Below is the the instruction that describes the task:
### Input:
Check minimum requirements to use VMware Player.
VIX 1.13 was the release for Player 6.
VIX 1.14 was the release for Player 7.
VIX 1.15 was the release for Workstation Player 12.
:param player_version: VMware Player m... |
def post(self, request, *args, **kwargs):
""" Handles POST requests. """
return self.disapprove(request, *args, **kwargs) | Handles POST requests. | Below is the the instruction that describes the task:
### Input:
Handles POST requests.
### Response:
def post(self, request, *args, **kwargs):
""" Handles POST requests. """
return self.disapprove(request, *args, **kwargs) |
def rst(filename):
'''
Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- travis ci build badge
'''
content = codecs.open(filename, encoding='utf-8').read()
for regex, replacement in PYPI_RST_FILTERS:
content = re.sub(regex, replace... | Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- travis ci build badge | Below is the the instruction that describes the task:
### Input:
Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- travis ci build badge
### Response:
def rst(filename):
'''
Load rst file and sanitize it for PyPI.
Remove unsupported github ta... |
async def _get_smallest_env(self):
"""Get address of the slave environment manager with the smallest
number of agents.
"""
async def slave_task(mgr_addr):
r_manager = await self.env.connect(mgr_addr, timeout=TIMEOUT)
ret = await r_manager.get_agents(addr=True)
... | Get address of the slave environment manager with the smallest
number of agents. | Below is the the instruction that describes the task:
### Input:
Get address of the slave environment manager with the smallest
number of agents.
### Response:
async def _get_smallest_env(self):
"""Get address of the slave environment manager with the smallest
number of agents.
"""
... |
def main():
"""Parser the command line and run the validator."""
parser = argparse.ArgumentParser(
description="[v" + __version__ + "] " + __doc__,
prog="w3c_validator",
)
parser.add_argument(
"--log",
default="INFO",
help=("log level: DEBUG, INFO or INFO "
... | Parser the command line and run the validator. | Below is the the instruction that describes the task:
### Input:
Parser the command line and run the validator.
### Response:
def main():
"""Parser the command line and run the validator."""
parser = argparse.ArgumentParser(
description="[v" + __version__ + "] " + __doc__,
prog="w3c_validat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.