code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def put_job(self, id, body, params=None):
"""
`<>`_
:arg id: The ID of the job to create
:arg body: The job configuration
"""
for param in (id, body):
if param in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument.")
... | `<>`_
:arg id: The ID of the job to create
:arg body: The job configuration | Below is the the instruction that describes the task:
### Input:
`<>`_
:arg id: The ID of the job to create
:arg body: The job configuration
### Response:
def put_job(self, id, body, params=None):
"""
`<>`_
:arg id: The ID of the job to create
:arg body: The job co... |
def flatMap(self, f, preservesPartitioning=False):
"""Apply function f and flatten.
:param f: mapping function
:rtype: DStream
"""
return self.mapPartitions(
lambda p: (e for pp in p for e in f(pp)),
preservesPartitioning,
) | Apply function f and flatten.
:param f: mapping function
:rtype: DStream | Below is the the instruction that describes the task:
### Input:
Apply function f and flatten.
:param f: mapping function
:rtype: DStream
### Response:
def flatMap(self, f, preservesPartitioning=False):
"""Apply function f and flatten.
:param f: mapping function
:rtype: DS... |
def get_template_filelist(repo_path, ignore_files=[], ignore_folders=[]):
"""
input: local repo path
output: path list of files which need to be rendered
"""
default_ignore_files = ['.gitignore']
default_ignore_folders = ['.git']
ignore_files += default_ignore_files
ignore_folders += d... | input: local repo path
output: path list of files which need to be rendered | Below is the the instruction that describes the task:
### Input:
input: local repo path
output: path list of files which need to be rendered
### Response:
def get_template_filelist(repo_path, ignore_files=[], ignore_folders=[]):
"""
input: local repo path
output: path list of files which need to be... |
def push_sample(self, x, timestamp=0.0, pushthrough=True):
"""Push a sample into the outlet.
Each entry in the list corresponds to one channel.
Keyword arguments:
x -- A list of values to push (one per channel).
timestamp -- Optionally the capture time of the sample, in agreeme... | Push a sample into the outlet.
Each entry in the list corresponds to one channel.
Keyword arguments:
x -- A list of values to push (one per channel).
timestamp -- Optionally the capture time of the sample, in agreement
with local_clock(); if omitted, the current
... | Below is the the instruction that describes the task:
### Input:
Push a sample into the outlet.
Each entry in the list corresponds to one channel.
Keyword arguments:
x -- A list of values to push (one per channel).
timestamp -- Optionally the capture time of the sample, in agreemen... |
def _eliminate_leafs(self, graph):
"""
Eliminate leaf objects - that are objects not referencing any other
objects in the list `graph`. Returns the list of objects without the
objects identified as leafs.
"""
result = []
idset = set([id(x) for x in graph])
... | Eliminate leaf objects - that are objects not referencing any other
objects in the list `graph`. Returns the list of objects without the
objects identified as leafs. | Below is the the instruction that describes the task:
### Input:
Eliminate leaf objects - that are objects not referencing any other
objects in the list `graph`. Returns the list of objects without the
objects identified as leafs.
### Response:
def _eliminate_leafs(self, graph):
"""
... |
def pull_request(ctx, base_branch, open_pr, stop_timer):
"""Create a new pull request for this issue."""
lancet = ctx.obj
review_status = lancet.config.get("tracker", "review_status")
remote_name = lancet.config.get("repository", "remote_name")
if not base_branch:
base_branch = lancet.conf... | Create a new pull request for this issue. | Below is the the instruction that describes the task:
### Input:
Create a new pull request for this issue.
### Response:
def pull_request(ctx, base_branch, open_pr, stop_timer):
"""Create a new pull request for this issue."""
lancet = ctx.obj
review_status = lancet.config.get("tracker", "review_status... |
def queued(values, qsize):
"""
Queues up readings from *values* (the number of readings queued is
determined by *qsize*) and begins yielding values only when the queue is
full. For example, to "cascade" values along a sequence of LEDs::
from gpiozero import LEDBoard, Button
from gpiozer... | Queues up readings from *values* (the number of readings queued is
determined by *qsize*) and begins yielding values only when the queue is
full. For example, to "cascade" values along a sequence of LEDs::
from gpiozero import LEDBoard, Button
from gpiozero.tools import queued
from sign... | Below is the the instruction that describes the task:
### Input:
Queues up readings from *values* (the number of readings queued is
determined by *qsize*) and begins yielding values only when the queue is
full. For example, to "cascade" values along a sequence of LEDs::
from gpiozero import LEDBoar... |
def vofile(filename, **kwargs):
"""
Open and return a handle on a VOSpace data connection
@param filename:
@param kwargs:
@return:
"""
basename = os.path.basename(filename)
if os.access(basename, os.R_OK):
return open(basename, 'r')
kwargs['view'] = kwargs.get('view', 'data')... | Open and return a handle on a VOSpace data connection
@param filename:
@param kwargs:
@return: | Below is the the instruction that describes the task:
### Input:
Open and return a handle on a VOSpace data connection
@param filename:
@param kwargs:
@return:
### Response:
def vofile(filename, **kwargs):
"""
Open and return a handle on a VOSpace data connection
@param filename:
@param... |
def generate_id(self, agreement_id, types, values):
"""
Generate id for the condition.
:param agreement_id: id of the agreement, hex str
:param types: list of types
:param values: list of values
:return: id, str
"""
values_hash = utils.generate_multi_valu... | Generate id for the condition.
:param agreement_id: id of the agreement, hex str
:param types: list of types
:param values: list of values
:return: id, str | Below is the the instruction that describes the task:
### Input:
Generate id for the condition.
:param agreement_id: id of the agreement, hex str
:param types: list of types
:param values: list of values
:return: id, str
### Response:
def generate_id(self, agreement_id, types, valu... |
def get_changesets(self, start=None, end=None, start_date=None,
end_date=None, branch_name=None, reverse=False):
"""
Returns iterator of ``GitChangeset`` objects from start to end (both
are inclusive), in ascending date order (unless ``reverse`` is set).
:param start: changes... | Returns iterator of ``GitChangeset`` objects from start to end (both
are inclusive), in ascending date order (unless ``reverse`` is set).
:param start: changeset ID, as str; first returned changeset
:param end: changeset ID, as str; last returned changeset
:param start_date: if specifie... | Below is the the instruction that describes the task:
### Input:
Returns iterator of ``GitChangeset`` objects from start to end (both
are inclusive), in ascending date order (unless ``reverse`` is set).
:param start: changeset ID, as str; first returned changeset
:param end: changeset ID, a... |
def epd_kepler_lightcurve(lcdict,
xccol='mom_centr1',
yccol='mom_centr2',
timestoignore=None,
filterflags=True,
writetodict=True,
epdsmooth=5):
'''This runs EPD... | This runs EPD on the Kepler light curve.
Following Huang et al. 2015, we fit the following EPD function to a smoothed
light curve, and then subtract it to obtain EPD corrected magnitudes::
f = c0 +
c1*sin(2*pi*x) + c2*cos(2*pi*x) + c3*sin(2*pi*y) + c4*cos(2*pi*y) +
c5*sin(4*pi*... | Below is the the instruction that describes the task:
### Input:
This runs EPD on the Kepler light curve.
Following Huang et al. 2015, we fit the following EPD function to a smoothed
light curve, and then subtract it to obtain EPD corrected magnitudes::
f = c0 +
c1*sin(2*pi*x) + c2*cos... |
def tostring(element):
"""Serialize an element and its child nodes to a string"""
rv = []
def serializeElement(element):
if not hasattr(element, "tag"):
if element.docinfo.internalDTD:
if element.docinfo.doctype:
dtd_str = element.docinfo.doctype
... | Serialize an element and its child nodes to a string | Below is the the instruction that describes the task:
### Input:
Serialize an element and its child nodes to a string
### Response:
def tostring(element):
"""Serialize an element and its child nodes to a string"""
rv = []
def serializeElement(element):
if not hasattr(element, "tag"):
... |
def pause_process(self, key):
"""Pause a specific processes."""
if key in self.processes and key not in self.paused:
os.killpg(os.getpgid(self.processes[key].pid), signal.SIGSTOP)
self.queue[key]['status'] = 'paused'
self.paused.append(key)
return True
... | Pause a specific processes. | Below is the the instruction that describes the task:
### Input:
Pause a specific processes.
### Response:
def pause_process(self, key):
"""Pause a specific processes."""
if key in self.processes and key not in self.paused:
os.killpg(os.getpgid(self.processes[key].pid), signal.SIGSTOP)
... |
def _axis_levels(self, axis):
"""
Return the number of levels in the labels taking into account the axis.
Get the number of levels for the columns (0) or rows (1).
"""
ax = self._axis(axis)
return 1 if not hasattr(ax, 'levels') else len(ax.levels) | Return the number of levels in the labels taking into account the axis.
Get the number of levels for the columns (0) or rows (1). | Below is the the instruction that describes the task:
### Input:
Return the number of levels in the labels taking into account the axis.
Get the number of levels for the columns (0) or rows (1).
### Response:
def _axis_levels(self, axis):
"""
Return the number of levels in the labels t... |
def _ReadFixedSizeDataTypeDefinition(
self, definitions_registry, definition_values, data_type_definition_class,
definition_name, supported_attributes,
default_size=definitions.SIZE_NATIVE, default_units='bytes',
is_member=False, supported_size_values=None):
"""Reads a fixed-size data type d... | Reads a fixed-size data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
data_type_definition_class (str): data type definition class.
definition_name (str): name of... | Below is the the instruction that describes the task:
### Input:
Reads a fixed-size data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
data_type_definition_class (s... |
def QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None):
'''
save stock_day
保存日线数据
:param client:
:param ui_log: 给GUI qt 界面使用
:param ui_progress: 给GUI qt 界面使用
:param ui_progress_int_value: 给GUI qt 界面使用
'''
stock_list = QA_fetch_get_stock_list().code.unique().tolist... | save stock_day
保存日线数据
:param client:
:param ui_log: 给GUI qt 界面使用
:param ui_progress: 给GUI qt 界面使用
:param ui_progress_int_value: 给GUI qt 界面使用 | Below is the the instruction that describes the task:
### Input:
save stock_day
保存日线数据
:param client:
:param ui_log: 给GUI qt 界面使用
:param ui_progress: 给GUI qt 界面使用
:param ui_progress_int_value: 给GUI qt 界面使用
### Response:
def QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None):
... |
def get_sql_state(self, state):
"""
Get SQLStateGraph from state.
"""
if not hasattr(state, 'sql_state'):
setattr(state, 'sql_state', SQLStateGraph())
return state.sql_state | Get SQLStateGraph from state. | Below is the the instruction that describes the task:
### Input:
Get SQLStateGraph from state.
### Response:
def get_sql_state(self, state):
"""
Get SQLStateGraph from state.
"""
if not hasattr(state, 'sql_state'):
setattr(state, 'sql_state', SQLStateGraph())
ret... |
def reload(self):
"""Reload catalog if sufficient time has passed"""
if time.time() - self.updated > self.ttl:
self.force_reload() | Reload catalog if sufficient time has passed | Below is the the instruction that describes the task:
### Input:
Reload catalog if sufficient time has passed
### Response:
def reload(self):
"""Reload catalog if sufficient time has passed"""
if time.time() - self.updated > self.ttl:
self.force_reload() |
def intervalleftjoin(left, right, lstart='start', lstop='stop', rstart='start',
rstop='stop', lkey=None, rkey=None, include_stop=False,
missing=None, lprefix=None, rprefix=None):
"""
Like :func:`petl.transform.intervals.intervaljoin` but rows from the left
table wi... | Like :func:`petl.transform.intervals.intervaljoin` but rows from the left
table without a match in the right table are also included. E.g.::
>>> import petl as etl
>>> left = [['begin', 'end', 'quux'],
... [1, 2, 'a'],
... [2, 4, 'b'],
... [2, 5, 'c'... | Below is the the instruction that describes the task:
### Input:
Like :func:`petl.transform.intervals.intervaljoin` but rows from the left
table without a match in the right table are also included. E.g.::
>>> import petl as etl
>>> left = [['begin', 'end', 'quux'],
... [1, 2, ... |
def copy_results(self, copy_to_dir, rename_model_to=None, force_rerun=False):
"""Copy the raw information from I-TASSER modeling to a new folder.
Copies all files in the list _attrs_to_copy.
Args:
copy_to_dir (str): Directory to copy the minimal set of results per sequence.
... | Copy the raw information from I-TASSER modeling to a new folder.
Copies all files in the list _attrs_to_copy.
Args:
copy_to_dir (str): Directory to copy the minimal set of results per sequence.
rename_model_to (str): New file name (without extension)
force_rerun (bo... | Below is the the instruction that describes the task:
### Input:
Copy the raw information from I-TASSER modeling to a new folder.
Copies all files in the list _attrs_to_copy.
Args:
copy_to_dir (str): Directory to copy the minimal set of results per sequence.
rename_model_to... |
def reverseCommit(self):
"""
Replace the current widget content with the original text.
Note that the original text has styling information available,
whereas the new text does not.
"""
self.baseClass.setText(self.oldText)
self.qteWidget.SCISetStylingEx(0, 0, self... | Replace the current widget content with the original text.
Note that the original text has styling information available,
whereas the new text does not. | Below is the the instruction that describes the task:
### Input:
Replace the current widget content with the original text.
Note that the original text has styling information available,
whereas the new text does not.
### Response:
def reverseCommit(self):
"""
Replace the current wi... |
def simxGetOutMessageInfo(clientID, infoType):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
info = ct.c_int()
return c_GetOutMessageInfo(clientID, infoType, ct.byref(info)), info.value | Please have a look at the function description/documentation in the V-REP user manual | Below is the the instruction that describes the task:
### Input:
Please have a look at the function description/documentation in the V-REP user manual
### Response:
def simxGetOutMessageInfo(clientID, infoType):
'''
Please have a look at the function description/documentation in the V-REP user manual
'... |
def change_resource_record_set_writer(connection, change_set, comment=None):
"""
Forms an XML string that we'll send to Route53 in order to change
record sets.
:param Route53Connection connection: The connection instance used to
query the API.
:param change_set.ChangeSet change_set: The Cha... | Forms an XML string that we'll send to Route53 in order to change
record sets.
:param Route53Connection connection: The connection instance used to
query the API.
:param change_set.ChangeSet change_set: The ChangeSet object to create the
XML doc from.
:keyword str comment: An optional c... | Below is the the instruction that describes the task:
### Input:
Forms an XML string that we'll send to Route53 in order to change
record sets.
:param Route53Connection connection: The connection instance used to
query the API.
:param change_set.ChangeSet change_set: The ChangeSet object to cre... |
def deserialize(stream_or_string, **options):
'''
Deserialize any string or stream like object into a Python data structure.
:param stream_or_string: stream or string to deserialize.
:param options: options given to lower configparser module.
'''
if six.PY3:
cp = configparser.ConfigPar... | Deserialize any string or stream like object into a Python data structure.
:param stream_or_string: stream or string to deserialize.
:param options: options given to lower configparser module. | Below is the the instruction that describes the task:
### Input:
Deserialize any string or stream like object into a Python data structure.
:param stream_or_string: stream or string to deserialize.
:param options: options given to lower configparser module.
### Response:
def deserialize(stream_or_string, ... |
def _download_vswhere():
"""
Download vswhere to DOWNLOAD_PATH.
"""
print('downloading from', _get_latest_release_url())
try:
from urllib.request import urlopen
with urlopen(_get_latest_release_url()) as response, open(DOWNLOAD_PATH, 'wb') as outfile:
shutil.copyfileobj(r... | Download vswhere to DOWNLOAD_PATH. | Below is the the instruction that describes the task:
### Input:
Download vswhere to DOWNLOAD_PATH.
### Response:
def _download_vswhere():
"""
Download vswhere to DOWNLOAD_PATH.
"""
print('downloading from', _get_latest_release_url())
try:
from urllib.request import urlopen
with... |
def get_pmids(self):
"""Get list of all PMIDs associated with edges in the network."""
pmids = []
for ea in self._edge_attributes.values():
edge_pmids = ea.get('pmids')
if edge_pmids:
pmids += edge_pmids
return list(set(pmids)) | Get list of all PMIDs associated with edges in the network. | Below is the the instruction that describes the task:
### Input:
Get list of all PMIDs associated with edges in the network.
### Response:
def get_pmids(self):
"""Get list of all PMIDs associated with edges in the network."""
pmids = []
for ea in self._edge_attributes.values():
... |
def getPrioritySortkey(self):
"""
Returns the key that will be used to sort the current Analysis, from
most prioritary to less prioritary.
:return: string used for sorting
"""
analysis_request = self.getRequest()
if analysis_request is None:
return Non... | Returns the key that will be used to sort the current Analysis, from
most prioritary to less prioritary.
:return: string used for sorting | Below is the the instruction that describes the task:
### Input:
Returns the key that will be used to sort the current Analysis, from
most prioritary to less prioritary.
:return: string used for sorting
### Response:
def getPrioritySortkey(self):
"""
Returns the key that will be use... |
def transform(self, X):
"""Transform X according to the fitted transformer.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input vectors, where n_samples is the number of samples
and n_features is the number of features.
Returns
... | Transform X according to the fitted transformer.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input vectors, where n_samples is the number of samples
and n_features is the number of features.
Returns
-------
X_new : array... | Below is the the instruction that describes the task:
### Input:
Transform X according to the fitted transformer.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input vectors, where n_samples is the number of samples
and n_features is the numbe... |
def google_poem(self, message, topic):
"""make a poem about __: show a google poem about __"""
r = requests.get("http://www.google.com/complete/search?output=toolbar&q=" + topic + "%20")
xmldoc = minidom.parseString(r.text)
item_list = xmldoc.getElementsByTagName("suggestion")
co... | make a poem about __: show a google poem about __ | Below is the the instruction that describes the task:
### Input:
make a poem about __: show a google poem about __
### Response:
def google_poem(self, message, topic):
"""make a poem about __: show a google poem about __"""
r = requests.get("http://www.google.com/complete/search?output=toolbar&q=" ... |
def append(self, report):
"""Append a new CSP report."""
assert report not in self.examples
self.count += 1
if len(self.examples) < self.top:
self.examples.append(report) | Append a new CSP report. | Below is the the instruction that describes the task:
### Input:
Append a new CSP report.
### Response:
def append(self, report):
"""Append a new CSP report."""
assert report not in self.examples
self.count += 1
if len(self.examples) < self.top:
self.examples.append(repo... |
def getExim(exim_id):
"""Returns the instrument interface for the exim_id passed in
"""
interfaces = filter(lambda i: i[0]==exim_id, get_instrument_interfaces())
return interfaces and interfaces[0][1] or None | Returns the instrument interface for the exim_id passed in | Below is the the instruction that describes the task:
### Input:
Returns the instrument interface for the exim_id passed in
### Response:
def getExim(exim_id):
"""Returns the instrument interface for the exim_id passed in
"""
interfaces = filter(lambda i: i[0]==exim_id, get_instrument_interfaces())
... |
def delete_hook(self, id):
"""
:calls: `DELETE /orgs/:owner/hooks/:id <http://developer.github.com/v3/orgs/hooks>`_
:param id: integer
:rtype: None`
"""
assert isinstance(id, (int, long)), id
headers, data = self._requester.requestJsonAndCheck(
"DELETE... | :calls: `DELETE /orgs/:owner/hooks/:id <http://developer.github.com/v3/orgs/hooks>`_
:param id: integer
:rtype: None` | Below is the the instruction that describes the task:
### Input:
:calls: `DELETE /orgs/:owner/hooks/:id <http://developer.github.com/v3/orgs/hooks>`_
:param id: integer
:rtype: None`
### Response:
def delete_hook(self, id):
"""
:calls: `DELETE /orgs/:owner/hooks/:id <http://develope... |
def repr_part(self):
"""String usable in a space's ``__repr__`` method."""
optargs = [('weighting', array_str(self.array, nprint=10), ''),
('exponent', self.exponent, 2.0)]
return signature_string([], optargs, sep=',\n',
mod=[[], ['!s', ':.4']]) | String usable in a space's ``__repr__`` method. | Below is the the instruction that describes the task:
### Input:
String usable in a space's ``__repr__`` method.
### Response:
def repr_part(self):
"""String usable in a space's ``__repr__`` method."""
optargs = [('weighting', array_str(self.array, nprint=10), ''),
('exponent', s... |
def calc_periods(hour=0, minute=0):
"""Returns a tuple of start_period and end_period.
Assumes that the period is 24-hrs.
Parameters:
- `hour`: the hour from 0 to 23 when the period ends
- `minute`: the minute from 0 to 59 when the period ends
This method will calculate the end of the p... | Returns a tuple of start_period and end_period.
Assumes that the period is 24-hrs.
Parameters:
- `hour`: the hour from 0 to 23 when the period ends
- `minute`: the minute from 0 to 59 when the period ends
This method will calculate the end of the period as the closest hour/minute
going ... | Below is the the instruction that describes the task:
### Input:
Returns a tuple of start_period and end_period.
Assumes that the period is 24-hrs.
Parameters:
- `hour`: the hour from 0 to 23 when the period ends
- `minute`: the minute from 0 to 59 when the period ends
This method will ... |
def send_post(self, mri, method_name, **params):
"""Abstract method to dispatch a Post to the server
Args:
mri (str): The mri of the Block
method_name (str): The name of the Method within the Block
params: The parameters to send
Returns:
The retu... | Abstract method to dispatch a Post to the server
Args:
mri (str): The mri of the Block
method_name (str): The name of the Method within the Block
params: The parameters to send
Returns:
The return results from the server | Below is the the instruction that describes the task:
### Input:
Abstract method to dispatch a Post to the server
Args:
mri (str): The mri of the Block
method_name (str): The name of the Method within the Block
params: The parameters to send
Returns:
... |
def put_settings(self, app=None, index=None, settings=None, es=None):
"""Modify index settings.
Index must exist already.
"""
if not index:
index = self.index
if not app:
app = self.app
if not es:
es = self.es
if not setting... | Modify index settings.
Index must exist already. | Below is the the instruction that describes the task:
### Input:
Modify index settings.
Index must exist already.
### Response:
def put_settings(self, app=None, index=None, settings=None, es=None):
"""Modify index settings.
Index must exist already.
"""
if not index:
... |
def create_serv_obj(self, tenant_id):
"""Creates and stores the service object associated with a tenant. """
self.service_attr[tenant_id] = ServiceIpSegTenantMap()
self.store_tenant_obj(tenant_id, self.service_attr[tenant_id]) | Creates and stores the service object associated with a tenant. | Below is the the instruction that describes the task:
### Input:
Creates and stores the service object associated with a tenant.
### Response:
def create_serv_obj(self, tenant_id):
"""Creates and stores the service object associated with a tenant. """
self.service_attr[tenant_id] = ServiceIpSegTena... |
def write_output_files(self, fh):
"""
Write as a comment into the DAG file the list of output files
for this DAG node.
@param fh: descriptor of open DAG file.
"""
for f in self.__output_files:
print >>fh, "## Job %s generates output file %s" % (self.__name, f) | Write as a comment into the DAG file the list of output files
for this DAG node.
@param fh: descriptor of open DAG file. | Below is the the instruction that describes the task:
### Input:
Write as a comment into the DAG file the list of output files
for this DAG node.
@param fh: descriptor of open DAG file.
### Response:
def write_output_files(self, fh):
"""
Write as a comment into the DAG file the list of output file... |
def label(self) -> str:
"""A latex formatted label representing constant expression and united value."""
label = self.expression.replace("_", "\\;")
if self.units_kind:
symbol = wt_units.get_symbol(self.units)
for v in self.variables:
vl = "%s_{%s}" % (sym... | A latex formatted label representing constant expression and united value. | Below is the the instruction that describes the task:
### Input:
A latex formatted label representing constant expression and united value.
### Response:
def label(self) -> str:
"""A latex formatted label representing constant expression and united value."""
label = self.expression.replace("_", "\\... |
def _urls(self):
"""Constructs the URLconf for Horizon from registered Dashboards."""
urlpatterns = self._get_default_urlpatterns()
self._autodiscover()
# Discover each dashboard's panels.
for dash in self._registry.values():
dash._autodiscover()
# Load the ... | Constructs the URLconf for Horizon from registered Dashboards. | Below is the the instruction that describes the task:
### Input:
Constructs the URLconf for Horizon from registered Dashboards.
### Response:
def _urls(self):
"""Constructs the URLconf for Horizon from registered Dashboards."""
urlpatterns = self._get_default_urlpatterns()
self._autodiscove... |
def generate_random_nhs_number() -> int:
"""
Returns a random valid NHS number, as an ``int``.
"""
check_digit = 10 # NHS numbers with this check digit are all invalid
while check_digit == 10:
digits = [random.randint(1, 9)] # don't start with a zero
digits.extend([random.randint(0... | Returns a random valid NHS number, as an ``int``. | Below is the the instruction that describes the task:
### Input:
Returns a random valid NHS number, as an ``int``.
### Response:
def generate_random_nhs_number() -> int:
"""
Returns a random valid NHS number, as an ``int``.
"""
check_digit = 10 # NHS numbers with this check digit are all invalid
... |
def fetch_file(
download_url,
filename=None,
decompress=False,
subdir=None,
force=False,
timeout=None,
use_wget_if_available=False):
"""
Download a remote file and store it locally in a cache directory. Don't
download it again if it's already present (... | Download a remote file and store it locally in a cache directory. Don't
download it again if it's already present (unless `force` is True.)
Parameters
----------
download_url : str
Remote URL of file to download.
filename : str, optional
Local filename, used as cache key. If omitte... | Below is the the instruction that describes the task:
### Input:
Download a remote file and store it locally in a cache directory. Don't
download it again if it's already present (unless `force` is True.)
Parameters
----------
download_url : str
Remote URL of file to download.
filename... |
def _save_assignment(self, node, name=None):
"""save assignement situation since node.parent is not available yet"""
if self._global_names and node.name in self._global_names[-1]:
node.root().set_local(node.name, node)
else:
node.parent.set_local(node.name, node) | save assignement situation since node.parent is not available yet | Below is the the instruction that describes the task:
### Input:
save assignement situation since node.parent is not available yet
### Response:
def _save_assignment(self, node, name=None):
"""save assignement situation since node.parent is not available yet"""
if self._global_names and node.name i... |
def aggregate(d, y_size, x_size):
"""Average every 4 elements (2x2) in a 2D array"""
if d.ndim != 2:
# we can't guarantee what blocks we are getting and how
# it should be reshaped to do the averaging.
raise ValueError("Can't aggregrate (reduce) data arrays with "
... | Average every 4 elements (2x2) in a 2D array | Below is the the instruction that describes the task:
### Input:
Average every 4 elements (2x2) in a 2D array
### Response:
def aggregate(d, y_size, x_size):
"""Average every 4 elements (2x2) in a 2D array"""
if d.ndim != 2:
# we can't guarantee what blocks we are getting and how
... |
def _to_zip_product(sweep: Sweep) -> Product:
"""Converts sweep to a product of zips of single sweeps, if possible."""
if not isinstance(sweep, Product):
sweep = Product(sweep)
if not all(isinstance(f, Zip) for f in sweep.factors):
factors = [f if isinstance(f, Zip) else Zip(f) for f in swee... | Converts sweep to a product of zips of single sweeps, if possible. | Below is the the instruction that describes the task:
### Input:
Converts sweep to a product of zips of single sweeps, if possible.
### Response:
def _to_zip_product(sweep: Sweep) -> Product:
"""Converts sweep to a product of zips of single sweeps, if possible."""
if not isinstance(sweep, Product):
... |
def patch_config(config, data):
"""recursively 'patch' `config` with `data`
:returns: `!True` if the `config` was changed"""
is_changed = False
for name, value in data.items():
if value is None:
if config.pop(name, None) is not None:
is_changed = True
elif nam... | recursively 'patch' `config` with `data`
:returns: `!True` if the `config` was changed | Below is the the instruction that describes the task:
### Input:
recursively 'patch' `config` with `data`
:returns: `!True` if the `config` was changed
### Response:
def patch_config(config, data):
"""recursively 'patch' `config` with `data`
:returns: `!True` if the `config` was changed"""
is_chang... |
def url_unescape( # noqa: F811
value: Union[str, bytes], encoding: Optional[str] = "utf-8", plus: bool = True
) -> Union[str, bytes]:
"""Decodes the given value from a URL.
The argument may be either a byte or unicode string.
If encoding is None, the result will be a byte string. Otherwise,
the ... | Decodes the given value from a URL.
The argument may be either a byte or unicode string.
If encoding is None, the result will be a byte string. Otherwise,
the result is a unicode string in the specified encoding.
If ``plus`` is true (the default), plus signs will be interpreted
as spaces (litera... | Below is the the instruction that describes the task:
### Input:
Decodes the given value from a URL.
The argument may be either a byte or unicode string.
If encoding is None, the result will be a byte string. Otherwise,
the result is a unicode string in the specified encoding.
If ``plus`` is tru... |
def server_socket(self, config):
""" :meth:`.WNetworkNativeTransportProto.server_socket` method implementation
"""
if self.__server_socket is None:
self.__server_socket = self.create_server_socket(config)
self.__server_socket.bind(self.bind_socket(config).pair())
return self.__server_socket | :meth:`.WNetworkNativeTransportProto.server_socket` method implementation | Below is the the instruction that describes the task:
### Input:
:meth:`.WNetworkNativeTransportProto.server_socket` method implementation
### Response:
def server_socket(self, config):
""" :meth:`.WNetworkNativeTransportProto.server_socket` method implementation
"""
if self.__server_socket is None:
self.... |
def list_secties_by_afdeling(self, afdeling):
'''
List all `secties` in a `kadastrale afdeling`.
:param afdeling: The :class:`Afdeling` for which the `secties` are \
wanted. Can also be the id of and `afdeling`.
:rtype: A :class:`list` of `Sectie`.
'''
try:
... | List all `secties` in a `kadastrale afdeling`.
:param afdeling: The :class:`Afdeling` for which the `secties` are \
wanted. Can also be the id of and `afdeling`.
:rtype: A :class:`list` of `Sectie`. | Below is the the instruction that describes the task:
### Input:
List all `secties` in a `kadastrale afdeling`.
:param afdeling: The :class:`Afdeling` for which the `secties` are \
wanted. Can also be the id of and `afdeling`.
:rtype: A :class:`list` of `Sectie`.
### Response:
def list... |
def get_manifest_from_meta(metaurl, name):
"""
Extact manifest url from metadata url
:param metaurl: Url to metadata
:param name: Name of application to extract
:return:
"""
if 'http' in metaurl:
kit = yaml.safe_load(requests.get(url=metaurl).content)['kit']['applications']
else:... | Extact manifest url from metadata url
:param metaurl: Url to metadata
:param name: Name of application to extract
:return: | Below is the the instruction that describes the task:
### Input:
Extact manifest url from metadata url
:param metaurl: Url to metadata
:param name: Name of application to extract
:return:
### Response:
def get_manifest_from_meta(metaurl, name):
"""
Extact manifest url from metadata url
:par... |
def get_display(display):
"""dname, protocol, host, dno, screen = get_display(display)
Parse DISPLAY into its components. If DISPLAY is None, use
the default display. The return values are:
DNAME -- the full display name (string)
PROTOCOL -- the protocol to use (None if automatic)
H... | dname, protocol, host, dno, screen = get_display(display)
Parse DISPLAY into its components. If DISPLAY is None, use
the default display. The return values are:
DNAME -- the full display name (string)
PROTOCOL -- the protocol to use (None if automatic)
HOST -- the host name (string,... | Below is the the instruction that describes the task:
### Input:
dname, protocol, host, dno, screen = get_display(display)
Parse DISPLAY into its components. If DISPLAY is None, use
the default display. The return values are:
DNAME -- the full display name (string)
PROTOCOL -- the protoco... |
def switch(self, *args):
"""
Method that attempts to change the switch to the opposite of its
current state. Calls either switch_on() or switch_off() to accomplish
this.
:param kwargs: an variable length dictionary of key-pair arguments
passed through to either switc... | Method that attempts to change the switch to the opposite of its
current state. Calls either switch_on() or switch_off() to accomplish
this.
:param kwargs: an variable length dictionary of key-pair arguments
passed through to either switch_on() or switch_off()
:return: Boole... | Below is the the instruction that describes the task:
### Input:
Method that attempts to change the switch to the opposite of its
current state. Calls either switch_on() or switch_off() to accomplish
this.
:param kwargs: an variable length dictionary of key-pair arguments
passed... |
def get_lb_conn(dd_driver=None):
'''
Return a load-balancer conn object
'''
vm_ = get_configured_provider()
region = config.get_cloud_config_value(
'region', vm_, __opts__
)
user_id = config.get_cloud_config_value(
'user_id', vm_, __opts__
)
key = config.get_cloud_co... | Return a load-balancer conn object | Below is the the instruction that describes the task:
### Input:
Return a load-balancer conn object
### Response:
def get_lb_conn(dd_driver=None):
'''
Return a load-balancer conn object
'''
vm_ = get_configured_provider()
region = config.get_cloud_config_value(
'region', vm_, __opts__
... |
def list_runners(*args):
'''
List the runners loaded on the minion
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' sys.list_runners
Runner names can be specified as globs.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' sys.list_runn... | List the runners loaded on the minion
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' sys.list_runners
Runner names can be specified as globs.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' sys.list_runners 'm*' | Below is the the instruction that describes the task:
### Input:
List the runners loaded on the minion
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' sys.list_runners
Runner names can be specified as globs.
.. versionadded:: 2015.5.0
.. code-block:: bash... |
def coalesce(self):
"""Merge contiguous elements of this list into single objects
This method implicitly sorts and potentially shortens this list.
"""
self.sort(key=lambda ts: ts.t0.value)
i = j = 0
N = len(self)
while j < N:
this = self[j]
... | Merge contiguous elements of this list into single objects
This method implicitly sorts and potentially shortens this list. | Below is the the instruction that describes the task:
### Input:
Merge contiguous elements of this list into single objects
This method implicitly sorts and potentially shortens this list.
### Response:
def coalesce(self):
"""Merge contiguous elements of this list into single objects
This... |
def base_elts(elt, cls=None, depth=None):
"""Get bases elements of the input elt.
- If elt is an instance, get class and all base classes.
- If elt is a method, get all base methods.
- If elt is a class, get all base classes.
- In other case, get an empty list.
:param elt: supposed inherited e... | Get bases elements of the input elt.
- If elt is an instance, get class and all base classes.
- If elt is a method, get all base methods.
- If elt is a class, get all base classes.
- In other case, get an empty list.
:param elt: supposed inherited elt.
:param cls: cls from where find attribute... | Below is the the instruction that describes the task:
### Input:
Get bases elements of the input elt.
- If elt is an instance, get class and all base classes.
- If elt is a method, get all base methods.
- If elt is a class, get all base classes.
- In other case, get an empty list.
:param elt: ... |
def line_statuses(self, filename):
"""
Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (line hit) or `F... | Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (line hit) or `False` (line miss). | Below is the the instruction that describes the task:
### Input:
Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (l... |
def clear(self):
"""Clear the statement_group, citation, evidence, and annotations."""
self.statement_group = None
self.citation.clear()
self.evidence = None
self.annotations.clear() | Clear the statement_group, citation, evidence, and annotations. | Below is the the instruction that describes the task:
### Input:
Clear the statement_group, citation, evidence, and annotations.
### Response:
def clear(self):
"""Clear the statement_group, citation, evidence, and annotations."""
self.statement_group = None
self.citation.clear()
sel... |
def remove_scope_ip(hostid, auth, url):
"""
Function to add remove IP address allocation
:param hostid: Host id of the host to be deleted
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.au... | Function to add remove IP address allocation
:param hostid: Host id of the host to be deleted
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: String of HTTP response c... | Below is the the instruction that describes the task:
### Input:
Function to add remove IP address allocation
:param hostid: Host id of the host to be deleted
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url... |
def _draw_rect(ax:plt.Axes, b:Collection[int], color:str='white', text=None, text_size=14):
"Draw bounding box on `ax`."
patch = ax.add_patch(patches.Rectangle(b[:2], *b[-2:], fill=False, edgecolor=color, lw=2))
_draw_outline(patch, 4)
if text is not None:
patch = ax.text(*b[:2], text, verticala... | Draw bounding box on `ax`. | Below is the the instruction that describes the task:
### Input:
Draw bounding box on `ax`.
### Response:
def _draw_rect(ax:plt.Axes, b:Collection[int], color:str='white', text=None, text_size=14):
"Draw bounding box on `ax`."
patch = ax.add_patch(patches.Rectangle(b[:2], *b[-2:], fill=False, edgecolor=col... |
def config_to_api_list(dic):
"""
Converts a python dictionary into a list containing the proper
ApiConfig encoding for configuration data.
@param dic: Key-value pairs to convert.
@return: JSON dictionary of an ApiConfig list (*not* an ApiList).
"""
config = [ ]
for k, v in dic.iteritems():
config.a... | Converts a python dictionary into a list containing the proper
ApiConfig encoding for configuration data.
@param dic: Key-value pairs to convert.
@return: JSON dictionary of an ApiConfig list (*not* an ApiList). | Below is the the instruction that describes the task:
### Input:
Converts a python dictionary into a list containing the proper
ApiConfig encoding for configuration data.
@param dic: Key-value pairs to convert.
@return: JSON dictionary of an ApiConfig list (*not* an ApiList).
### Response:
def config_to_api... |
def invoke(proc, args=None, *, _instance = None, **kwargs):
"""
Executes the processor passing given arguments.
:param args: a list of parameters in --key=value format.
"""
if args is None:
args=[]
for kwargname in kwargs:
args.append('--'+kwargna... | Executes the processor passing given arguments.
:param args: a list of parameters in --key=value format. | Below is the the instruction that describes the task:
### Input:
Executes the processor passing given arguments.
:param args: a list of parameters in --key=value format.
### Response:
def invoke(proc, args=None, *, _instance = None, **kwargs):
"""
Executes the processor passing given argum... |
def read_losc_hdf5_state(f, path='quality/simple', start=None, end=None,
copy=False):
"""Read a `StateVector` from a LOSC-format HDF file.
Parameters
----------
f : `str`, `h5py.HLObject`
path of HDF5 file, or open `H5File`
path : `str`
path of HDF5 dataset... | Read a `StateVector` from a LOSC-format HDF file.
Parameters
----------
f : `str`, `h5py.HLObject`
path of HDF5 file, or open `H5File`
path : `str`
path of HDF5 dataset to read.
start : `Time`, `~gwpy.time.LIGOTimeGPS`, optional
start GPS time of desired data
end : `T... | Below is the the instruction that describes the task:
### Input:
Read a `StateVector` from a LOSC-format HDF file.
Parameters
----------
f : `str`, `h5py.HLObject`
path of HDF5 file, or open `H5File`
path : `str`
path of HDF5 dataset to read.
start : `Time`, `~gwpy.time.LIGOTi... |
def getCredentials(self, request):
"""
Derive credentials from an HTTP request.
Override SessionWrapper.getCredentials to add the Host: header to the
credentials. This will make web-based virtual hosting work.
@type request: L{nevow.inevow.IRequest}
@param request: The... | Derive credentials from an HTTP request.
Override SessionWrapper.getCredentials to add the Host: header to the
credentials. This will make web-based virtual hosting work.
@type request: L{nevow.inevow.IRequest}
@param request: The request being handled.
@rtype: L{twisted.cred... | Below is the the instruction that describes the task:
### Input:
Derive credentials from an HTTP request.
Override SessionWrapper.getCredentials to add the Host: header to the
credentials. This will make web-based virtual hosting work.
@type request: L{nevow.inevow.IRequest}
@para... |
def setCurrentPlugin( self, plugin ):
"""
Sets the current plugin item to the inputed plugin.
:param plugin | <XConfigPlugin> || None
"""
if ( not plugin ):
self.uiPluginTREE.setCurrentItem(None)
return
for i in range(sel... | Sets the current plugin item to the inputed plugin.
:param plugin | <XConfigPlugin> || None | Below is the the instruction that describes the task:
### Input:
Sets the current plugin item to the inputed plugin.
:param plugin | <XConfigPlugin> || None
### Response:
def setCurrentPlugin( self, plugin ):
"""
Sets the current plugin item to the inputed plugin.
... |
def update_todo_item(self, item_id, content, party_id=None, notify=False):
"""
Modifies an existing item. The values work much like the "create item"
operation, so you should refer to that for a more detailed explanation.
"""
path = '/todos/update_item/%u' % item_id
req =... | Modifies an existing item. The values work much like the "create item"
operation, so you should refer to that for a more detailed explanation. | Below is the the instruction that describes the task:
### Input:
Modifies an existing item. The values work much like the "create item"
operation, so you should refer to that for a more detailed explanation.
### Response:
def update_todo_item(self, item_id, content, party_id=None, notify=False):
""... |
def _delete_empty_properties(self, properties):
"""
Delete empty properties before serialization to avoid
extra keys with empty values in the output json.
"""
if not self.parent_id:
del properties['parent_id']
if not self.subsegments:
del propertie... | Delete empty properties before serialization to avoid
extra keys with empty values in the output json. | Below is the the instruction that describes the task:
### Input:
Delete empty properties before serialization to avoid
extra keys with empty values in the output json.
### Response:
def _delete_empty_properties(self, properties):
"""
Delete empty properties before serialization to avoid
... |
def pop(self, key, default=None):
""" Get item from the dict and remove it.
Return default if expired or does not exist. Never raise KeyError.
"""
with self.lock:
try:
item = OrderedDict.__getitem__(self, key)
del self[key]
ret... | Get item from the dict and remove it.
Return default if expired or does not exist. Never raise KeyError. | Below is the the instruction that describes the task:
### Input:
Get item from the dict and remove it.
Return default if expired or does not exist. Never raise KeyError.
### Response:
def pop(self, key, default=None):
""" Get item from the dict and remove it.
Return default if expired or ... |
def check_folder_exists(project, path, folder_name):
'''
:param project: project id
:type project: string
:param path: path to where we should look for the folder in question
:type path: string
:param folder_name: name of the folder in question
:type folder_name: string
:returns: A boole... | :param project: project id
:type project: string
:param path: path to where we should look for the folder in question
:type path: string
:param folder_name: name of the folder in question
:type folder_name: string
:returns: A boolean True or False whether the folder exists at the specified path
... | Below is the the instruction that describes the task:
### Input:
:param project: project id
:type project: string
:param path: path to where we should look for the folder in question
:type path: string
:param folder_name: name of the folder in question
:type folder_name: string
:returns: A b... |
def _writeMapTable(self, session, fileObject, mapTable, replaceParamFile):
"""
Write Generic Map Table Method
This method writes a mapping table in the generic format to file. The method will handle
both empty and filled cases of generic formatted mapping tables.
session = SQLA... | Write Generic Map Table Method
This method writes a mapping table in the generic format to file. The method will handle
both empty and filled cases of generic formatted mapping tables.
session = SQLAlchemy session object for retrieving data from the database
fileObject = The file objec... | Below is the the instruction that describes the task:
### Input:
Write Generic Map Table Method
This method writes a mapping table in the generic format to file. The method will handle
both empty and filled cases of generic formatted mapping tables.
session = SQLAlchemy session object for ... |
def get_user(self, id=None, name=None, email=None):
""" Get user object by email or id.
"""
log.info("Picking user: %s (%s) (%s)" % (name, email, id))
from qubell.api.private.user import User
if email:
user = User.get(self._router, organization=self, email=email)
... | Get user object by email or id. | Below is the the instruction that describes the task:
### Input:
Get user object by email or id.
### Response:
def get_user(self, id=None, name=None, email=None):
""" Get user object by email or id.
"""
log.info("Picking user: %s (%s) (%s)" % (name, email, id))
from qubell.api.priva... |
def _deserialize(self, value, environment=None):
"""A collection traverses over something to deserialize its value.
:param value: a ``dict`` wich contains mapped values
"""
if not isinstance(value, MappingABC):
raise exc.Invalid(self)
# traverse items and match aga... | A collection traverses over something to deserialize its value.
:param value: a ``dict`` wich contains mapped values | Below is the the instruction that describes the task:
### Input:
A collection traverses over something to deserialize its value.
:param value: a ``dict`` wich contains mapped values
### Response:
def _deserialize(self, value, environment=None):
"""A collection traverses over something to deseriali... |
def StateOfCharge(self):
""" % of Full Charge """
return (self.bus.read_byte_data(self.address, 0x02) + self.bus.read_byte_data(self.address, 0x03) * 256) | % of Full Charge | Below is the the instruction that describes the task:
### Input:
% of Full Charge
### Response:
def StateOfCharge(self):
""" % of Full Charge """
return (self.bus.read_byte_data(self.address, 0x02) + self.bus.read_byte_data(self.address, 0x03) * 256) |
def insert_sequences_into_tree(aln, moltype, params={},
write_log=True):
"""Returns a tree from Alignment object aln.
aln: an xxx.Alignment object, or data that can be used to build one.
moltype: cogent.core.moltype.MolType object
params: dict of parameters ... | Returns a tree from Alignment object aln.
aln: an xxx.Alignment object, or data that can be used to build one.
moltype: cogent.core.moltype.MolType object
params: dict of parameters to pass in to the RAxML app controller.
The result will be an xxx.Alignment object, or None if tree fails. | Below is the the instruction that describes the task:
### Input:
Returns a tree from Alignment object aln.
aln: an xxx.Alignment object, or data that can be used to build one.
moltype: cogent.core.moltype.MolType object
params: dict of parameters to pass in to the RAxML app controller.
The resul... |
def find_text(self, text, changed=True, forward=True, case=False,
words=False, regexp=False):
"""Find text"""
cursor = self.textCursor()
findflag = QTextDocument.FindFlag()
if not forward:
findflag = findflag | QTextDocument.FindBackward
i... | Find text | Below is the the instruction that describes the task:
### Input:
Find text
### Response:
def find_text(self, text, changed=True, forward=True, case=False,
words=False, regexp=False):
"""Find text"""
cursor = self.textCursor()
findflag = QTextDocument.FindFlag()
... |
def sample_dynamic_posterior(self, inputs, samples, static_sample=None):
"""Sample the static latent posterior.
Args:
inputs: A batch of intermediate representations of image frames
across all timesteps, of shape [..., batch_size, timesteps,
hidden_size].
samples: Number of samples ... | Sample the static latent posterior.
Args:
inputs: A batch of intermediate representations of image frames
across all timesteps, of shape [..., batch_size, timesteps,
hidden_size].
samples: Number of samples to draw from the latent distribution.
static_sample: A tensor sample of th... | Below is the the instruction that describes the task:
### Input:
Sample the static latent posterior.
Args:
inputs: A batch of intermediate representations of image frames
across all timesteps, of shape [..., batch_size, timesteps,
hidden_size].
samples: Number of samples to draw fro... |
def get_rendition_fit_size(spec, input_w, input_h, output_scale):
""" Determine the scaled size based on the provided spec """
width = input_w
height = input_h
scale = spec.get('scale')
if scale:
width = width / scale
height = height / scale
min... | Determine the scaled size based on the provided spec | Below is the the instruction that describes the task:
### Input:
Determine the scaled size based on the provided spec
### Response:
def get_rendition_fit_size(spec, input_w, input_h, output_scale):
""" Determine the scaled size based on the provided spec """
width = input_w
height = input_... |
def load_object(imp_path):
'''
Given a python import path, load the object
For dynamic imports in a program
>>> isdir = load_object('os.path.isdir')
>>> isdir('/tmp')
True
>>> num = load_object('numbers.Number')
>>> isinstance('x', num)
False
>>> isinstance(777, num)
True
... | Given a python import path, load the object
For dynamic imports in a program
>>> isdir = load_object('os.path.isdir')
>>> isdir('/tmp')
True
>>> num = load_object('numbers.Number')
>>> isinstance('x', num)
False
>>> isinstance(777, num)
True | Below is the the instruction that describes the task:
### Input:
Given a python import path, load the object
For dynamic imports in a program
>>> isdir = load_object('os.path.isdir')
>>> isdir('/tmp')
True
>>> num = load_object('numbers.Number')
>>> isinstance('x', num)
False
>>> i... |
def near(self, center, sphere=False, min=None, max=None):
"""Order results by their distance from the given point, optionally with range limits in meters.
Geospatial operator: {$near: {...}}
Documentation: https://docs.mongodb.com/manual/reference/operator/query/near/#op._S_near
{
$near: {
$geom... | Order results by their distance from the given point, optionally with range limits in meters.
Geospatial operator: {$near: {...}}
Documentation: https://docs.mongodb.com/manual/reference/operator/query/near/#op._S_near
{
$near: {
$geometry: <center; Point or (long, lat)>,
$minDistance: <min; ... | Below is the the instruction that describes the task:
### Input:
Order results by their distance from the given point, optionally with range limits in meters.
Geospatial operator: {$near: {...}}
Documentation: https://docs.mongodb.com/manual/reference/operator/query/near/#op._S_near
{
$near: {
... |
def get_aoi(self, solar_zenith, solar_azimuth):
"""Get the angle of incidence on the system.
Parameters
----------
solar_zenith : float or Series.
Solar zenith angle.
solar_azimuth : float or Series.
Solar azimuth angle.
Returns
-------
... | Get the angle of incidence on the system.
Parameters
----------
solar_zenith : float or Series.
Solar zenith angle.
solar_azimuth : float or Series.
Solar azimuth angle.
Returns
-------
aoi : Series
The angle of incidence | Below is the the instruction that describes the task:
### Input:
Get the angle of incidence on the system.
Parameters
----------
solar_zenith : float or Series.
Solar zenith angle.
solar_azimuth : float or Series.
Solar azimuth angle.
Returns
... |
def run_process(self, process):
"""Runs a single action."""
message = u'#{bright}'
message += u'{} '.format(str(process)[:68]).ljust(69, '.')
stashed = False
if self.unstaged_changes and not self.include_unstaged_changes:
out, err, code = self.git.stash(keep_index=Tr... | Runs a single action. | Below is the the instruction that describes the task:
### Input:
Runs a single action.
### Response:
def run_process(self, process):
"""Runs a single action."""
message = u'#{bright}'
message += u'{} '.format(str(process)[:68]).ljust(69, '.')
stashed = False
if self.unstage... |
def add_typeattr(typeattr,**kwargs):
"""
Add an typeattr to an existing type.
"""
tmpltype = get_templatetype(typeattr.type_id, user_id=kwargs.get('user_id'))
ta = _set_typeattr(typeattr)
tmpltype.typeattrs.append(ta)
db.DBSession.flush()
return ta | Add an typeattr to an existing type. | Below is the the instruction that describes the task:
### Input:
Add an typeattr to an existing type.
### Response:
def add_typeattr(typeattr,**kwargs):
"""
Add an typeattr to an existing type.
"""
tmpltype = get_templatetype(typeattr.type_id, user_id=kwargs.get('user_id'))
ta = _set_type... |
def genderize(name, api_token=None):
"""Fetch gender from genderize.io"""
GENDERIZE_API_URL = "https://api.genderize.io/"
TOTAL_RETRIES = 10
MAX_RETRIES = 5
SLEEP_TIME = 0.25
STATUS_FORCELIST = [502]
params = {
'name': name
}
if api_token:
params['apikey'] = api_to... | Fetch gender from genderize.io | Below is the the instruction that describes the task:
### Input:
Fetch gender from genderize.io
### Response:
def genderize(name, api_token=None):
"""Fetch gender from genderize.io"""
GENDERIZE_API_URL = "https://api.genderize.io/"
TOTAL_RETRIES = 10
MAX_RETRIES = 5
SLEEP_TIME = 0.25
STATU... |
def fill_archive(self, stream=None, kind='tgz', prefix=None,
subrepos=False):
"""
Fills up given stream.
:param stream: file like object.
:param kind: one of following: ``zip``, ``tgz`` or ``tbz2``.
Default: ``tgz``.
:param prefix: name of root d... | Fills up given stream.
:param stream: file like object.
:param kind: one of following: ``zip``, ``tgz`` or ``tbz2``.
Default: ``tgz``.
:param prefix: name of root directory in archive.
Default is repository name and changeset's raw_id joined with dash
(``repo... | Below is the the instruction that describes the task:
### Input:
Fills up given stream.
:param stream: file like object.
:param kind: one of following: ``zip``, ``tgz`` or ``tbz2``.
Default: ``tgz``.
:param prefix: name of root directory in archive.
Default is reposi... |
def extract(self, text: str, get_attr=['PERSON', 'ORG', 'GPE']) -> List[Extraction]:
"""
Args:
text (str): the text to extract from.
get_attr (List[str]): The spaCy NER attributes we're interested in.
Returns:
List(Extraction): the list of extraction or the e... | Args:
text (str): the text to extract from.
get_attr (List[str]): The spaCy NER attributes we're interested in.
Returns:
List(Extraction): the list of extraction or the empty list if there are no matches. | Below is the the instruction that describes the task:
### Input:
Args:
text (str): the text to extract from.
get_attr (List[str]): The spaCy NER attributes we're interested in.
Returns:
List(Extraction): the list of extraction or the empty list if there are no matches.
#... |
def _read_data_type_2(self, length):
"""Read IPv6-Route Type 2 data.
Structure of IPv6-Route Type 2 data [RFC 6275]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len=2 | Routing Type=2|Segments Left=1|
+-+-+-+-+-+-+-+-+-... | Read IPv6-Route Type 2 data.
Structure of IPv6-Route Type 2 data [RFC 6275]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len=2 | Routing Type=2|Segments Left=1|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
... | Below is the the instruction that describes the task:
### Input:
Read IPv6-Route Type 2 data.
Structure of IPv6-Route Type 2 data [RFC 6275]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len=2 | Routing Type=2|Segments Left=1|
... |
def get_lonlatalts(self):
"""Obtain GCPs and construct latitude and longitude arrays.
Args:
band (gdal band): Measurement band which comes with GCP's
array_shape (tuple) : The size of the data array
Returns:
coordinates (tuple): A tuple with longitude and latitu... | Obtain GCPs and construct latitude and longitude arrays.
Args:
band (gdal band): Measurement band which comes with GCP's
array_shape (tuple) : The size of the data array
Returns:
coordinates (tuple): A tuple with longitude and latitude arrays | Below is the the instruction that describes the task:
### Input:
Obtain GCPs and construct latitude and longitude arrays.
Args:
band (gdal band): Measurement band which comes with GCP's
array_shape (tuple) : The size of the data array
Returns:
coordinates (tuple): A... |
def ping(self) -> None:
"""Pings a database connection, reconnecting if necessary."""
if self.db is None or self.db_pythonlib not in [PYTHONLIB_MYSQLDB,
PYTHONLIB_PYMYSQL]:
return
try:
self.db.ping(True) # test conn... | Pings a database connection, reconnecting if necessary. | Below is the the instruction that describes the task:
### Input:
Pings a database connection, reconnecting if necessary.
### Response:
def ping(self) -> None:
"""Pings a database connection, reconnecting if necessary."""
if self.db is None or self.db_pythonlib not in [PYTHONLIB_MYSQLDB,
... |
def fix_variables(bqm, sampling_mode=True):
"""Determine assignments for some variables of a binary quadratic model.
Roof duality finds a lower bound for the minimum of a quadratic polynomial. It
can also find minimizing assignments for some of the polynomial's variables;
these fixed variables take the... | Determine assignments for some variables of a binary quadratic model.
Roof duality finds a lower bound for the minimum of a quadratic polynomial. It
can also find minimizing assignments for some of the polynomial's variables;
these fixed variables take the same values in all optimal solutions [BHT]_ [BH]_.... | Below is the the instruction that describes the task:
### Input:
Determine assignments for some variables of a binary quadratic model.
Roof duality finds a lower bound for the minimum of a quadratic polynomial. It
can also find minimizing assignments for some of the polynomial's variables;
these fixed ... |
def _get_bandgap_doscar(filename):
"""Get the bandgap from the DOSCAR file"""
with open(filename) as fp:
for i in range(6):
l = fp.readline()
efermi = float(l.split()[3])
step1 = fp.readline().split()[0]
step2 = fp.readline().split()[0]
... | Get the bandgap from the DOSCAR file | Below is the the instruction that describes the task:
### Input:
Get the bandgap from the DOSCAR file
### Response:
def _get_bandgap_doscar(filename):
"""Get the bandgap from the DOSCAR file"""
with open(filename) as fp:
for i in range(6):
l = fp.readline()
e... |
def replace_row(self, line, ndx):
"""
replace a grids row at index 'ndx' with 'line'
"""
for col in range(len(line)):
self.set_tile(ndx, col, line[col]) | replace a grids row at index 'ndx' with 'line' | Below is the the instruction that describes the task:
### Input:
replace a grids row at index 'ndx' with 'line'
### Response:
def replace_row(self, line, ndx):
"""
replace a grids row at index 'ndx' with 'line'
"""
for col in range(len(line)):
self.set_tile(ndx, col, l... |
def path(self, path):
"""
Defines a URL path to match.
Only call this method if the URL has no path already defined.
Arguments:
path (str): URL path value to match. E.g: ``/api/users``.
Returns:
self: current Mock instance.
"""
url = fur... | Defines a URL path to match.
Only call this method if the URL has no path already defined.
Arguments:
path (str): URL path value to match. E.g: ``/api/users``.
Returns:
self: current Mock instance. | Below is the the instruction that describes the task:
### Input:
Defines a URL path to match.
Only call this method if the URL has no path already defined.
Arguments:
path (str): URL path value to match. E.g: ``/api/users``.
Returns:
self: current Mock instance.
##... |
def get_root_nodes(self, project, depth=None):
"""GetRootNodes.
[Preview API] Gets root classification nodes under the project.
:param str project: Project ID or project name
:param int depth: Depth of children to fetch.
:rtype: [WorkItemClassificationNode]
"""
ro... | GetRootNodes.
[Preview API] Gets root classification nodes under the project.
:param str project: Project ID or project name
:param int depth: Depth of children to fetch.
:rtype: [WorkItemClassificationNode] | Below is the the instruction that describes the task:
### Input:
GetRootNodes.
[Preview API] Gets root classification nodes under the project.
:param str project: Project ID or project name
:param int depth: Depth of children to fetch.
:rtype: [WorkItemClassificationNode]
### Respons... |
async def certify(client: Client, certification_signed_raw: str) -> ClientResponse:
"""
POST certification raw document
:param client: Client to connect to the api
:param certification_signed_raw: Certification raw document
:return:
"""
return await client.post(MODULE + '/certify', {'cert':... | POST certification raw document
:param client: Client to connect to the api
:param certification_signed_raw: Certification raw document
:return: | Below is the the instruction that describes the task:
### Input:
POST certification raw document
:param client: Client to connect to the api
:param certification_signed_raw: Certification raw document
:return:
### Response:
async def certify(client: Client, certification_signed_raw: str) -> ClientResp... |
def fit(self, X, y):
"""
Fit CAIM
Parameters
----------
X : array-like, pandas dataframe, shape [n_samples, n_feature]
Input array can contain missing values
y: array-like, pandas dataframe, shape [n_samples]
Target variable. Must be categorical.
... | Fit CAIM
Parameters
----------
X : array-like, pandas dataframe, shape [n_samples, n_feature]
Input array can contain missing values
y: array-like, pandas dataframe, shape [n_samples]
Target variable. Must be categorical.
Returns
-------
s... | Below is the the instruction that describes the task:
### Input:
Fit CAIM
Parameters
----------
X : array-like, pandas dataframe, shape [n_samples, n_feature]
Input array can contain missing values
y: array-like, pandas dataframe, shape [n_samples]
Target var... |
def if_body_action(self, text, loc, arg):
"""Code executed after recognising if statement's body"""
exshared.setpos(loc, text)
if DEBUG > 0:
print("IF_BODY:",arg)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
#generate conditional ju... | Code executed after recognising if statement's body | Below is the the instruction that describes the task:
### Input:
Code executed after recognising if statement's body
### Response:
def if_body_action(self, text, loc, arg):
"""Code executed after recognising if statement's body"""
exshared.setpos(loc, text)
if DEBUG > 0:
pri... |
def run_fn_atomically(self, request):
"""Execute a function, atomically and reply with the result."""
fn = serializer.loads_fn(request[Msgs.info])
args, kwargs = request[Msgs.args], request[Msgs.kwargs]
with self.mutate_safely():
self.reply(fn(self.state, *args, **kwargs)) | Execute a function, atomically and reply with the result. | Below is the the instruction that describes the task:
### Input:
Execute a function, atomically and reply with the result.
### Response:
def run_fn_atomically(self, request):
"""Execute a function, atomically and reply with the result."""
fn = serializer.loads_fn(request[Msgs.info])
args, k... |
def capture_role(self, service_name, deployment_name, role_name,
post_capture_action, target_image_name,
target_image_label, provisioning_configuration=None):
'''
The Capture Role operation captures a virtual machine image to your
image gallery. From the... | The Capture Role operation captures a virtual machine image to your
image gallery. From the captured image, you can create additional
customized virtual machines.
service_name:
The name of the service.
deployment_name:
The name of the deployment.
role_nam... | Below is the the instruction that describes the task:
### Input:
The Capture Role operation captures a virtual machine image to your
image gallery. From the captured image, you can create additional
customized virtual machines.
service_name:
The name of the service.
depl... |
def run_copy(self,
source_project_dataset_tables,
destination_project_dataset_table,
write_disposition='WRITE_EMPTY',
create_disposition='CREATE_IF_NEEDED',
labels=None):
"""
Executes a BigQuery copy command to copy dat... | Executes a BigQuery copy command to copy data from one BigQuery table
to another. See here:
https://cloud.google.com/bigquery/docs/reference/v2/jobs#configuration.copy
For more details about these parameters.
:param source_project_dataset_tables: One or more dotted
``(proj... | Below is the the instruction that describes the task:
### Input:
Executes a BigQuery copy command to copy data from one BigQuery table
to another. See here:
https://cloud.google.com/bigquery/docs/reference/v2/jobs#configuration.copy
For more details about these parameters.
:param ... |
def getL2Representations(self):
"""
Returns the active representation in L2.
"""
return [set(L2.getSelf()._pooler.getActiveCells()) for L2 in self.L2Regions] | Returns the active representation in L2. | Below is the the instruction that describes the task:
### Input:
Returns the active representation in L2.
### Response:
def getL2Representations(self):
"""
Returns the active representation in L2.
"""
return [set(L2.getSelf()._pooler.getActiveCells()) for L2 in self.L2Regions] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.