code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _upload_in_splits( self, destination_folder_id, source_path, preflight_check, verbose = True, chunked_upload_threads = 5 ):
'''
Since Box has a maximum file size limit (15 GB at time of writing),
we need to split files larger than this into smaller parts, and chunk upload each part
'... | Since Box has a maximum file size limit (15 GB at time of writing),
we need to split files larger than this into smaller parts, and chunk upload each part | Below is the the instruction that describes the task:
### Input:
Since Box has a maximum file size limit (15 GB at time of writing),
we need to split files larger than this into smaller parts, and chunk upload each part
### Response:
def _upload_in_splits( self, destination_folder_id, source_path, prefligh... |
def _validate_row(row, sep=',', required_length=None):
'''validate_row will ensure that a row has the proper length, and is
not empty and cleaned of extra spaces.
Parameters
==========
row: a single row, not yet parsed.
Returns a valid row, or None if not valid
'''
if ... | validate_row will ensure that a row has the proper length, and is
not empty and cleaned of extra spaces.
Parameters
==========
row: a single row, not yet parsed.
Returns a valid row, or None if not valid | Below is the the instruction that describes the task:
### Input:
validate_row will ensure that a row has the proper length, and is
not empty and cleaned of extra spaces.
Parameters
==========
row: a single row, not yet parsed.
Returns a valid row, or None if not valid
### Respo... |
def putlogo(figure=None):
"""Puts the CREDO logo at the bottom right of the current figure (or
the figure given by the ``figure`` argument if supplied).
"""
ip = get_ipython()
if figure is None:
figure=plt.gcf()
curraxis= figure.gca()
logoaxis = figure.add_axes([0.89, 0.01, 0.1, 0.1]... | Puts the CREDO logo at the bottom right of the current figure (or
the figure given by the ``figure`` argument if supplied). | Below is the the instruction that describes the task:
### Input:
Puts the CREDO logo at the bottom right of the current figure (or
the figure given by the ``figure`` argument if supplied).
### Response:
def putlogo(figure=None):
"""Puts the CREDO logo at the bottom right of the current figure (or
the f... |
def get_interface_detail_output_interface_ifHCOutOctets(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_interface_detail_output_interface_ifHCOutOctets(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detai... |
def record(self):
# type: () -> bytes
'''
A method to generate the string representing this UDF NSR Volume
Structure.
Parameters:
None.
Returns:
A string representing this UDF BEA Volume Strucutre.
'''
if not self._initialized:
... | A method to generate the string representing this UDF NSR Volume
Structure.
Parameters:
None.
Returns:
A string representing this UDF BEA Volume Strucutre. | Below is the the instruction that describes the task:
### Input:
A method to generate the string representing this UDF NSR Volume
Structure.
Parameters:
None.
Returns:
A string representing this UDF BEA Volume Strucutre.
### Response:
def record(self):
# type: () ... |
def logistic(x, x0, k, L):
'''Logistic function.
See, e.g `Wikipedia <https://en.wikipedia.org/wiki/Logistic_function>`_.
:param x: point in x-axis
:type x: float or numpy.ndarray
:param float x0: sigmoid's midpoint
:param float k: steepness of the curve
:param float L: maximum value of th... | Logistic function.
See, e.g `Wikipedia <https://en.wikipedia.org/wiki/Logistic_function>`_.
:param x: point in x-axis
:type x: float or numpy.ndarray
:param float x0: sigmoid's midpoint
:param float k: steepness of the curve
:param float L: maximum value of the curve
:returns: function's v... | Below is the the instruction that describes the task:
### Input:
Logistic function.
See, e.g `Wikipedia <https://en.wikipedia.org/wiki/Logistic_function>`_.
:param x: point in x-axis
:type x: float or numpy.ndarray
:param float x0: sigmoid's midpoint
:param float k: steepness of the curve
... |
def plotER(self,*args,**kwargs):
"""
NAME:
plotER
PURPOSE:
plot ER(.) along the orbit
INPUT:
bovy_plot.bovy_plot inputs
OUTPUT:
figure to output device
HISTORY:
2014-06-16 - Written - Bovy (IAS)
"""
if... | NAME:
plotER
PURPOSE:
plot ER(.) along the orbit
INPUT:
bovy_plot.bovy_plot inputs
OUTPUT:
figure to output device
HISTORY:
2014-06-16 - Written - Bovy (IAS) | Below is the the instruction that describes the task:
### Input:
NAME:
plotER
PURPOSE:
plot ER(.) along the orbit
INPUT:
bovy_plot.bovy_plot inputs
OUTPUT:
figure to output device
HISTORY:
2014-06-16 - Written - Bovy (IAS)
### Re... |
def default_provenance():
"""The provenance for the default values.
:return: default provenance.
:rtype: str
"""
field = TextParameter()
field.name = tr('Provenance')
field.description = tr('The provenance of minimum needs')
field.value = 'The minimum needs are based on BNPB Perka 7/200... | The provenance for the default values.
:return: default provenance.
:rtype: str | Below is the the instruction that describes the task:
### Input:
The provenance for the default values.
:return: default provenance.
:rtype: str
### Response:
def default_provenance():
"""The provenance for the default values.
:return: default provenance.
:rtype: str
"""
field = TextP... |
def prepare_classpath():
"""
Ensures that certain subfolders of AIRFLOW_HOME are on the classpath
"""
if DAGS_FOLDER not in sys.path:
sys.path.append(DAGS_FOLDER)
# Add ./config/ for loading custom log parsers etc, or
# airflow_local_settings etc.
config_path = os.path.join(AIRFLOW... | Ensures that certain subfolders of AIRFLOW_HOME are on the classpath | Below is the the instruction that describes the task:
### Input:
Ensures that certain subfolders of AIRFLOW_HOME are on the classpath
### Response:
def prepare_classpath():
"""
Ensures that certain subfolders of AIRFLOW_HOME are on the classpath
"""
if DAGS_FOLDER not in sys.path:
sys.path... |
def _init_trace_logging(self, app):
"""
Sets up trace logging unless ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` is
set in the Flask config.
Args:
app (flask.Flask). the Flask application for which to initialize the extension.
"""
enabled = not app.config.get(CONF_... | Sets up trace logging unless ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` is
set in the Flask config.
Args:
app (flask.Flask). the Flask application for which to initialize the extension. | Below is the the instruction that describes the task:
### Input:
Sets up trace logging unless ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` is
set in the Flask config.
Args:
app (flask.Flask). the Flask application for which to initialize the extension.
### Response:
def _init_trace_logging(se... |
def collect_files(self):
"""
Return collected files links
:rtype: list[static_bundle.files.StaticFileResult]
"""
self.files = []
for bundle in self.bundles:
bundle.init_build(self, self.builder)
bundle_files = bundle.prepare()
self.fil... | Return collected files links
:rtype: list[static_bundle.files.StaticFileResult] | Below is the the instruction that describes the task:
### Input:
Return collected files links
:rtype: list[static_bundle.files.StaticFileResult]
### Response:
def collect_files(self):
"""
Return collected files links
:rtype: list[static_bundle.files.StaticFileResult]
"""
... |
def get_user_pubkeys(users):
'''
Retrieve a set of public keys from GitHub for the specified list of users.
Expects input in list format. Optionally, a value in the list may be a dict
whose value is a list of key IDs to be returned. If this is not done, then
all keys will be returned.
Some exam... | Retrieve a set of public keys from GitHub for the specified list of users.
Expects input in list format. Optionally, a value in the list may be a dict
whose value is a list of key IDs to be returned. If this is not done, then
all keys will be returned.
Some example data structures that coupld be passed... | Below is the the instruction that describes the task:
### Input:
Retrieve a set of public keys from GitHub for the specified list of users.
Expects input in list format. Optionally, a value in the list may be a dict
whose value is a list of key IDs to be returned. If this is not done, then
all keys will... |
def taskfile_created_data(file_, role):
"""Return the data for created date
:param file_: the file that holds the data
:type file_: :class:`jukeboxcore.djadapter.models.File`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the created date
:rtype: depending... | Return the data for created date
:param file_: the file that holds the data
:type file_: :class:`jukeboxcore.djadapter.models.File`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the created date
:rtype: depending on role
:raises: None | Below is the the instruction that describes the task:
### Input:
Return the data for created date
:param file_: the file that holds the data
:type file_: :class:`jukeboxcore.djadapter.models.File`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the created date... |
def prepare(self, engine, mode, items) -> None:
"""
Create a unique transaction id and dumps the items into a cached request object.
"""
self.tx_id = str(uuid.uuid4()).replace("-", "")
self.engine = engine
self.mode = mode
self.items = items
self._prepare_... | Create a unique transaction id and dumps the items into a cached request object. | Below is the the instruction that describes the task:
### Input:
Create a unique transaction id and dumps the items into a cached request object.
### Response:
def prepare(self, engine, mode, items) -> None:
"""
Create a unique transaction id and dumps the items into a cached request object.
... |
def refreshButton(self):
"""
Refreshes the button for this toolbar.
"""
collapsed = self.isCollapsed()
btn = self._collapseButton
if not btn:
return
btn.setMaximumSize(MAX_SIZE, MAX_SIZE)
# set up a vertical... | Refreshes the button for this toolbar. | Below is the the instruction that describes the task:
### Input:
Refreshes the button for this toolbar.
### Response:
def refreshButton(self):
"""
Refreshes the button for this toolbar.
"""
collapsed = self.isCollapsed()
btn = self._collapseButton
... |
def __CheckAndUnifyQueryFormat(self, query_body):
"""Checks and unifies the format of the query body.
:raises TypeError: If query_body is not of expected type (depending on the query compatibility mode).
:raises ValueError: If query_body is a dict but doesn\'t have valid query text.
:ra... | Checks and unifies the format of the query body.
:raises TypeError: If query_body is not of expected type (depending on the query compatibility mode).
:raises ValueError: If query_body is a dict but doesn\'t have valid query text.
:raises SystemError: If the query compatibility mode is undefine... | Below is the the instruction that describes the task:
### Input:
Checks and unifies the format of the query body.
:raises TypeError: If query_body is not of expected type (depending on the query compatibility mode).
:raises ValueError: If query_body is a dict but doesn\'t have valid query text.
... |
def process_cmap(cmap, ncolors=None, provider=None, categorical=False):
"""
Convert valid colormap specifications to a list of colors.
"""
providers_checked="matplotlib, bokeh, or colorcet" if provider is None else provider
if isinstance(cmap, Cycle):
palette = [rgb2hex(c) if isinstance(c, ... | Convert valid colormap specifications to a list of colors. | Below is the the instruction that describes the task:
### Input:
Convert valid colormap specifications to a list of colors.
### Response:
def process_cmap(cmap, ncolors=None, provider=None, categorical=False):
"""
Convert valid colormap specifications to a list of colors.
"""
providers_checked="mat... |
def generate_dynamodb_tables():
"""Create the Blockade DynamoDB tables."""
logger.debug("[#] Setting up DynamoDB tables")
client = boto3.client('dynamodb', region_name=PRIMARY_REGION)
existing_tables = client.list_tables()['TableNames']
responses = list()
for label in DYNAMODB_TABLES:
i... | Create the Blockade DynamoDB tables. | Below is the the instruction that describes the task:
### Input:
Create the Blockade DynamoDB tables.
### Response:
def generate_dynamodb_tables():
"""Create the Blockade DynamoDB tables."""
logger.debug("[#] Setting up DynamoDB tables")
client = boto3.client('dynamodb', region_name=PRIMARY_REGION)
... |
def isStochastic(matrix):
"""Check that ``matrix`` is row stochastic.
Returns
=======
is_stochastic : bool
``True`` if ``matrix`` is row stochastic, ``False`` otherwise.
"""
try:
absdiff = (_np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0])))
except AttributeError:
... | Check that ``matrix`` is row stochastic.
Returns
=======
is_stochastic : bool
``True`` if ``matrix`` is row stochastic, ``False`` otherwise. | Below is the the instruction that describes the task:
### Input:
Check that ``matrix`` is row stochastic.
Returns
=======
is_stochastic : bool
``True`` if ``matrix`` is row stochastic, ``False`` otherwise.
### Response:
def isStochastic(matrix):
"""Check that ``matrix`` is row stochastic.
... |
def ObtenerTablaParametros(self, tipo_recurso, sep="||"):
"Devuelve un array de elementos que tienen id y descripción"
if not self.client:
self.Conectar()
self.response = self.client("parametros", "v1", tipo_recurso)
result = json.loads(self.response)
ret = {}... | Devuelve un array de elementos que tienen id y descripción | Below is the the instruction that describes the task:
### Input:
Devuelve un array de elementos que tienen id y descripción
### Response:
def ObtenerTablaParametros(self, tipo_recurso, sep="||"):
"Devuelve un array de elementos que tienen id y descripción"
if not self.client:
se... |
def reload_instance(self, instance_id,
post_uri=None,
ssh_keys=None,
image_id=None):
"""Perform an OS reload of an instance.
:param integer instance_id: the instance ID to reload
:param string post_url: The URI of the post-... | Perform an OS reload of an instance.
:param integer instance_id: the instance ID to reload
:param string post_url: The URI of the post-install script to run
after reload
:param list ssh_keys: The SSH keys to add to the root user
:param int image_id: The G... | Below is the the instruction that describes the task:
### Input:
Perform an OS reload of an instance.
:param integer instance_id: the instance ID to reload
:param string post_url: The URI of the post-install script to run
after reload
:param list ssh_keys: Th... |
def serialize(self, value):
"""Takes a datetime object and returns a string"""
if isinstance(value, str):
return value
return value.strftime(DATETIME_FORMAT) | Takes a datetime object and returns a string | Below is the the instruction that describes the task:
### Input:
Takes a datetime object and returns a string
### Response:
def serialize(self, value):
"""Takes a datetime object and returns a string"""
if isinstance(value, str):
return value
return value.strftime(DATETIME_FORMA... |
def gym_space_spec(gym_space):
"""Returns a reading spec of a gym space.
NOTE: Only implemented currently for Box and Discrete.
Args:
gym_space: instance of gym.spaces whose spec we want.
Returns:
Reading spec for that space.
Raises:
NotImplementedError: For spaces whose reading spec we haven'... | Returns a reading spec of a gym space.
NOTE: Only implemented currently for Box and Discrete.
Args:
gym_space: instance of gym.spaces whose spec we want.
Returns:
Reading spec for that space.
Raises:
NotImplementedError: For spaces whose reading spec we haven't implemented. | Below is the the instruction that describes the task:
### Input:
Returns a reading spec of a gym space.
NOTE: Only implemented currently for Box and Discrete.
Args:
gym_space: instance of gym.spaces whose spec we want.
Returns:
Reading spec for that space.
Raises:
NotImplementedError: For sp... |
def _load(self, value: Any):
"""
Load the value for the field, run validators and return the value.
Subclasses can override this to provide custom load logic.
:param value: value of the field
"""
if value in self.empty_values:
# If a default has been set fo... | Load the value for the field, run validators and return the value.
Subclasses can override this to provide custom load logic.
:param value: value of the field | Below is the the instruction that describes the task:
### Input:
Load the value for the field, run validators and return the value.
Subclasses can override this to provide custom load logic.
:param value: value of the field
### Response:
def _load(self, value: Any):
"""
Load the va... |
def prepare_vector_layer(layer):
"""This function will prepare the layer to be used in InaSAFE :
* Make a local copy of the layer.
* Make sure that we have an InaSAFE ID column.
* Rename fields according to our definitions.
* Remove fields which are not used.
:param layer: The layer to prep... | This function will prepare the layer to be used in InaSAFE :
* Make a local copy of the layer.
* Make sure that we have an InaSAFE ID column.
* Rename fields according to our definitions.
* Remove fields which are not used.
:param layer: The layer to prepare.
:type layer: QgsVectorLayer
... | Below is the the instruction that describes the task:
### Input:
This function will prepare the layer to be used in InaSAFE :
* Make a local copy of the layer.
* Make sure that we have an InaSAFE ID column.
* Rename fields according to our definitions.
* Remove fields which are not used.
:p... |
def decision_function(self, X):
"Decision function i.e. the raw data of the prediction"
self._X = Model.convert_features(X)
self._eval()
return self._ind[0].hy | Decision function i.e. the raw data of the prediction | Below is the the instruction that describes the task:
### Input:
Decision function i.e. the raw data of the prediction
### Response:
def decision_function(self, X):
"Decision function i.e. the raw data of the prediction"
self._X = Model.convert_features(X)
self._eval()
return self._... |
def transform(params):
"""
Transforms an heterogeneous map of params into a CloudStack
ready mapping of parameter to values.
It handles lists and dicts.
>>> p = {"a": 1, "b": "foo", "c": ["eggs", "spam"], "d": {"key": "value"}}
>>> transform(p)
>>> print(p)
{'a': '1', 'b': 'foo', 'c': ... | Transforms an heterogeneous map of params into a CloudStack
ready mapping of parameter to values.
It handles lists and dicts.
>>> p = {"a": 1, "b": "foo", "c": ["eggs", "spam"], "d": {"key": "value"}}
>>> transform(p)
>>> print(p)
{'a': '1', 'b': 'foo', 'c': 'eggs,spam', 'd[0].key': 'value'} | Below is the the instruction that describes the task:
### Input:
Transforms an heterogeneous map of params into a CloudStack
ready mapping of parameter to values.
It handles lists and dicts.
>>> p = {"a": 1, "b": "foo", "c": ["eggs", "spam"], "d": {"key": "value"}}
>>> transform(p)
>>> print(p... |
def perform_completion(editor):
"""
Performs the completion on given editor.
:param editor: Document editor.
:type editor: QWidget
:return: Method success.
:rtype: bool
"""
completion_prefix = editor.get_partial_word_under_cursor()
if not completion_prefix:
return
word... | Performs the completion on given editor.
:param editor: Document editor.
:type editor: QWidget
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Performs the completion on given editor.
:param editor: Document editor.
:type editor: QWidget
:return: Method success.
:rtype: bool
### Response:
def perform_completion(editor):
"""
Performs the completion on given editor.
... |
def save(self, outfile):
"""Save the image data to a file or file-like object"""
if isinstance(outfile, compat.string_type):
outfile = open(outfile, 'wb')
outfile.write(compat.urllib2.urlopen(self.href).read()) | Save the image data to a file or file-like object | Below is the the instruction that describes the task:
### Input:
Save the image data to a file or file-like object
### Response:
def save(self, outfile):
"""Save the image data to a file or file-like object"""
if isinstance(outfile, compat.string_type):
outfile = open(outfile, 'wb')
... |
def _do_layout(self):
"""Layout sizers"""
label_style = wx.LEFT | wx.ALIGN_CENTER_VERTICAL
button_style = wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | \
wx.ALIGN_CENTER_VERTICAL | wx.FIXED_MINSIZE
grid_sizer_1 = wx.GridSizer(4, 2, 3, 3)
grid_sizer_1.Add(self.R... | Layout sizers | Below is the the instruction that describes the task:
### Input:
Layout sizers
### Response:
def _do_layout(self):
"""Layout sizers"""
label_style = wx.LEFT | wx.ALIGN_CENTER_VERTICAL
button_style = wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | \
wx.ALIGN_CENTER_VERTICAL | ... |
def _play_sound(self, filename):
""" Shells player with the provided filename.
`filename`
Filename for sound file.
"""
command = self._get_external_player()
if not command:
return # no player found
if common.IS_MACOSX:
c... | Shells player with the provided filename.
`filename`
Filename for sound file. | Below is the the instruction that describes the task:
### Input:
Shells player with the provided filename.
`filename`
Filename for sound file.
### Response:
def _play_sound(self, filename):
""" Shells player with the provided filename.
`filename`
Fi... |
def least_squares(Cui, X, Y, regularization, num_threads=0):
""" For each user in Cui, calculate factors Xu for them
using least squares on Y.
Note: this is at least 10 times slower than the cython version included
here.
"""
users, n_factors = X.shape
YtY = Y.T.dot(Y)
for u in range(us... | For each user in Cui, calculate factors Xu for them
using least squares on Y.
Note: this is at least 10 times slower than the cython version included
here. | Below is the the instruction that describes the task:
### Input:
For each user in Cui, calculate factors Xu for them
using least squares on Y.
Note: this is at least 10 times slower than the cython version included
here.
### Response:
def least_squares(Cui, X, Y, regularization, num_threads=0):
""... |
def _clean_tag(name):
"""Cleans a tag. Removes illegal characters for instance.
Adapted from the TensorFlow function `clean_tag()` at
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/summary_op_util.py
Parameters
----------
name : str
The original tag n... | Cleans a tag. Removes illegal characters for instance.
Adapted from the TensorFlow function `clean_tag()` at
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/summary_op_util.py
Parameters
----------
name : str
The original tag name to be processed.
Ret... | Below is the the instruction that describes the task:
### Input:
Cleans a tag. Removes illegal characters for instance.
Adapted from the TensorFlow function `clean_tag()` at
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/summary_op_util.py
Parameters
----------
n... |
def raw_print(*args, **kw):
"""Raw print to sys.__stdout__, otherwise identical interface to print()."""
print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
file=sys.__stdout__)
sys.__stdout__.flush() | Raw print to sys.__stdout__, otherwise identical interface to print(). | Below is the the instruction that describes the task:
### Input:
Raw print to sys.__stdout__, otherwise identical interface to print().
### Response:
def raw_print(*args, **kw):
"""Raw print to sys.__stdout__, otherwise identical interface to print()."""
print(*args, sep=kw.get('sep', ' '), end=kw.get('en... |
def sender(self, body, stamp, url, sig):
"""Validate request is from Alexa.
Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5.
Checking the Signature of the Request: https://goo.gl/FDkjBN.
Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ
Args:
... | Validate request is from Alexa.
Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5.
Checking the Signature of the Request: https://goo.gl/FDkjBN.
Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ
Args:
body: str. HTTPS request body.
s... | Below is the the instruction that describes the task:
### Input:
Validate request is from Alexa.
Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5.
Checking the Signature of the Request: https://goo.gl/FDkjBN.
Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ
... |
def check_output(self, cmd):
"""Calls a command through SSH and returns its output.
"""
ret, output = self._call(cmd, True)
if ret != 0: # pragma: no cover
raise RemoteCommandFailure(command=cmd, ret=ret)
logger.debug("Output: %r", output)
return output | Calls a command through SSH and returns its output. | Below is the the instruction that describes the task:
### Input:
Calls a command through SSH and returns its output.
### Response:
def check_output(self, cmd):
"""Calls a command through SSH and returns its output.
"""
ret, output = self._call(cmd, True)
if ret != 0: # pragma: no c... |
def pyLuceneIndexer4to5(old):
"""
Copy attributes, reset index due because information about deleted
documents has been lost, and power up for IFulltextIndexer so other code
can find this item.
"""
new = old.upgradeVersion(PyLuceneIndexer.typeName, 4, 5,
indexCount=o... | Copy attributes, reset index due because information about deleted
documents has been lost, and power up for IFulltextIndexer so other code
can find this item. | Below is the the instruction that describes the task:
### Input:
Copy attributes, reset index due because information about deleted
documents has been lost, and power up for IFulltextIndexer so other code
can find this item.
### Response:
def pyLuceneIndexer4to5(old):
"""
Copy attributes, reset ind... |
def address(self):
'''
Return the address of this "object", minus the scheme, hostname
and port of the bridge
'''
return self.API.replace(
'http://{}:{}'.format(
self._bridge.hostname,
self._bridge.port
), ''
) | Return the address of this "object", minus the scheme, hostname
and port of the bridge | Below is the the instruction that describes the task:
### Input:
Return the address of this "object", minus the scheme, hostname
and port of the bridge
### Response:
def address(self):
'''
Return the address of this "object", minus the scheme, hostname
and port of the bridge
... |
def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False):
"""
Trains a k-nearest neighbors classifier for face recognition.
:param train_dir: directory that contains a sub-directory for each known person, with its name.
(View in source code to see train_dir ex... | Trains a k-nearest neighbors classifier for face recognition.
:param train_dir: directory that contains a sub-directory for each known person, with its name.
(View in source code to see train_dir example tree structure)
Structure:
<train_dir>/
├── <person1>/
│ ├── <somename1>.... | Below is the the instruction that describes the task:
### Input:
Trains a k-nearest neighbors classifier for face recognition.
:param train_dir: directory that contains a sub-directory for each known person, with its name.
(View in source code to see train_dir example tree structure)
Structure:
... |
def get_changes(self, changers, in_hierarchy=False, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Get changes caused by this refactoring
`changers` is a list of `_ArgumentChanger`\s. If `in_hierarchy`
is `True` the changers are applyed to all matching methods... | Get changes caused by this refactoring
`changers` is a list of `_ArgumentChanger`\s. If `in_hierarchy`
is `True` the changers are applyed to all matching methods in
the class hierarchy.
`resources` can be a list of `rope.base.resource.File`\s that
should be searched for occurre... | Below is the the instruction that describes the task:
### Input:
Get changes caused by this refactoring
`changers` is a list of `_ArgumentChanger`\s. If `in_hierarchy`
is `True` the changers are applyed to all matching methods in
the class hierarchy.
`resources` can be a list of `r... |
async def open(self) -> 'NodePool':
"""
Explicit entry. Opens pool as configured, for later closure via close().
Creates pool if it does not yet exist, using configured genesis transaction file.
For use when keeping pool open across multiple calls.
Raise any AbsentPool if node p... | Explicit entry. Opens pool as configured, for later closure via close().
Creates pool if it does not yet exist, using configured genesis transaction file.
For use when keeping pool open across multiple calls.
Raise any AbsentPool if node pool ledger configuration is not available.
:ret... | Below is the the instruction that describes the task:
### Input:
Explicit entry. Opens pool as configured, for later closure via close().
Creates pool if it does not yet exist, using configured genesis transaction file.
For use when keeping pool open across multiple calls.
Raise any AbsentP... |
def _list_gids():
'''
Return a list of gids in use
'''
output = __salt__['cmd.run'](
['dscacheutil', '-q', 'group'],
output_loglevel='quiet',
python_shell=False
)
ret = set()
for line in salt.utils.itertools.split(output, '\n'):
if line.startswith('gid:'):
... | Return a list of gids in use | Below is the the instruction that describes the task:
### Input:
Return a list of gids in use
### Response:
def _list_gids():
'''
Return a list of gids in use
'''
output = __salt__['cmd.run'](
['dscacheutil', '-q', 'group'],
output_loglevel='quiet',
python_shell=False
)
... |
def update_ssl_termination(self, loadbalancer, securePort=None, enabled=None,
secureTrafficOnly=None):
"""
Updates existing SSL termination information for the load balancer
without affecting the existing certificates/keys.
"""
return loadbalancer.update_ssl_terminati... | Updates existing SSL termination information for the load balancer
without affecting the existing certificates/keys. | Below is the the instruction that describes the task:
### Input:
Updates existing SSL termination information for the load balancer
without affecting the existing certificates/keys.
### Response:
def update_ssl_termination(self, loadbalancer, securePort=None, enabled=None,
secureTrafficOnly=Non... |
def transform(self, X):
"""Computes the row principal coordinates of a dataset."""
utils.validation.check_is_fitted(self, 's_')
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
return self.row_coordinates(X) | Computes the row principal coordinates of a dataset. | Below is the the instruction that describes the task:
### Input:
Computes the row principal coordinates of a dataset.
### Response:
def transform(self, X):
"""Computes the row principal coordinates of a dataset."""
utils.validation.check_is_fitted(self, 's_')
if self.check_input:
... |
def print_yielded(func):
"""
Convert a generator into a function that prints all yielded elements
>>> @print_yielded
... def x():
... yield 3; yield None
>>> x()
3
None
"""
print_all = functools.partial(map, print)
print_results = compose(more_itertools.recipes.consume, print_all, func)
return functool... | Convert a generator into a function that prints all yielded elements
>>> @print_yielded
... def x():
... yield 3; yield None
>>> x()
3
None | Below is the the instruction that describes the task:
### Input:
Convert a generator into a function that prints all yielded elements
>>> @print_yielded
... def x():
... yield 3; yield None
>>> x()
3
None
### Response:
def print_yielded(func):
"""
Convert a generator into a function that prints all yi... |
def get_variant_id(variant_dict=None, variant_line=None):
"""Build a variant id
The variant id is a string made of CHROM_POS_REF_ALT
Args:
variant_dict (dict): A variant dictionary
Returns:
variant_id (str)
"""
if variant_dict:
... | Build a variant id
The variant id is a string made of CHROM_POS_REF_ALT
Args:
variant_dict (dict): A variant dictionary
Returns:
variant_id (str) | Below is the the instruction that describes the task:
### Input:
Build a variant id
The variant id is a string made of CHROM_POS_REF_ALT
Args:
variant_dict (dict): A variant dictionary
Returns:
variant_id (str)
### Response:
def get_variant_id(... |
def _get_stddevs(self, C, stddev_types, num_sites):
"""
Return total standard deviation.
"""
# standard deviation is converted from log10 to ln
std_total = np.log(10 ** C['sigma'])
stddevs = []
for _ in stddev_types:
stddevs.append(np.zeros(num_sites) ... | Return total standard deviation. | Below is the the instruction that describes the task:
### Input:
Return total standard deviation.
### Response:
def _get_stddevs(self, C, stddev_types, num_sites):
"""
Return total standard deviation.
"""
# standard deviation is converted from log10 to ln
std_total = np.log(... |
def _match_path(pathname,
included_patterns,
excluded_patterns,
case_sensitive=True):
"""Internal function same as :func:`match_path` but does not check arguments.
Doctests::
>>> _match_path("/users/gorakhargosh/foobar.py", ["*.py"], ["*.PY"], True)
... | Internal function same as :func:`match_path` but does not check arguments.
Doctests::
>>> _match_path("/users/gorakhargosh/foobar.py", ["*.py"], ["*.PY"], True)
True
>>> _match_path("/users/gorakhargosh/FOOBAR.PY", ["*.py"], ["*.PY"], True)
False
>>> _match_path("/users/gora... | Below is the the instruction that describes the task:
### Input:
Internal function same as :func:`match_path` but does not check arguments.
Doctests::
>>> _match_path("/users/gorakhargosh/foobar.py", ["*.py"], ["*.PY"], True)
True
>>> _match_path("/users/gorakhargosh/FOOBAR.PY", ["*.py"... |
def spmatrix(self, reordered = True, symmetric = False):
"""
Converts the :py:class:`cspmatrix` :math:`A` to a sparse matrix. A reordered
matrix is returned if the optional argument `reordered` is
`True` (default), and otherwise the inverse permutation is applied. Only the
defaul... | Converts the :py:class:`cspmatrix` :math:`A` to a sparse matrix. A reordered
matrix is returned if the optional argument `reordered` is
`True` (default), and otherwise the inverse permutation is applied. Only the
default options are allowed if the :py:class:`cspmatrix` :math:`A` represents
... | Below is the the instruction that describes the task:
### Input:
Converts the :py:class:`cspmatrix` :math:`A` to a sparse matrix. A reordered
matrix is returned if the optional argument `reordered` is
`True` (default), and otherwise the inverse permutation is applied. Only the
default option... |
def incfile(fname, fpointer, lrange="1,6-", sdir=None):
r"""
Include a Python source file in a docstring formatted in reStructuredText.
:param fname: File name, relative to environment variable
:bash:`${TRACER_DIR}`
:type fname: string
:param fpointer: Output function pointer. N... | r"""
Include a Python source file in a docstring formatted in reStructuredText.
:param fname: File name, relative to environment variable
:bash:`${TRACER_DIR}`
:type fname: string
:param fpointer: Output function pointer. Normally is :code:`cog.out` but
:code:`p... | Below is the the instruction that describes the task:
### Input:
r"""
Include a Python source file in a docstring formatted in reStructuredText.
:param fname: File name, relative to environment variable
:bash:`${TRACER_DIR}`
:type fname: string
:param fpointer: Output function p... |
def handle_connection_change(self, state):
"""
Callback for handling changes in the kazoo client's connection state.
If the connection becomes lost or suspended, the `connected` Event
is cleared. Other given states imply that the connection is
established so `connected` is set.... | Callback for handling changes in the kazoo client's connection state.
If the connection becomes lost or suspended, the `connected` Event
is cleared. Other given states imply that the connection is
established so `connected` is set. | Below is the the instruction that describes the task:
### Input:
Callback for handling changes in the kazoo client's connection state.
If the connection becomes lost or suspended, the `connected` Event
is cleared. Other given states imply that the connection is
established so `connected` i... |
def __update_clusters(self, medoids):
"""!
@brief Forms cluster in line with specified medoids by calculation distance from each point to medoids.
"""
self.__belong = [0] * len(self.__pointer_data)
self.__clusters = [[] for i in range(len(medoids))]
... | !
@brief Forms cluster in line with specified medoids by calculation distance from each point to medoids. | Below is the the instruction that describes the task:
### Input:
!
@brief Forms cluster in line with specified medoids by calculation distance from each point to medoids.
### Response:
def __update_clusters(self, medoids):
"""!
@brief Forms cluster in line with specified medoids by calcu... |
def get_account(self, account):
""" Fetches an account with all its attributes.
:param account: an account object, with either id or name attribute set
:returns: a zobjects.Account object, filled.
"""
selector = account.to_selector()
resp = self.request_single('GetAccoun... | Fetches an account with all its attributes.
:param account: an account object, with either id or name attribute set
:returns: a zobjects.Account object, filled. | Below is the the instruction that describes the task:
### Input:
Fetches an account with all its attributes.
:param account: an account object, with either id or name attribute set
:returns: a zobjects.Account object, filled.
### Response:
def get_account(self, account):
""" Fetches an acc... |
def coerce_value(type, value):
# type: (Any, Any) -> Union[List, Dict, int, float, bool, str, None]
"""Given a type and any value, return a runtime value coerced to match the type."""
if isinstance(type, GraphQLNonNull):
# Note: we're not checking that the result of coerceValue is
# non-null... | Given a type and any value, return a runtime value coerced to match the type. | Below is the the instruction that describes the task:
### Input:
Given a type and any value, return a runtime value coerced to match the type.
### Response:
def coerce_value(type, value):
# type: (Any, Any) -> Union[List, Dict, int, float, bool, str, None]
"""Given a type and any value, return a runtime va... |
def open_mfdataset(paths, chunks=None, concat_dim=_CONCAT_DIM_DEFAULT,
compat='no_conflicts', preprocess=None, engine=None,
lock=None, data_vars='all', coords='different',
autoclose=None, parallel=False, **kwargs):
"""Open multiple files as a single dataset.
... | Open multiple files as a single dataset.
Requires dask to be installed. See documentation for details on dask [1].
Attributes from the first dataset file are used for the combined dataset.
Parameters
----------
paths : str or sequence
Either a string glob in the form "path/to/my/files/*.nc... | Below is the the instruction that describes the task:
### Input:
Open multiple files as a single dataset.
Requires dask to be installed. See documentation for details on dask [1].
Attributes from the first dataset file are used for the combined dataset.
Parameters
----------
paths : str or seq... |
def synchronized(lock):
"""
Synchronization decorator; provide thread-safe locking on a function
http://code.activestate.com/recipes/465057/
"""
def wrap(f):
def synchronize(*args, **kw):
lock.acquire()
try:
return f(*args, **kw)
finally:
... | Synchronization decorator; provide thread-safe locking on a function
http://code.activestate.com/recipes/465057/ | Below is the the instruction that describes the task:
### Input:
Synchronization decorator; provide thread-safe locking on a function
http://code.activestate.com/recipes/465057/
### Response:
def synchronized(lock):
"""
Synchronization decorator; provide thread-safe locking on a function
http://cod... |
def rm(self, filename):
""" Delete a file from the server.
:param filename: the file to be deleted.
:type filename: string
"""
try:
self._ftp.delete(filename)
except error_perm: # target is either a directory
# either it does not ... | Delete a file from the server.
:param filename: the file to be deleted.
:type filename: string | Below is the the instruction that describes the task:
### Input:
Delete a file from the server.
:param filename: the file to be deleted.
:type filename: string
### Response:
def rm(self, filename):
""" Delete a file from the server.
:param filename: the file to be deleted.
... |
def schedule(self, year):
"""Gets schedule information for a team-season.
:year: The year for which we want the schedule.
:returns: DataFrame of schedule information.
"""
doc = self.get_year_doc('{}_games'.format(year))
table = doc('table#games')
df = sportsref.u... | Gets schedule information for a team-season.
:year: The year for which we want the schedule.
:returns: DataFrame of schedule information. | Below is the the instruction that describes the task:
### Input:
Gets schedule information for a team-season.
:year: The year for which we want the schedule.
:returns: DataFrame of schedule information.
### Response:
def schedule(self, year):
"""Gets schedule information for a team-season.... |
def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 4)
self.set_attributes(priority, address, rtr)
self._day = data[0]... | :return: None | Below is the the instruction that describes the task:
### Input:
:return: None
### Response:
def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rtr)
self.n... |
def GetPreviousNonBlankLine(clean_lines, linenum):
"""Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents ... | Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, ... | Below is the the instruction that describes the task:
### Input:
Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is ... |
def memoize(Class, *args, **kwargs):
'''
Memoize/record a function inside this vlermv. ::
@Vlermv.cache('~/.http')
def get(url):
return requests.get(url, auth = ('username', 'password'))
The args and kwargs get passed to the Vlermv with some slight chang... | Memoize/record a function inside this vlermv. ::
@Vlermv.cache('~/.http')
def get(url):
return requests.get(url, auth = ('username', 'password'))
The args and kwargs get passed to the Vlermv with some slight changes.
Here are the changes.
First, the def... | Below is the the instruction that describes the task:
### Input:
Memoize/record a function inside this vlermv. ::
@Vlermv.cache('~/.http')
def get(url):
return requests.get(url, auth = ('username', 'password'))
The args and kwargs get passed to the Vlermv with some ... |
def normalize_dsn_or_dict(d):
"""Clean up a database DSN, or dict version of a DSN, returning both the cleaned DSN and dict version"""
if isinstance(d, dict):
try:
# Convert from an AttrDict to a real dict
d = d.to_dict()
except AttributeError:
pass # Alread... | Clean up a database DSN, or dict version of a DSN, returning both the cleaned DSN and dict version | Below is the the instruction that describes the task:
### Input:
Clean up a database DSN, or dict version of a DSN, returning both the cleaned DSN and dict version
### Response:
def normalize_dsn_or_dict(d):
"""Clean up a database DSN, or dict version of a DSN, returning both the cleaned DSN and dict version""... |
def _chart_class(self, df, chart_type, **kwargs):
"""
Get the right chart class from a string
"""
if chart_type == "bar":
return Chart(df).mark_bar(**kwargs)
elif chart_type == "circle":
return Chart(df).mark_circle(**kwargs)
elif chart_type == "li... | Get the right chart class from a string | Below is the the instruction that describes the task:
### Input:
Get the right chart class from a string
### Response:
def _chart_class(self, df, chart_type, **kwargs):
"""
Get the right chart class from a string
"""
if chart_type == "bar":
return Chart(df).mark_bar(**kw... |
def _has_valid_positional_setitem_indexer(self, indexer):
""" validate that an positional indexer cannot enlarge its target
will raise if needed, does not modify the indexer externally
"""
if isinstance(indexer, dict):
raise IndexError("{0} cannot enlarge its target object"
... | validate that an positional indexer cannot enlarge its target
will raise if needed, does not modify the indexer externally | Below is the the instruction that describes the task:
### Input:
validate that an positional indexer cannot enlarge its target
will raise if needed, does not modify the indexer externally
### Response:
def _has_valid_positional_setitem_indexer(self, indexer):
""" validate that an positional indexer... |
def strip_suffix(s, suffix, strict=False):
"""Removes the suffix, if it's there, otherwise returns input string unchanged.
If strict is True, also ensures the suffix was present"""
if s.endswith(suffix):
return s[: len(s) - len(suffix)]
elif strict:
raise WimpyError("string doesn't end w... | Removes the suffix, if it's there, otherwise returns input string unchanged.
If strict is True, also ensures the suffix was present | Below is the the instruction that describes the task:
### Input:
Removes the suffix, if it's there, otherwise returns input string unchanged.
If strict is True, also ensures the suffix was present
### Response:
def strip_suffix(s, suffix, strict=False):
"""Removes the suffix, if it's there, otherwise retur... |
def write_edge (self, node):
"""Write edge from parent to node."""
source = dotquote(self.nodes[node["parent_url"]]["label"])
target = dotquote(node["label"])
self.writeln(u' "%s" -> "%s" [' % (source, target))
self.writeln(u' label="%s",' % dotquote(node["edge"]))
if... | Write edge from parent to node. | Below is the the instruction that describes the task:
### Input:
Write edge from parent to node.
### Response:
def write_edge (self, node):
"""Write edge from parent to node."""
source = dotquote(self.nodes[node["parent_url"]]["label"])
target = dotquote(node["label"])
self.writeln(... |
def marshall(self, registry):
"""Returns bytes"""
result = b""
for i in registry.get_all():
# Each message needs to be prefixed with a varint with the size of
# the message (MetrycType)
# https://github.com/matttproud/golang_protobuf_extensions/blob/master/ex... | Returns bytes | Below is the the instruction that describes the task:
### Input:
Returns bytes
### Response:
def marshall(self, registry):
"""Returns bytes"""
result = b""
for i in registry.get_all():
# Each message needs to be prefixed with a varint with the size of
# the message ... |
def on_ok(self):
""" Perform restoration on the backup file selected """
if self.dir_select.value:
npyscreen.notify_wait('In the process of restoring',
title='Restoring...')
status = self.restore(self.dirs[self.dir_select.value[0]])
i... | Perform restoration on the backup file selected | Below is the the instruction that describes the task:
### Input:
Perform restoration on the backup file selected
### Response:
def on_ok(self):
""" Perform restoration on the backup file selected """
if self.dir_select.value:
npyscreen.notify_wait('In the process of restoring',
... |
def _parse_info_snpeff(self, info):
"""
Specialized INFO field parser for SnpEff ANN fields.
Requires self._snpeff_ann_fields to be set.
"""
ann = info.pop('ANN', []) or []
# Overwrite the existing ANN with something parsed
# Split on '|', merge with the ANN keys ... | Specialized INFO field parser for SnpEff ANN fields.
Requires self._snpeff_ann_fields to be set. | Below is the the instruction that describes the task:
### Input:
Specialized INFO field parser for SnpEff ANN fields.
Requires self._snpeff_ann_fields to be set.
### Response:
def _parse_info_snpeff(self, info):
"""
Specialized INFO field parser for SnpEff ANN fields.
Requires self.... |
def get_docargs(self, args=None, prt=None):
"""Pare down docopt. Return a minimal dictionary and a set containing runtime arg values."""
# docargs = self.objdoc.get_docargs(args, exp_letters=set(['o', 't', 'p', 'c']))
docargs = self.objdoc.get_docargs(args, prt)
self._chk_docopts(docargs... | Pare down docopt. Return a minimal dictionary and a set containing runtime arg values. | Below is the the instruction that describes the task:
### Input:
Pare down docopt. Return a minimal dictionary and a set containing runtime arg values.
### Response:
def get_docargs(self, args=None, prt=None):
"""Pare down docopt. Return a minimal dictionary and a set containing runtime arg values."""
... |
def evaluate_script(self):
"""
Evaluates current **Script_Editor_tabWidget** Widget tab Model editor content
into the interactive console.
:return: Method success.
:rtype: bool
"""
editor = self.get_current_editor()
if not editor:
return Fals... | Evaluates current **Script_Editor_tabWidget** Widget tab Model editor content
into the interactive console.
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Evaluates current **Script_Editor_tabWidget** Widget tab Model editor content
into the interactive console.
:return: Method success.
:rtype: bool
### Response:
def evaluate_script(self):
"""
Evaluates current ... |
def get_arguments(self):
""" Gets the arguments from the command line. """
parser = argparse.ArgumentParser(
description='Downloads images from given URL')
parser.add_argument('url2scrape', nargs=1, help="URL to scrape")
parser.add_argument('-m', '--max-images', type=int, de... | Gets the arguments from the command line. | Below is the the instruction that describes the task:
### Input:
Gets the arguments from the command line.
### Response:
def get_arguments(self):
""" Gets the arguments from the command line. """
parser = argparse.ArgumentParser(
description='Downloads images from given URL')
p... |
def set_eol_chars(self, text):
"""Set widget end-of-line (EOL) characters from text (analyzes text)"""
if not is_text_string(text): # testing for QString (PyQt API#1)
text = to_text_string(text)
eol_chars = sourcecode.get_eol_chars(text)
is_document_modified = eol_chars ... | Set widget end-of-line (EOL) characters from text (analyzes text) | Below is the the instruction that describes the task:
### Input:
Set widget end-of-line (EOL) characters from text (analyzes text)
### Response:
def set_eol_chars(self, text):
"""Set widget end-of-line (EOL) characters from text (analyzes text)"""
if not is_text_string(text): # testing for QStrin... |
def filter(self, record):
"""Is the specified record to be logged? Returns zero for no,
nonzero for yes. If deemed appropriate, the record may be modified
in-place by this method.
:param logging.LogRecord record: The log record to process
:rtype: int
"""
if self... | Is the specified record to be logged? Returns zero for no,
nonzero for yes. If deemed appropriate, the record may be modified
in-place by this method.
:param logging.LogRecord record: The log record to process
:rtype: int | Below is the the instruction that describes the task:
### Input:
Is the specified record to be logged? Returns zero for no,
nonzero for yes. If deemed appropriate, the record may be modified
in-place by this method.
:param logging.LogRecord record: The log record to process
:rtype: ... |
def save(self, destination: BinaryIO, buffer_size: int=16384) -> None:
"""Save the file to the destination.
Arguments:
destination: A filename (str) or file object to write to.
buffer_size: Buffer size as used as length in
:func:`shutil.copyfileobj`.
"""
... | Save the file to the destination.
Arguments:
destination: A filename (str) or file object to write to.
buffer_size: Buffer size as used as length in
:func:`shutil.copyfileobj`. | Below is the the instruction that describes the task:
### Input:
Save the file to the destination.
Arguments:
destination: A filename (str) or file object to write to.
buffer_size: Buffer size as used as length in
:func:`shutil.copyfileobj`.
### Response:
def save(s... |
def execute_cleanup_tasks(ctx, cleanup_tasks, dry_run=False):
"""Execute several cleanup tasks as part of the cleanup.
REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks.
:param ctx: Context object for the tasks.
:param cleanup_tasks: Collection of cleanup tasks (as Colle... | Execute several cleanup tasks as part of the cleanup.
REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks.
:param ctx: Context object for the tasks.
:param cleanup_tasks: Collection of cleanup tasks (as Collection).
:param dry_run: Indicates dry-run mode (bool) | Below is the the instruction that describes the task:
### Input:
Execute several cleanup tasks as part of the cleanup.
REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks.
:param ctx: Context object for the tasks.
:param cleanup_tasks: Collection of cleanup tasks (as Colle... |
def convertTimestamps(column):
"""Convert a dtype of a given column to a datetime.
This method tries to do this by brute force.
Args:
column (pandas.Series): A Series object with all rows.
Returns:
column: Converted to datetime if no errors occured, else the
original colum... | Convert a dtype of a given column to a datetime.
This method tries to do this by brute force.
Args:
column (pandas.Series): A Series object with all rows.
Returns:
column: Converted to datetime if no errors occured, else the
original column will be returned. | Below is the the instruction that describes the task:
### Input:
Convert a dtype of a given column to a datetime.
This method tries to do this by brute force.
Args:
column (pandas.Series): A Series object with all rows.
Returns:
column: Converted to datetime if no errors occured, else... |
def console_output(self, instance=None):
"""Yields the output and metadata from all jobs in the pipeline
Args:
instance: The result of a :meth:`instance` call, if not supplied
the latest of the pipeline will be used.
Yields:
tuple: (metadata (dict), output (str)... | Yields the output and metadata from all jobs in the pipeline
Args:
instance: The result of a :meth:`instance` call, if not supplied
the latest of the pipeline will be used.
Yields:
tuple: (metadata (dict), output (str)).
metadata contains:
- pipel... | Below is the the instruction that describes the task:
### Input:
Yields the output and metadata from all jobs in the pipeline
Args:
instance: The result of a :meth:`instance` call, if not supplied
the latest of the pipeline will be used.
Yields:
tuple: (metadata (di... |
def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
... | Create an unsigned transaction. | Below is the the instruction that describes the task:
### Input:
Create an unsigned transaction.
### Response:
def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
... |
def ValidateURL(url, column_name=None, problems=None):
"""
Validates a non-required URL value using IsValidURL():
- if invalid adds InvalidValue error (if problems accumulator is provided)
- an empty URL is considered valid and no error or warning is issued.
"""
if IsEmpty(url) or IsValidURL(url):
r... | Validates a non-required URL value using IsValidURL():
- if invalid adds InvalidValue error (if problems accumulator is provided)
- an empty URL is considered valid and no error or warning is issued. | Below is the the instruction that describes the task:
### Input:
Validates a non-required URL value using IsValidURL():
- if invalid adds InvalidValue error (if problems accumulator is provided)
- an empty URL is considered valid and no error or warning is issued.
### Response:
def ValidateURL(url, column_... |
def _inhibitColumnsWithLateral(self, overlaps, lateralConnections):
"""
Performs an experimentatl local inhibition. Local inhibition is
iteratively performed on a column by column basis.
"""
n,m = self.shape
y = np.zeros(n)
s = self.sparsity
L = lateralConnections
desiredWeigh... | Performs an experimentatl local inhibition. Local inhibition is
iteratively performed on a column by column basis. | Below is the the instruction that describes the task:
### Input:
Performs an experimentatl local inhibition. Local inhibition is
iteratively performed on a column by column basis.
### Response:
def _inhibitColumnsWithLateral(self, overlaps, lateralConnections):
"""
Performs an experimentatl local inhi... |
def load_fits_catalog(self, name, **kwargs):
"""Load sources from a FITS catalog file.
Parameters
----------
name : str
Catalog name or path to a catalog FITS file.
"""
# EAC split this function to make it easier to load an existing catalog
cat = cat... | Load sources from a FITS catalog file.
Parameters
----------
name : str
Catalog name or path to a catalog FITS file. | Below is the the instruction that describes the task:
### Input:
Load sources from a FITS catalog file.
Parameters
----------
name : str
Catalog name or path to a catalog FITS file.
### Response:
def load_fits_catalog(self, name, **kwargs):
"""Load sources from a FITS ... |
def destroy_template(name=None, call=None, kwargs=None):
'''
Destroy Xen VM or template instance
.. code-block:: bash
salt-cloud -f destroy_template myxen name=testvm2
'''
if call == 'action':
raise SaltCloudSystemExit(
'The destroy_template function must be ca... | Destroy Xen VM or template instance
.. code-block:: bash
salt-cloud -f destroy_template myxen name=testvm2 | Below is the the instruction that describes the task:
### Input:
Destroy Xen VM or template instance
.. code-block:: bash
salt-cloud -f destroy_template myxen name=testvm2
### Response:
def destroy_template(name=None, call=None, kwargs=None):
'''
Destroy Xen VM or template instance
... |
def pycode(argcount,
kwonlyargcount,
nlocals,
stacksize,
flags,
codestring,
constants,
names,
varnames,
filename,
name,
firstlineno,
lnotab,
freevars=(),
cellvars=())... | types.CodeType constructor that accepts keyword arguments.
See Also
--------
types.CodeType | Below is the the instruction that describes the task:
### Input:
types.CodeType constructor that accepts keyword arguments.
See Also
--------
types.CodeType
### Response:
def pycode(argcount,
kwonlyargcount,
nlocals,
stacksize,
flags,
codestring,
... |
def target_address(self):
"""Return the authorative target of the link."""
# If link is a receiver, target is determined by the local
# value, else use the remote.
if self._pn_link.is_receiver:
return self._pn_link.target.address
else:
return self._pn_link... | Return the authorative target of the link. | Below is the the instruction that describes the task:
### Input:
Return the authorative target of the link.
### Response:
def target_address(self):
"""Return the authorative target of the link."""
# If link is a receiver, target is determined by the local
# value, else use the remote.
... |
def flipVertical(self):
""" flips an image object vertically
"""
self.flipV = not self.flipV
self._transmogrophy(self.angle, self.percent, self.scaleFromCenter, self.flipH, self.flipV) | flips an image object vertically | Below is the the instruction that describes the task:
### Input:
flips an image object vertically
### Response:
def flipVertical(self):
""" flips an image object vertically
"""
self.flipV = not self.flipV
self._transmogrophy(self.angle, self.percent, self.scaleFromCent... |
def cli(obj, ids, query, filters):
"""Show raw data for alerts."""
client = obj['client']
if ids:
query = [('id', x) for x in ids]
elif query:
query = [('q', query)]
else:
query = build_query(filters)
alerts = client.search(query)
headers = {'id': 'ID', 'rawData': 'R... | Show raw data for alerts. | Below is the the instruction that describes the task:
### Input:
Show raw data for alerts.
### Response:
def cli(obj, ids, query, filters):
"""Show raw data for alerts."""
client = obj['client']
if ids:
query = [('id', x) for x in ids]
elif query:
query = [('q', query)]
else:
... |
def sync_model(self, comment='', compact_central=False,
release_borrowed=True, release_workset=True,
save_local=False):
"""Append a sync model entry to the journal.
This instructs Revit to sync the currently open workshared model.
Args:
comment... | Append a sync model entry to the journal.
This instructs Revit to sync the currently open workshared model.
Args:
comment (str): comment to be provided for the sync step
compact_central (bool): if True compacts the central file
release_borrowed (bool): if True relea... | Below is the the instruction that describes the task:
### Input:
Append a sync model entry to the journal.
This instructs Revit to sync the currently open workshared model.
Args:
comment (str): comment to be provided for the sync step
compact_central (bool): if True compact... |
def convert_timedelta(duration):
"""
Summary:
Convert duration into component time units
Args:
:duration (datetime.timedelta): time duration to convert
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers)
"""
days, seconds = duration.days, duration.seconds
... | Summary:
Convert duration into component time units
Args:
:duration (datetime.timedelta): time duration to convert
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers) | Below is the the instruction that describes the task:
### Input:
Summary:
Convert duration into component time units
Args:
:duration (datetime.timedelta): time duration to convert
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers)
### Response:
def convert_timedelta(dur... |
def odd_odd(self):
"""Selects odd-odd nuclei from the table:
>>> Table('FRDM95').odd_odd
Out[13]:
Z N
9 9 1.21
11 0.10
13 3.08
15 9.32
...
"""
return self.select(lambda Z, N: (Z % 2) and (N % 2)... | Selects odd-odd nuclei from the table:
>>> Table('FRDM95').odd_odd
Out[13]:
Z N
9 9 1.21
11 0.10
13 3.08
15 9.32
... | Below is the the instruction that describes the task:
### Input:
Selects odd-odd nuclei from the table:
>>> Table('FRDM95').odd_odd
Out[13]:
Z N
9 9 1.21
11 0.10
13 3.08
15 9.32
...
### Response:
def odd_odd(self)... |
def _handle_builder_exception(self, message, residue):
"""
Makes a PDB Construction Error a bit more verbose and informative
"""
message = "%s. Error when parsing residue %s:%s" %(message, residue['number'], residue['name'])
raise PDBConstructionException(messag... | Makes a PDB Construction Error a bit more verbose and informative | Below is the the instruction that describes the task:
### Input:
Makes a PDB Construction Error a bit more verbose and informative
### Response:
def _handle_builder_exception(self, message, residue):
"""
Makes a PDB Construction Error a bit more verbose and informative
"""
... |
def has_file_url(self):
"""stub"""
return bool(self._get_asset_content(
Id(self.my_osid_object._my_map['fileId']['assetId']),
self.my_osid_object._my_map['fileId']['assetContentTypeId']).has_url()) | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def has_file_url(self):
"""stub"""
return bool(self._get_asset_content(
Id(self.my_osid_object._my_map['fileId']['assetId']),
self.my_osid_object._my_map['fileId']['assetContentTypeId']).has_... |
def encodeLength(value):
'''
Encodes value into a multibyte sequence defined by MQTT protocol.
Used to encode packet length fields.
'''
encoded = bytearray()
while True:
digit = value % 128
value //= 128
if value > 0:
digit |= 128
encoded.append(digit)... | Encodes value into a multibyte sequence defined by MQTT protocol.
Used to encode packet length fields. | Below is the the instruction that describes the task:
### Input:
Encodes value into a multibyte sequence defined by MQTT protocol.
Used to encode packet length fields.
### Response:
def encodeLength(value):
'''
Encodes value into a multibyte sequence defined by MQTT protocol.
Used to encode packet ... |
def from_dlpack(dlpack):
"""Returns a NDArray backed by a dlpack tensor.
Parameters
----------
dlpack: PyCapsule (the pointer of DLManagedTensor)
input data
Returns
-------
NDArray
a NDArray backed by a dlpack tensor
Examples
--------
>>> x = mx.nd.ones((2,3))
... | Returns a NDArray backed by a dlpack tensor.
Parameters
----------
dlpack: PyCapsule (the pointer of DLManagedTensor)
input data
Returns
-------
NDArray
a NDArray backed by a dlpack tensor
Examples
--------
>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.to_dlpack_for_... | Below is the the instruction that describes the task:
### Input:
Returns a NDArray backed by a dlpack tensor.
Parameters
----------
dlpack: PyCapsule (the pointer of DLManagedTensor)
input data
Returns
-------
NDArray
a NDArray backed by a dlpack tensor
Examples
--... |
def get_anchor_format(a):
"""
Extract the resource file-type format from the anchor.
"""
# (. or format=) then (file_extension) then (? or $)
# e.g. "...format=txt" or "...download.mp4?..."
fmt = re.search(r"(?:\.|format=)(\w+)(?:\?.*)?$", a)
return fmt.group(1) if fmt else None | Extract the resource file-type format from the anchor. | Below is the the instruction that describes the task:
### Input:
Extract the resource file-type format from the anchor.
### Response:
def get_anchor_format(a):
"""
Extract the resource file-type format from the anchor.
"""
# (. or format=) then (file_extension) then (? or $)
# e.g. "...format=... |
def transform(self, X):
"""
Args:
X: DataFrame with NaN's
Returns:
Dictionary with one key - 'X' corresponding to given DataFrame but without nan's
"""
if self.fill_missing:
X = self.filler.complete(X)
return {'X': X} | Args:
X: DataFrame with NaN's
Returns:
Dictionary with one key - 'X' corresponding to given DataFrame but without nan's | Below is the the instruction that describes the task:
### Input:
Args:
X: DataFrame with NaN's
Returns:
Dictionary with one key - 'X' corresponding to given DataFrame but without nan's
### Response:
def transform(self, X):
"""
Args:
X: DataFrame with NaN'... |
def colourblind(i):
'''
colour pallete from http://tableaufriction.blogspot.ro/
allegedly suitable for colour-blind folk
SJ
'''
rawRGBs = [(162,200,236),
(255,128,14),
(171,171,171),
(95,158,209),
(89,89,89),
... | colour pallete from http://tableaufriction.blogspot.ro/
allegedly suitable for colour-blind folk
SJ | Below is the the instruction that describes the task:
### Input:
colour pallete from http://tableaufriction.blogspot.ro/
allegedly suitable for colour-blind folk
SJ
### Response:
def colourblind(i):
'''
colour pallete from http://tableaufriction.blogspot.ro/
allegedly suitable ... |
def _dfs_edges(graph, source, max_steps=None):
"""
Perform a depth-first search on the given DiGraph, with a limit on maximum steps.
:param networkx.DiGraph graph: The graph to traverse.
:param Any source: The source to begin traversal.
:param int max_steps: ... | Perform a depth-first search on the given DiGraph, with a limit on maximum steps.
:param networkx.DiGraph graph: The graph to traverse.
:param Any source: The source to begin traversal.
:param int max_steps: Maximum steps of the traversal, or None if not limiting steps.
... | Below is the the instruction that describes the task:
### Input:
Perform a depth-first search on the given DiGraph, with a limit on maximum steps.
:param networkx.DiGraph graph: The graph to traverse.
:param Any source: The source to begin traversal.
:param int max_steps: ... |
def set_condition(self, value):
"""
Setter for 'condition' field.
:param value - a new value of 'condition' field. Required field. Must be a String.
"""
if value is None or not isinstance(value, str):
raise TypeError("Condition is required and must be set to a String"... | Setter for 'condition' field.
:param value - a new value of 'condition' field. Required field. Must be a String. | Below is the the instruction that describes the task:
### Input:
Setter for 'condition' field.
:param value - a new value of 'condition' field. Required field. Must be a String.
### Response:
def set_condition(self, value):
"""
Setter for 'condition' field.
:param value - a new valu... |
def _check_transition_target(self, transition):
"""Checks the validity of a transition target
Checks whether the transition target is valid.
:param rafcon.core.transition.Transition transition: The transition to be checked
:return bool validity, str message: validity is True, when the ... | Checks the validity of a transition target
Checks whether the transition target is valid.
:param rafcon.core.transition.Transition transition: The transition to be checked
:return bool validity, str message: validity is True, when the transition is valid, False else. message gives
... | Below is the the instruction that describes the task:
### Input:
Checks the validity of a transition target
Checks whether the transition target is valid.
:param rafcon.core.transition.Transition transition: The transition to be checked
:return bool validity, str message: validity is True,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.