code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def assertNotCookie(self, name, value=None, attrs={}, *args, **kwargs):
""" Negation of :meth:`assertCookie`. """
return not self.assertCookie(name, value, attrs) | Negation of :meth:`assertCookie`. | Below is the the instruction that describes the task:
### Input:
Negation of :meth:`assertCookie`.
### Response:
def assertNotCookie(self, name, value=None, attrs={}, *args, **kwargs):
""" Negation of :meth:`assertCookie`. """
return not self.assertCookie(name, value, attrs) |
def main(
title,
authors,
year,
email,
journal='',
volume='',
number='',
pages='',
publisher='',
doi='',
tags=[],
DFT_code='Quantum ESPRESSO',
DFT_functionals=['BEEF-vdW'],
reactions=[
{'reactants... | Automatically generate an organized folder structure for a DFT
calculation.
Start by copying the script to a folder in your username
and assign the right information to the arguments in the function.
You can change the parameters and run the script several times if you,
for example, are using diff... | Below is the the instruction that describes the task:
### Input:
Automatically generate an organized folder structure for a DFT
calculation.
Start by copying the script to a folder in your username
and assign the right information to the arguments in the function.
You can change the parameters and... |
def fetch_state_data(self, states):
"""
Fetch census estimates from table.
"""
print("Fetching census data")
for table in CensusTable.objects.all():
api = self.get_series(table.series)
for variable in table.variables.all():
estimate = "{}_{... | Fetch census estimates from table. | Below is the the instruction that describes the task:
### Input:
Fetch census estimates from table.
### Response:
def fetch_state_data(self, states):
"""
Fetch census estimates from table.
"""
print("Fetching census data")
for table in CensusTable.objects.all():
... |
def run(self, host, port, **options):
"""For debugging purposes, you can run this as a standalone server.
.. WARNING:: **Security vulnerability**
This uses :class:`DebuggedJsonRpcApplication` to assist debugging. If you want to use
this in production, you should run :class:`Ser... | For debugging purposes, you can run this as a standalone server.
.. WARNING:: **Security vulnerability**
This uses :class:`DebuggedJsonRpcApplication` to assist debugging. If you want to use
this in production, you should run :class:`Server` as a standard WSGI app with
`uWS... | Below is the the instruction that describes the task:
### Input:
For debugging purposes, you can run this as a standalone server.
.. WARNING:: **Security vulnerability**
This uses :class:`DebuggedJsonRpcApplication` to assist debugging. If you want to use
this in production, you sh... |
def normal_mean(data, variance):
""" Creates a segment cost function for a time series with a
Normal distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
variance (float): variance
Returns:
function: Function with signature
(int,... | Creates a segment cost function for a time series with a
Normal distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
variance (float): variance
Returns:
function: Function with signature
(int, int) -> float
where the firs... | Below is the the instruction that describes the task:
### Input:
Creates a segment cost function for a time series with a
Normal distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
variance (float): variance
Returns:
function: Function with... |
def finalize(self):
"""
Prepare the figure for rendering by setting the title and adjusting
the limits on the axes, adding labels and a legend.
"""
# Set the title
self.set_title((
"Silhouette Plot of {} Clustering for {} Samples in {} Centers"
).form... | Prepare the figure for rendering by setting the title and adjusting
the limits on the axes, adding labels and a legend. | Below is the the instruction that describes the task:
### Input:
Prepare the figure for rendering by setting the title and adjusting
the limits on the axes, adding labels and a legend.
### Response:
def finalize(self):
"""
Prepare the figure for rendering by setting the title and adjusting
... |
def methods(self):
"""
Returns all documented methods as `pydoc.Function` objects in
the class, sorted alphabetically with `__init__` always coming
first.
Unfortunately, this also includes class methods.
"""
p = lambda o: (isinstance(o, Function)
... | Returns all documented methods as `pydoc.Function` objects in
the class, sorted alphabetically with `__init__` always coming
first.
Unfortunately, this also includes class methods. | Below is the the instruction that describes the task:
### Input:
Returns all documented methods as `pydoc.Function` objects in
the class, sorted alphabetically with `__init__` always coming
first.
Unfortunately, this also includes class methods.
### Response:
def methods(self):
"""... |
def assign_load_feedin_case(network):
"""
For each time step evaluate whether it is a feed-in or a load case.
Feed-in and load case are identified based on the
generation and load time series and defined as follows:
1. Load case: positive (load - generation) at HV/MV substation
2. Feed-in case... | For each time step evaluate whether it is a feed-in or a load case.
Feed-in and load case are identified based on the
generation and load time series and defined as follows:
1. Load case: positive (load - generation) at HV/MV substation
2. Feed-in case: negative (load - generation) at HV/MV substation... | Below is the the instruction that describes the task:
### Input:
For each time step evaluate whether it is a feed-in or a load case.
Feed-in and load case are identified based on the
generation and load time series and defined as follows:
1. Load case: positive (load - generation) at HV/MV substation
... |
def punctuate_authorname(an):
"""Punctuate author names properly.
Expects input in the form 'Bloggs, J K' and will return 'Bloggs, J. K.'.
"""
name = an.strip()
parts = [x for x in name.split(',') if x != '']
ret_str = ''
for idx, part in enumerate(parts):
subparts = part.strip().sp... | Punctuate author names properly.
Expects input in the form 'Bloggs, J K' and will return 'Bloggs, J. K.'. | Below is the the instruction that describes the task:
### Input:
Punctuate author names properly.
Expects input in the form 'Bloggs, J K' and will return 'Bloggs, J. K.'.
### Response:
def punctuate_authorname(an):
"""Punctuate author names properly.
Expects input in the form 'Bloggs, J K' and will r... |
def _exec_process(cmd_list, base_context, instance=0, log=None):
"""
Process execution tool.
The forks and execs a process with args formatted according to a context.
This is implemented as a module function to make it available to
event_targets, legion and tasks.
The args are:
cmd_list ... | Process execution tool.
The forks and execs a process with args formatted according to a context.
This is implemented as a module function to make it available to
event_targets, legion and tasks.
The args are:
cmd_list - The path and arg vector
context - Task's context
instance ... | Below is the the instruction that describes the task:
### Input:
Process execution tool.
The forks and execs a process with args formatted according to a context.
This is implemented as a module function to make it available to
event_targets, legion and tasks.
The args are:
cmd_list - The ... |
def nii_gzip(imfile, outpath=''):
'''Compress *.gz file'''
import gzip
with open(imfile, 'rb') as f:
d = f.read()
# Now store the compressed data
if outpath=='':
fout = imfile+'.gz'
else:
fout = os.path.join(outpath, os.path.basename(imfile)+'.gz')
# store compressed ... | Compress *.gz file | Below is the the instruction that describes the task:
### Input:
Compress *.gz file
### Response:
def nii_gzip(imfile, outpath=''):
'''Compress *.gz file'''
import gzip
with open(imfile, 'rb') as f:
d = f.read()
# Now store the compressed data
if outpath=='':
fout = imfile+'.gz'... |
def already_pending_upgrade(self, upgrade_type: UpgradeId) -> Union[int, float]:
""" Check if an upgrade is being researched
Return values:
0: not started
0 < x < 1: researching
1: finished
"""
assert isinstance(upgrade_type, UpgradeId)
if upgrade_type in ... | Check if an upgrade is being researched
Return values:
0: not started
0 < x < 1: researching
1: finished | Below is the the instruction that describes the task:
### Input:
Check if an upgrade is being researched
Return values:
0: not started
0 < x < 1: researching
1: finished
### Response:
def already_pending_upgrade(self, upgrade_type: UpgradeId) -> Union[int, float]:
""" Check ... |
def down(job, input_file_id, n, down_checkpoints):
"""Input is a file and a range into that file to sort and an output location in which
to write the sorted file.
If the range is larger than a threshold N the range is divided recursively and
a follow on job is then created which merges back the results.... | Input is a file and a range into that file to sort and an output location in which
to write the sorted file.
If the range is larger than a threshold N the range is divided recursively and
a follow on job is then created which merges back the results. Otherwise,
the file is sorted and placed in the outpu... | Below is the the instruction that describes the task:
### Input:
Input is a file and a range into that file to sort and an output location in which
to write the sorted file.
If the range is larger than a threshold N the range is divided recursively and
a follow on job is then created which merges back t... |
def check_new_round(hours=24, tournament=1):
"""Check if a new round has started within the last `hours`."""
click.echo(int(napi.check_new_round(hours=hours, tournament=tournament))) | Check if a new round has started within the last `hours`. | Below is the the instruction that describes the task:
### Input:
Check if a new round has started within the last `hours`.
### Response:
def check_new_round(hours=24, tournament=1):
"""Check if a new round has started within the last `hours`."""
click.echo(int(napi.check_new_round(hours=hours, tournament=t... |
def close(self):
"""Close a port on dummy_serial."""
if VERBOSE:
_print_out('\nDummy_serial: Closing port\n')
if not self._isOpen:
raise IOError('Dummy_serial: The port is already closed')
self._isOpen = False
self.port = None | Close a port on dummy_serial. | Below is the the instruction that describes the task:
### Input:
Close a port on dummy_serial.
### Response:
def close(self):
"""Close a port on dummy_serial."""
if VERBOSE:
_print_out('\nDummy_serial: Closing port\n')
if not self._isOpen:
raise IOError('Dummy_seria... |
def readQword(self):
"""
Reads a qword value from the L{ReadData} stream object.
@rtype: int
@return: The qword value read from the L{ReadData} stream.
"""
qword = unpack(self.endianness + ('Q' if not self.signed else 'b'), self.readAt(self.offset, 8))[0]
... | Reads a qword value from the L{ReadData} stream object.
@rtype: int
@return: The qword value read from the L{ReadData} stream. | Below is the the instruction that describes the task:
### Input:
Reads a qword value from the L{ReadData} stream object.
@rtype: int
@return: The qword value read from the L{ReadData} stream.
### Response:
def readQword(self):
"""
Reads a qword value from the L{ReadData} st... |
def single(fun, name, test=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Execute a single state function with the named kwargs, returns False if
insufficient data is sent to the command
By default, the values of the kwargs will be parsed as YAML. So, you can
specify lists values, or lists of... | .. versionadded:: 2015.5.0
Execute a single state function with the named kwargs, returns False if
insufficient data is sent to the command
By default, the values of the kwargs will be parsed as YAML. So, you can
specify lists values, or lists of single entry key-value maps, as you
would in a YAML... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2015.5.0
Execute a single state function with the named kwargs, returns False if
insufficient data is sent to the command
By default, the values of the kwargs will be parsed as YAML. So, you can
specify lists values... |
def delete_item(self, item):
''' removes an item from the db '''
for relation in self.relations_of(item):
self.delete_relation(item, relation)
for origin, relation in self.relations_to(item, True):
self.delete_relation(origin, relation, item)
with self._write_lock... | removes an item from the db | Below is the the instruction that describes the task:
### Input:
removes an item from the db
### Response:
def delete_item(self, item):
''' removes an item from the db '''
for relation in self.relations_of(item):
self.delete_relation(item, relation)
for origin, relation in self.... |
def GetAll(alias=None,location=None,session=None):
"""Gets a list of anti-affinity policies within a given account.
https://t3n.zendesk.com/entries/44657214-Get-Anti-Affinity-Policies
>>> clc.v2.AntiAffinity.GetAll()
[<clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65e910>, <clc.APIv2.anti_affinity.AntiA... | Gets a list of anti-affinity policies within a given account.
https://t3n.zendesk.com/entries/44657214-Get-Anti-Affinity-Policies
>>> clc.v2.AntiAffinity.GetAll()
[<clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65e910>, <clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65ec90>] | Below is the the instruction that describes the task:
### Input:
Gets a list of anti-affinity policies within a given account.
https://t3n.zendesk.com/entries/44657214-Get-Anti-Affinity-Policies
>>> clc.v2.AntiAffinity.GetAll()
[<clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65e910>, <clc.APIv2.anti_a... |
def perez(surface_tilt, surface_azimuth, dhi, dni, dni_extra,
solar_zenith, solar_azimuth, airmass,
model='allsitescomposite1990', return_components=False):
'''
Determine diffuse irradiance from the sky on a tilted surface using
one of the Perez models.
Perez models determine the di... | Determine diffuse irradiance from the sky on a tilted surface using
one of the Perez models.
Perez models determine the diffuse irradiance from the sky (ground
reflected irradiance is not included in this algorithm) on a tilted
surface using the surface tilt angle, surface azimuth angle, diffuse
ho... | Below is the the instruction that describes the task:
### Input:
Determine diffuse irradiance from the sky on a tilted surface using
one of the Perez models.
Perez models determine the diffuse irradiance from the sky (ground
reflected irradiance is not included in this algorithm) on a tilted
surfac... |
def run_ding0(self, session, mv_grid_districts_no=None, debug=False, export_figures=False):
""" Let DING0 run by shouting at this method (or just call
it from NetworkDing0 instance). This method is a wrapper
for the main functionality of DING0.
Parameters
----------
... | Let DING0 run by shouting at this method (or just call
it from NetworkDing0 instance). This method is a wrapper
for the main functionality of DING0.
Parameters
----------
session : sqlalchemy.orm.session.Session
Database session
mv_grid_districts_no :... | Below is the the instruction that describes the task:
### Input:
Let DING0 run by shouting at this method (or just call
it from NetworkDing0 instance). This method is a wrapper
for the main functionality of DING0.
Parameters
----------
session : sqlalchemy.orm.sessio... |
def get_pandas_series(self):
"""The function creates pandas series based on index and values"""
return pandas.Series(self.values, self.index, name=self.name) | The function creates pandas series based on index and values | Below is the the instruction that describes the task:
### Input:
The function creates pandas series based on index and values
### Response:
def get_pandas_series(self):
"""The function creates pandas series based on index and values"""
return pandas.Series(self.values, self.index, name=self.name) |
def get_subjects(self):
"""
Returns the list of subject names present in the schema registry.
"""
res = requests.get(self._url('/subjects'))
raise_if_failed(res)
return res.json() | Returns the list of subject names present in the schema registry. | Below is the the instruction that describes the task:
### Input:
Returns the list of subject names present in the schema registry.
### Response:
def get_subjects(self):
"""
Returns the list of subject names present in the schema registry.
"""
res = requests.get(self._url('/subjects'... |
def get_feature_variable_string(self, feature_key, variable_key, user_id, attributes=None):
""" Returns value for a certain string variable attached to a feature.
Args:
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is to be a... | Returns value for a certain string variable attached to a feature.
Args:
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is to be accessed.
user_id: ID for user.
attributes: Dict representing user attributes.
Retur... | Below is the the instruction that describes the task:
### Input:
Returns value for a certain string variable attached to a feature.
Args:
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is to be accessed.
user_id: ID for ... |
def _load_fits(self, h5file):
""" Loads fits from h5file and returns a dictionary of fits. """
fits = {}
for key in ['mf', 'chifz', 'vfx', 'vfy']:
fits[key] = self._load_scalar_fit(fit_key=key, h5file=h5file)
return fits | Loads fits from h5file and returns a dictionary of fits. | Below is the the instruction that describes the task:
### Input:
Loads fits from h5file and returns a dictionary of fits.
### Response:
def _load_fits(self, h5file):
""" Loads fits from h5file and returns a dictionary of fits. """
fits = {}
for key in ['mf', 'chifz', 'vfx', 'vfy']:
... |
def parse_insert_size(self, f):
""" Parse the contents of the Qualimap BamQC Insert Size Histogram file """
# Get the sample name from the parent parent directory
# Typical path: <sample name>/raw_data_qualimapReport/insert_size_histogram.txt
s_name = self.get_s_name(f)
d = dict()
zero_insertsi... | Parse the contents of the Qualimap BamQC Insert Size Histogram file | Below is the the instruction that describes the task:
### Input:
Parse the contents of the Qualimap BamQC Insert Size Histogram file
### Response:
def parse_insert_size(self, f):
""" Parse the contents of the Qualimap BamQC Insert Size Histogram file """
# Get the sample name from the parent parent directo... |
def _get_wcs_request(self, bbox, time_interval, size_x, size_y, maxcc, time_difference, custom_url_params):
"""
Returns WCS request.
"""
return WcsRequest(layer=self.data_feature,
bbox=bbox,
time=time_interval,
... | Returns WCS request. | Below is the the instruction that describes the task:
### Input:
Returns WCS request.
### Response:
def _get_wcs_request(self, bbox, time_interval, size_x, size_y, maxcc, time_difference, custom_url_params):
"""
Returns WCS request.
"""
return WcsRequest(layer=self.data_feature,
... |
def remove_accent_marks(text, excluded=None):
"""Remove accent marks from input text.
This function removes accent marks in the text, but leaves
unicode characters defined in the 'excluded' parameter.
Args:
text: The text to be processed.
excluded: Set of unicod... | Remove accent marks from input text.
This function removes accent marks in the text, but leaves
unicode characters defined in the 'excluded' parameter.
Args:
text: The text to be processed.
excluded: Set of unicode characters to exclude.
Returns:
Th... | Below is the the instruction that describes the task:
### Input:
Remove accent marks from input text.
This function removes accent marks in the text, but leaves
unicode characters defined in the 'excluded' parameter.
Args:
text: The text to be processed.
excluded: S... |
def _get_validate_plotdata_yaml(grading_file, data):
"""Retrieve validation plot data from grading YAML file (old style).
"""
with open(grading_file) as in_handle:
grade_stats = yaml.safe_load(in_handle)
for sample_stats in grade_stats:
sample = sample_stats["sample"]
for vtype, ... | Retrieve validation plot data from grading YAML file (old style). | Below is the the instruction that describes the task:
### Input:
Retrieve validation plot data from grading YAML file (old style).
### Response:
def _get_validate_plotdata_yaml(grading_file, data):
"""Retrieve validation plot data from grading YAML file (old style).
"""
with open(grading_file) as in_ha... |
def rmvsuffix(subject):
"""
Remove the suffix from *subject*.
"""
index = subject.rfind('.')
if index > subject.replace('\\', '/').rfind('/'):
subject = subject[:index]
return subject | Remove the suffix from *subject*. | Below is the the instruction that describes the task:
### Input:
Remove the suffix from *subject*.
### Response:
def rmvsuffix(subject):
"""
Remove the suffix from *subject*.
"""
index = subject.rfind('.')
if index > subject.replace('\\', '/').rfind('/'):
subject = subject[:index]
return subject |
def _close(self, fd):
"""
Close the descriptor used for a path regardless
of mode.
"""
if self._mode == WF_INOTIFYX:
try: pynotifyx.rm_watch(self._inx_fd, fd)
except: pass
else:
try: os.close(fd)
except: pass | Close the descriptor used for a path regardless
of mode. | Below is the the instruction that describes the task:
### Input:
Close the descriptor used for a path regardless
of mode.
### Response:
def _close(self, fd):
"""
Close the descriptor used for a path regardless
of mode.
"""
if self._mode == WF_INOTIFYX:
try: p... |
def mean_per_class_error(self, thresholds=None):
"""
:param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the
thresholds in this set of metrics will be used.
:returns: mean per class error.
"""
return [[x[0], 1 - x[1]] for x i... | :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the
thresholds in this set of metrics will be used.
:returns: mean per class error. | Below is the the instruction that describes the task:
### Input:
:param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the
thresholds in this set of metrics will be used.
:returns: mean per class error.
### Response:
def mean_per_class_error(self, thresh... |
def load(fname):
"""Loads an array from file.
See more details in ``save``.
Parameters
----------
fname : str
The filename.
Returns
-------
list of NDArray, RowSparseNDArray or CSRNDArray, or \
dict of str to NDArray, RowSparseNDArray or CSRNDArray
Loaded data.
... | Loads an array from file.
See more details in ``save``.
Parameters
----------
fname : str
The filename.
Returns
-------
list of NDArray, RowSparseNDArray or CSRNDArray, or \
dict of str to NDArray, RowSparseNDArray or CSRNDArray
Loaded data. | Below is the the instruction that describes the task:
### Input:
Loads an array from file.
See more details in ``save``.
Parameters
----------
fname : str
The filename.
Returns
-------
list of NDArray, RowSparseNDArray or CSRNDArray, or \
dict of str to NDArray, RowSparseN... |
def toplevelTryFunc(func, *args, **kwargs):
'Thread entry-point for `func(*args, **kwargs)` with try/except wrapper'
t = threading.current_thread()
t.name = func.__name__
ret = None
try:
ret = func(*args, **kwargs)
except EscapeException as e: # user aborted
... | Thread entry-point for `func(*args, **kwargs)` with try/except wrapper | Below is the the instruction that describes the task:
### Input:
Thread entry-point for `func(*args, **kwargs)` with try/except wrapper
### Response:
def toplevelTryFunc(func, *args, **kwargs):
'Thread entry-point for `func(*args, **kwargs)` with try/except wrapper'
t = threading.current_thread()
... |
def _RepackTemplates(self):
"""Repack templates with a dummy config."""
dummy_config = os.path.join(
args.grr_src, "grr/test/grr_response_test/test_data/dummyconfig.yaml")
if args.build_32:
template_i386 = glob.glob(os.path.join(args.output_dir,
"*_... | Repack templates with a dummy config. | Below is the the instruction that describes the task:
### Input:
Repack templates with a dummy config.
### Response:
def _RepackTemplates(self):
"""Repack templates with a dummy config."""
dummy_config = os.path.join(
args.grr_src, "grr/test/grr_response_test/test_data/dummyconfig.yaml")
if arg... |
def middleware(self, *args, **kwargs):
"""
A decorator that can be used to implement a Middleware plugin to
all of the Blueprints that belongs to this specific Blueprint Group.
In case of nested Blueprint Groups, the same middleware is applied
across each of the Blueprints recur... | A decorator that can be used to implement a Middleware plugin to
all of the Blueprints that belongs to this specific Blueprint Group.
In case of nested Blueprint Groups, the same middleware is applied
across each of the Blueprints recursively.
:param args: Optional positional Parameter... | Below is the the instruction that describes the task:
### Input:
A decorator that can be used to implement a Middleware plugin to
all of the Blueprints that belongs to this specific Blueprint Group.
In case of nested Blueprint Groups, the same middleware is applied
across each of the Bluepr... |
def _populate_worksheet(self, workbook, worksheet):
"""
Write the chart data contents to *worksheet* in category chart
layout. Write categories starting in the first column starting in
the second row, and proceeding one column per category level (for
charts having multi-level cat... | Write the chart data contents to *worksheet* in category chart
layout. Write categories starting in the first column starting in
the second row, and proceeding one column per category level (for
charts having multi-level categories). Write series as columns
starting in the next following... | Below is the the instruction that describes the task:
### Input:
Write the chart data contents to *worksheet* in category chart
layout. Write categories starting in the first column starting in
the second row, and proceeding one column per category level (for
charts having multi-level catego... |
def get_value(self, constraints, expression):
"""
Ask the solver for one possible result of given expression using given set of constraints.
"""
if not issymbolic(expression):
return expression
assert isinstance(expression, (Bool, BitVec, Array))
with constrai... | Ask the solver for one possible result of given expression using given set of constraints. | Below is the the instruction that describes the task:
### Input:
Ask the solver for one possible result of given expression using given set of constraints.
### Response:
def get_value(self, constraints, expression):
"""
Ask the solver for one possible result of given expression using given set of c... |
def read_element_tag(fd, endian):
"""Read data element tag: type and number of bytes.
If tag is of the Small Data Element (SDE) type the element data
is also returned.
"""
data = fd.read(8)
mtpn = unpack(endian, 'I', data[:4])
# The most significant two bytes of mtpn will always be 0,
# ... | Read data element tag: type and number of bytes.
If tag is of the Small Data Element (SDE) type the element data
is also returned. | Below is the the instruction that describes the task:
### Input:
Read data element tag: type and number of bytes.
If tag is of the Small Data Element (SDE) type the element data
is also returned.
### Response:
def read_element_tag(fd, endian):
"""Read data element tag: type and number of bytes.
If ... |
def get_decorators(func):
"""
Return a list of decorator names for this function.
"""
decorators = []
# Parse the source code of the function with ast to find the names of
# all of its decorators.
tree = ast.parse(inspect.getsource(func))
for node in ast.iter_child_nodes(tree):
f... | Return a list of decorator names for this function. | Below is the the instruction that describes the task:
### Input:
Return a list of decorator names for this function.
### Response:
def get_decorators(func):
"""
Return a list of decorator names for this function.
"""
decorators = []
# Parse the source code of the function with ast to find the n... |
def write_to(f, mode):
"""Flexible writing, where f can be a filename or f object, if filename, closed after writing"""
if hasattr(f, 'write'):
yield f
else:
f = open(f, mode)
yield f
f.close() | Flexible writing, where f can be a filename or f object, if filename, closed after writing | Below is the the instruction that describes the task:
### Input:
Flexible writing, where f can be a filename or f object, if filename, closed after writing
### Response:
def write_to(f, mode):
"""Flexible writing, where f can be a filename or f object, if filename, closed after writing"""
if hasattr(f, 'wr... |
def get_projects():
"""
Send a dictionary of projects that are available on the database.
Usage description:
This function is usually called to get and display the list of projects available in the database.
:return: JSON, {<int_keys>: <project_name>}
"""
assert request.method == "GET", "G... | Send a dictionary of projects that are available on the database.
Usage description:
This function is usually called to get and display the list of projects available in the database.
:return: JSON, {<int_keys>: <project_name>} | Below is the the instruction that describes the task:
### Input:
Send a dictionary of projects that are available on the database.
Usage description:
This function is usually called to get and display the list of projects available in the database.
:return: JSON, {<int_keys>: <project_name>}
### Respo... |
def errored_tasks(self):
"""List of errored tasks."""
etasks = []
for status in [self.S_ERROR, self.S_QCRITICAL, self.S_ABICRITICAL]:
etasks.extend(list(self.iflat_tasks(status=status)))
return set(etasks) | List of errored tasks. | Below is the the instruction that describes the task:
### Input:
List of errored tasks.
### Response:
def errored_tasks(self):
"""List of errored tasks."""
etasks = []
for status in [self.S_ERROR, self.S_QCRITICAL, self.S_ABICRITICAL]:
etasks.extend(list(self.iflat_tasks(status=... |
def security_rule_create_or_update(name, access, direction, priority, protocol, security_group, resource_group,
source_address_prefix=None, destination_address_prefix=None, source_port_range=None,
destination_port_range=None, source_address_prefixes=... | .. versionadded:: 2019.2.0
Create or update a security rule within a specified network security group.
:param name: The name of the security rule to create.
:param access:
'allow' or 'deny'
:param direction:
'inbound' or 'outbound'
:param priority:
Integer between 100 an... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2019.2.0
Create or update a security rule within a specified network security group.
:param name: The name of the security rule to create.
:param access:
'allow' or 'deny'
:param direction:
'inboun... |
def check_standard_name(self, ds):
'''
Check a variables's standard_name attribute to ensure that it meets CF
compliance.
CF §3.3 A standard name is associated with a variable via the attribute
standard_name which takes a string value comprised of a standard name
optiona... | Check a variables's standard_name attribute to ensure that it meets CF
compliance.
CF §3.3 A standard name is associated with a variable via the attribute
standard_name which takes a string value comprised of a standard name
optionally followed by one or more blanks and a standard name ... | Below is the the instruction that describes the task:
### Input:
Check a variables's standard_name attribute to ensure that it meets CF
compliance.
CF §3.3 A standard name is associated with a variable via the attribute
standard_name which takes a string value comprised of a standard name
... |
def from_urlsafe(cls, urlsafe):
"""
Returns an instance of the model from a urlsafe string.
:param urlsafe: urlsafe key
:return: Instance of cls
"""
try:
key = ndb.Key(urlsafe=urlsafe)
except:
return None
obj = key.get()
if... | Returns an instance of the model from a urlsafe string.
:param urlsafe: urlsafe key
:return: Instance of cls | Below is the the instruction that describes the task:
### Input:
Returns an instance of the model from a urlsafe string.
:param urlsafe: urlsafe key
:return: Instance of cls
### Response:
def from_urlsafe(cls, urlsafe):
"""
Returns an instance of the model from a urlsafe string.
... |
def verify_signature(key_dict, signature, data):
"""
<Purpose>
Determine whether the private key belonging to 'key_dict' produced
'signature'. verify_signature() will use the public key found in
'key_dict', the 'sig' objects contained in 'signature', and 'data' to
complete the verification.
>>... | <Purpose>
Determine whether the private key belonging to 'key_dict' produced
'signature'. verify_signature() will use the public key found in
'key_dict', the 'sig' objects contained in 'signature', and 'data' to
complete the verification.
>>> ed25519_key = generate_ed25519_key()
>>> data = 'Th... | Below is the the instruction that describes the task:
### Input:
<Purpose>
Determine whether the private key belonging to 'key_dict' produced
'signature'. verify_signature() will use the public key found in
'key_dict', the 'sig' objects contained in 'signature', and 'data' to
complete the verificat... |
def exists(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None):
'''
Check if path exists
path
path to check
profile
Configured Zookeeper profile to authenticate with (Default: None)
hosts
Lists of Zookeeper Hosts (Default: '127.0.0.... | Check if path exists
path
path to check
profile
Configured Zookeeper profile to authenticate with (Default: None)
hosts
Lists of Zookeeper Hosts (Default: '127.0.0.1:2181)
scheme
Scheme to authenticate with (Default: 'digest')
username
Username to authent... | Below is the the instruction that describes the task:
### Input:
Check if path exists
path
path to check
profile
Configured Zookeeper profile to authenticate with (Default: None)
hosts
Lists of Zookeeper Hosts (Default: '127.0.0.1:2181)
scheme
Scheme to authentica... |
def generate_slug(value):
"""
Generates a slug using a Hashid of `value`.
COPIED from spectator.core.models.SluggedModelMixin() because migrations
don't make this happen automatically and perhaps the least bad thing is
to copy the method here, ugh.
"""
alphabet = app_settings.SLUG_ALPHABET
... | Generates a slug using a Hashid of `value`.
COPIED from spectator.core.models.SluggedModelMixin() because migrations
don't make this happen automatically and perhaps the least bad thing is
to copy the method here, ugh. | Below is the the instruction that describes the task:
### Input:
Generates a slug using a Hashid of `value`.
COPIED from spectator.core.models.SluggedModelMixin() because migrations
don't make this happen automatically and perhaps the least bad thing is
to copy the method here, ugh.
### Response:
def ... |
def get_content_macro_by_macro_id(self, content_id, version, macro_id, callback=None):
"""
Returns the body of a macro (in storage format) with the given id.
This resource is primarily used by connect applications that require the body of macro to perform their work.
When content is cre... | Returns the body of a macro (in storage format) with the given id.
This resource is primarily used by connect applications that require the body of macro to perform their work.
When content is created, if no macroId is specified, then Confluence will generate a random id.
The id is persisted as... | Below is the the instruction that describes the task:
### Input:
Returns the body of a macro (in storage format) with the given id.
This resource is primarily used by connect applications that require the body of macro to perform their work.
When content is created, if no macroId is specified, then... |
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks f... | .. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
### Response:
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded... |
def add_round_key(state, rkey):
"""
Transformation in the Cipher and Inverse Cipher in which a Round Key is
added to the State using an XOR operation. The length of a Round Key equals
the size of the State (i.e., for Nb = 4, the Round Key length equals 128
bits/16 bytes).
"""
state = state.r... | Transformation in the Cipher and Inverse Cipher in which a Round Key is
added to the State using an XOR operation. The length of a Round Key equals
the size of the State (i.e., for Nb = 4, the Round Key length equals 128
bits/16 bytes). | Below is the the instruction that describes the task:
### Input:
Transformation in the Cipher and Inverse Cipher in which a Round Key is
added to the State using an XOR operation. The length of a Round Key equals
the size of the State (i.e., for Nb = 4, the Round Key length equals 128
bits/16 bytes).
##... |
def disable_key(self):
"""Disable an existing API Key."""
print("This command will disable a enabled key.")
apiKeyID = input("API Key ID: ")
try:
key = self._curl_bitmex("/apiKey/disable",
postdict={"apiKeyID": apiKeyID})
print(... | Disable an existing API Key. | Below is the the instruction that describes the task:
### Input:
Disable an existing API Key.
### Response:
def disable_key(self):
"""Disable an existing API Key."""
print("This command will disable a enabled key.")
apiKeyID = input("API Key ID: ")
try:
key = self._curl_... |
def check_required_fields(method, uri, body, field_names):
"""
Check required fields in the request body.
Raises:
BadRequestError with reason 3: Missing request body
BadRequestError with reason 5: Missing required field in request body
"""
# Check presence of request body
if body i... | Check required fields in the request body.
Raises:
BadRequestError with reason 3: Missing request body
BadRequestError with reason 5: Missing required field in request body | Below is the the instruction that describes the task:
### Input:
Check required fields in the request body.
Raises:
BadRequestError with reason 3: Missing request body
BadRequestError with reason 5: Missing required field in request body
### Response:
def check_required_fields(method, uri, body, f... |
def _raw_split(itxt):
"""
Parse HTML from text into array filled with tags end text.
Source code is little bit unintutive, because it is state machine parser.
For better understanding, look at http://bit.ly/1rXRcJj
Example::
>>> dhtmlparser._raw_split('<html><tag params="true"></html>')
... | Parse HTML from text into array filled with tags end text.
Source code is little bit unintutive, because it is state machine parser.
For better understanding, look at http://bit.ly/1rXRcJj
Example::
>>> dhtmlparser._raw_split('<html><tag params="true"></html>')
['<html>', '<tag params="t... | Below is the the instruction that describes the task:
### Input:
Parse HTML from text into array filled with tags end text.
Source code is little bit unintutive, because it is state machine parser.
For better understanding, look at http://bit.ly/1rXRcJj
Example::
>>> dhtmlparser._raw_split('... |
def _set_host(self, v, load=False):
"""
Setter method for host, mapped from YANG variable /snmp_server/host (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_host is considered as a private
method. Backends looking to populate this variable should
do so via ... | Setter method for host, mapped from YANG variable /snmp_server/host (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_host is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_host() directly. | Below is the the instruction that describes the task:
### Input:
Setter method for host, mapped from YANG variable /snmp_server/host (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_host is considered as a private
method. Backends looking to populate this variable ... |
def fetch(self, is_dl_forced=False):
"""
Here we connect to the coriell sftp server using private connection
details. They dump bi-weekly files with a timestamp in the filename.
For each catalog, we ping the remote site and pull the most-recently
updated file, renaming it to our... | Here we connect to the coriell sftp server using private connection
details. They dump bi-weekly files with a timestamp in the filename.
For each catalog, we ping the remote site and pull the most-recently
updated file, renaming it to our local latest.csv.
Be sure to have pg user/pass... | Below is the the instruction that describes the task:
### Input:
Here we connect to the coriell sftp server using private connection
details. They dump bi-weekly files with a timestamp in the filename.
For each catalog, we ping the remote site and pull the most-recently
updated file, renami... |
def update_loadbalancer(self, lbaas_loadbalancer, body=None):
"""Updates a load balancer."""
return self.put(self.lbaas_loadbalancer_path % (lbaas_loadbalancer),
body=body) | Updates a load balancer. | Below is the the instruction that describes the task:
### Input:
Updates a load balancer.
### Response:
def update_loadbalancer(self, lbaas_loadbalancer, body=None):
"""Updates a load balancer."""
return self.put(self.lbaas_loadbalancer_path % (lbaas_loadbalancer),
body=body... |
def delete_source(self, photo, **kwds):
"""
Endpoint: /photo/<id>/source/delete.json
Delete the source files of a photo.
Returns True if successful.
Raises a TroveboxError if not.
"""
return self._client.post("/photo/%s/source/delete.json" %
... | Endpoint: /photo/<id>/source/delete.json
Delete the source files of a photo.
Returns True if successful.
Raises a TroveboxError if not. | Below is the the instruction that describes the task:
### Input:
Endpoint: /photo/<id>/source/delete.json
Delete the source files of a photo.
Returns True if successful.
Raises a TroveboxError if not.
### Response:
def delete_source(self, photo, **kwds):
"""
Endpoint: /phot... |
def _get_named_graph(context):
"""
Returns the named graph for this context.
"""
if context is None:
return None
return models.NamedGraph.objects.get_or_create(identifier=context.identifier)[0] | Returns the named graph for this context. | Below is the the instruction that describes the task:
### Input:
Returns the named graph for this context.
### Response:
def _get_named_graph(context):
"""
Returns the named graph for this context.
"""
if context is None:
return None
return models.NamedGraph.objects.get_or_create(ident... |
def modify_log_flags(self, settings):
"""Modifies the debug or release logger flags.
in settings of type str
The flags settings string. See iprt/log.h for details. To target the
release logger, prefix the string with "release:".
"""
if not isinstance(settings, b... | Modifies the debug or release logger flags.
in settings of type str
The flags settings string. See iprt/log.h for details. To target the
release logger, prefix the string with "release:". | Below is the the instruction that describes the task:
### Input:
Modifies the debug or release logger flags.
in settings of type str
The flags settings string. See iprt/log.h for details. To target the
release logger, prefix the string with "release:".
### Response:
def modify_log_... |
def relabeled(self, label, new_label):
"""Return a new table with ``label`` specifying column label(s)
replaced by corresponding ``new_label``.
Args:
``label`` -- (str or array of str) The label(s) of
columns to be changed.
``new_label`` -- (str or array... | Return a new table with ``label`` specifying column label(s)
replaced by corresponding ``new_label``.
Args:
``label`` -- (str or array of str) The label(s) of
columns to be changed.
``new_label`` -- (str or array of str): The new label(s) of
colu... | Below is the the instruction that describes the task:
### Input:
Return a new table with ``label`` specifying column label(s)
replaced by corresponding ``new_label``.
Args:
``label`` -- (str or array of str) The label(s) of
columns to be changed.
``new_label... |
def parse_resource_extended(library, session, resource_name):
"""Parse a resource string to get extended interface information.
Corresponds to viParseRsrcEx function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Resource Manager session (should always be the ... | Parse a resource string to get extended interface information.
Corresponds to viParseRsrcEx function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Resource Manager session (should always be the Default Resource Manager for VISA
returned from o... | Below is the the instruction that describes the task:
### Input:
Parse a resource string to get extended interface information.
Corresponds to viParseRsrcEx function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Resource Manager session (should always be the ... |
def _calculate_areas(self, label):
"""Calculate areas for multiple labels"""
heights = np.maximum(0, label[:, 3] - label[:, 1])
widths = np.maximum(0, label[:, 2] - label[:, 0])
return heights * widths | Calculate areas for multiple labels | Below is the the instruction that describes the task:
### Input:
Calculate areas for multiple labels
### Response:
def _calculate_areas(self, label):
"""Calculate areas for multiple labels"""
heights = np.maximum(0, label[:, 3] - label[:, 1])
widths = np.maximum(0, label[:, 2] - label[:, 0]... |
def dump_rawdata(self):
"""Return contents of transport object for debugging forensics."""
if hasattr(self, 'transport'):
attrs = vars(self.transport)
return ', '.join("%s: %s" % item for item in attrs.items()) | Return contents of transport object for debugging forensics. | Below is the the instruction that describes the task:
### Input:
Return contents of transport object for debugging forensics.
### Response:
def dump_rawdata(self):
"""Return contents of transport object for debugging forensics."""
if hasattr(self, 'transport'):
attrs = vars(self.transpo... |
def get_indexer_for(self, target, **kwargs):
"""
Guaranteed return of an indexer even when non-unique.
This dispatches to get_indexer or get_indexer_nonunique
as appropriate.
"""
if self.is_unique:
return self.get_indexer(target, **kwargs)
indexer, _ ... | Guaranteed return of an indexer even when non-unique.
This dispatches to get_indexer or get_indexer_nonunique
as appropriate. | Below is the the instruction that describes the task:
### Input:
Guaranteed return of an indexer even when non-unique.
This dispatches to get_indexer or get_indexer_nonunique
as appropriate.
### Response:
def get_indexer_for(self, target, **kwargs):
"""
Guaranteed return of an inde... |
def listeI(l):
""" Fonction importante permettant de renvoyer
une liste d'entiers à partir d'une chaîne.
La chaîne est une liste de sections séparées
par des virgules. Une section peut être soit
un entier, soit un intervalle d'entiers. On
donne alors les l... | Fonction importante permettant de renvoyer
une liste d'entiers à partir d'une chaîne.
La chaîne est une liste de sections séparées
par des virgules. Une section peut être soit
un entier, soit un intervalle d'entiers. On
donne alors les limites inférieure et su... | Below is the the instruction that describes the task:
### Input:
Fonction importante permettant de renvoyer
une liste d'entiers à partir d'une chaîne.
La chaîne est une liste de sections séparées
par des virgules. Une section peut être soit
un entier, soit un interval... |
def ancestor(self, value):
"""Set the ancestor for the query
:type value: :class:`~google.cloud.datastore.key.Key`
:param value: the new ancestor key
"""
if not isinstance(value, Key):
raise TypeError("Ancestor must be a Key")
self._ancestor = value | Set the ancestor for the query
:type value: :class:`~google.cloud.datastore.key.Key`
:param value: the new ancestor key | Below is the the instruction that describes the task:
### Input:
Set the ancestor for the query
:type value: :class:`~google.cloud.datastore.key.Key`
:param value: the new ancestor key
### Response:
def ancestor(self, value):
"""Set the ancestor for the query
:type value: :class:`... |
def urlopen(self, method, url, body=None, headers=None, **kwargs):
"""Implementation of urllib3's urlopen."""
# pylint: disable=arguments-differ
# We use kwargs to collect additional args that we don't need to
# introspect here. However, we do explicitly collect the two
# positio... | Implementation of urllib3's urlopen. | Below is the the instruction that describes the task:
### Input:
Implementation of urllib3's urlopen.
### Response:
def urlopen(self, method, url, body=None, headers=None, **kwargs):
"""Implementation of urllib3's urlopen."""
# pylint: disable=arguments-differ
# We use kwargs to collect add... |
def stations_iter(self, *, page_size=250):
"""Get a paged iterator of library stations.
Parameters:
page_size (int, Optional): The maximum number of results per returned page.
Max allowed is ``49995``.
Default: ``250``
Yields:
list: Station dicts.
"""
start_token = None
while True:
resp... | Get a paged iterator of library stations.
Parameters:
page_size (int, Optional): The maximum number of results per returned page.
Max allowed is ``49995``.
Default: ``250``
Yields:
list: Station dicts. | Below is the the instruction that describes the task:
### Input:
Get a paged iterator of library stations.
Parameters:
page_size (int, Optional): The maximum number of results per returned page.
Max allowed is ``49995``.
Default: ``250``
Yields:
list: Station dicts.
### Response:
def stations_i... |
def define_contributor(self, request):
"""Define contributor by adding it to request.data."""
request.data['contributor'] = self.resolve_user(request.user).pk | Define contributor by adding it to request.data. | Below is the the instruction that describes the task:
### Input:
Define contributor by adding it to request.data.
### Response:
def define_contributor(self, request):
"""Define contributor by adding it to request.data."""
request.data['contributor'] = self.resolve_user(request.user).pk |
def update_pointed(self):
'''
Grabs the latest file contents based on the pointer uri
'''
# only grab file if our pointer is still good (not None)
if not self.pointed_at_expired:
try:
conf_string, stat2 = self.zoo_client.get(self.point_path,
... | Grabs the latest file contents based on the pointer uri | Below is the the instruction that describes the task:
### Input:
Grabs the latest file contents based on the pointer uri
### Response:
def update_pointed(self):
'''
Grabs the latest file contents based on the pointer uri
'''
# only grab file if our pointer is still good (not None)
... |
def create_char_dataframe(words):
"""
Give list of input tokenized words,
create dataframe of characters where first character of
the word is tagged as 1, otherwise 0
Example
=======
['กิน', 'หมด'] to dataframe of
[{'char': 'ก', 'type': ..., 'target': 1}, ...,
{'char': 'ด', 'type':... | Give list of input tokenized words,
create dataframe of characters where first character of
the word is tagged as 1, otherwise 0
Example
=======
['กิน', 'หมด'] to dataframe of
[{'char': 'ก', 'type': ..., 'target': 1}, ...,
{'char': 'ด', 'type': ..., 'target': 0}] | Below is the the instruction that describes the task:
### Input:
Give list of input tokenized words,
create dataframe of characters where first character of
the word is tagged as 1, otherwise 0
Example
=======
['กิน', 'หมด'] to dataframe of
[{'char': 'ก', 'type': ..., 'target': 1}, ...,
... |
def add_output_path(path: str = None) -> str:
"""
Adds the specified path to the output logging paths if it is not
already in the listed paths.
:param path:
The path to add to the logging output paths. If the path is empty
or no path is given, the current working directory will be used
... | Adds the specified path to the output logging paths if it is not
already in the listed paths.
:param path:
The path to add to the logging output paths. If the path is empty
or no path is given, the current working directory will be used
instead. | Below is the the instruction that describes the task:
### Input:
Adds the specified path to the output logging paths if it is not
already in the listed paths.
:param path:
The path to add to the logging output paths. If the path is empty
or no path is given, the current working directory wi... |
def shape(self):
"""Number of grid points per axis."""
try:
return self.__shape
except AttributeError:
shape = tuple(len(vec) for vec in self.coord_vectors)
self.__shape = shape
return shape | Number of grid points per axis. | Below is the the instruction that describes the task:
### Input:
Number of grid points per axis.
### Response:
def shape(self):
"""Number of grid points per axis."""
try:
return self.__shape
except AttributeError:
shape = tuple(len(vec) for vec in self.coord_vectors)... |
def datacite_to_pif_reference(dc):
"""
Parse a top-level datacite dictionary into a Reference
:param dc: dictionary containing datacite metadata
:return: Reference corresponding to that datacite entry
"""
ref = Reference()
if dc.get('identifier', {}).get('identifierType') == "DOI":
r... | Parse a top-level datacite dictionary into a Reference
:param dc: dictionary containing datacite metadata
:return: Reference corresponding to that datacite entry | Below is the the instruction that describes the task:
### Input:
Parse a top-level datacite dictionary into a Reference
:param dc: dictionary containing datacite metadata
:return: Reference corresponding to that datacite entry
### Response:
def datacite_to_pif_reference(dc):
"""
Parse a top-level d... |
def reshape_range(tensor, i, j, shape):
"""Reshapes a tensor between dimensions i and j."""
t_shape = common_layers.shape_list(tensor)
target_shape = t_shape[:i] + shape + t_shape[j:]
return tf.reshape(tensor, target_shape) | Reshapes a tensor between dimensions i and j. | Below is the the instruction that describes the task:
### Input:
Reshapes a tensor between dimensions i and j.
### Response:
def reshape_range(tensor, i, j, shape):
"""Reshapes a tensor between dimensions i and j."""
t_shape = common_layers.shape_list(tensor)
target_shape = t_shape[:i] + shape + t_shape[j:]
... |
def pointAt(self, **axis_values):
"""
Returns the point on the chart where the inputed values are located.
:return <QPointF>
"""
scene_point = self.renderer().pointAt(self.axes(), axis_values)
chart_point = self.uiChartVIEW.mapFromScene(scene_point)
... | Returns the point on the chart where the inputed values are located.
:return <QPointF> | Below is the the instruction that describes the task:
### Input:
Returns the point on the chart where the inputed values are located.
:return <QPointF>
### Response:
def pointAt(self, **axis_values):
"""
Returns the point on the chart where the inputed values are located.
... |
def _encode_config(conf_dict):
"""Encode `conf_dict` to string."""
out = []
# get variables in order defined in settings._ALLOWED_MERGES
for var in settings._ALLOWED_MERGES:
out.append(conf_dict[var])
# convert bools to chars
out = map(
lambda x: "t" if x else "f",
out
... | Encode `conf_dict` to string. | Below is the the instruction that describes the task:
### Input:
Encode `conf_dict` to string.
### Response:
def _encode_config(conf_dict):
"""Encode `conf_dict` to string."""
out = []
# get variables in order defined in settings._ALLOWED_MERGES
for var in settings._ALLOWED_MERGES:
out.app... |
def impact_rating(self):
'''
Returns the impact rating for this node. Impact rating is a measure
of how powerful this moment in the story is by evaluting how many simultaneous
arc elements are associated with it. There is also a generational bleed element,
where the impact score ... | Returns the impact rating for this node. Impact rating is a measure
of how powerful this moment in the story is by evaluting how many simultaneous
arc elements are associated with it. There is also a generational bleed element,
where the impact score creates shockwaves throughout their direct an... | Below is the the instruction that describes the task:
### Input:
Returns the impact rating for this node. Impact rating is a measure
of how powerful this moment in the story is by evaluting how many simultaneous
arc elements are associated with it. There is also a generational bleed element,
... |
def _create_variables_pretrain(self):
"""Create model variables (previous unsupervised pretraining).
:return: self
"""
for l, layer in enumerate(self.layers):
self.encoding_w_[l] = tf.Variable(
self.encoding_w_[l], name='enc-w-{}'.format(l))
self.... | Create model variables (previous unsupervised pretraining).
:return: self | Below is the the instruction that describes the task:
### Input:
Create model variables (previous unsupervised pretraining).
:return: self
### Response:
def _create_variables_pretrain(self):
"""Create model variables (previous unsupervised pretraining).
:return: self
"""
f... |
def main_photo(self):
"""Return user's main photo."""
if not self._main_photo:
self._main_photo = self.photos_factory()
return self._main_photo | Return user's main photo. | Below is the the instruction that describes the task:
### Input:
Return user's main photo.
### Response:
def main_photo(self):
"""Return user's main photo."""
if not self._main_photo:
self._main_photo = self.photos_factory()
return self._main_photo |
def get_len(self, key):
"""Return sequence length"""
data = self.model.get_data()
return len(data[key]) | Return sequence length | Below is the the instruction that describes the task:
### Input:
Return sequence length
### Response:
def get_len(self, key):
"""Return sequence length"""
data = self.model.get_data()
return len(data[key]) |
def compile_dependencies(self, sourcepath, include_self=True):
"""
Same as inherit method but the default value for keyword argument
``ìnclude_self`` is ``True``.
"""
return super(SassProjectEventHandler, self).compile_dependencies(
sourcepath,
include_sel... | Same as inherit method but the default value for keyword argument
``ìnclude_self`` is ``True``. | Below is the the instruction that describes the task:
### Input:
Same as inherit method but the default value for keyword argument
``ìnclude_self`` is ``True``.
### Response:
def compile_dependencies(self, sourcepath, include_self=True):
"""
Same as inherit method but the default value for ... |
def header(self):
'''
Displays the scan header, as defined by self.HEADER and self.HEADER_FORMAT.
Returns None.
'''
self.config.display.format_strings(self.HEADER_FORMAT, self.RESULT_FORMAT)
self.config.display.add_custom_header(self.VERBOSE_FORMAT, self.VERBOSE)
... | Displays the scan header, as defined by self.HEADER and self.HEADER_FORMAT.
Returns None. | Below is the the instruction that describes the task:
### Input:
Displays the scan header, as defined by self.HEADER and self.HEADER_FORMAT.
Returns None.
### Response:
def header(self):
'''
Displays the scan header, as defined by self.HEADER and self.HEADER_FORMAT.
Returns None.
... |
def get_access_token(self):
"""
判断现有的token是否过期。
用户需要多进程或者多机部署可以手动重写这个函数
来自定义token的存储,刷新策略。
:return: 返回token
"""
if self._token:
now = time.time()
if self.token_expires_at - now > 60:
return self._token
json = self.g... | 判断现有的token是否过期。
用户需要多进程或者多机部署可以手动重写这个函数
来自定义token的存储,刷新策略。
:return: 返回token | Below is the the instruction that describes the task:
### Input:
判断现有的token是否过期。
用户需要多进程或者多机部署可以手动重写这个函数
来自定义token的存储,刷新策略。
:return: 返回token
### Response:
def get_access_token(self):
"""
判断现有的token是否过期。
用户需要多进程或者多机部署可以手动重写这个函数
来自定义token的存储,刷新策略。
:re... |
def bind(self):
"""Binds reference objects to the proper parse actions."""
self.endline <<= attach(self.endline_ref, self.endline_handle)
self.moduledoc_item <<= trace(attach(self.moduledoc, self.set_docstring))
self.name <<= trace(attach(self.base_name, self.name_check))
# comm... | Binds reference objects to the proper parse actions. | Below is the the instruction that describes the task:
### Input:
Binds reference objects to the proper parse actions.
### Response:
def bind(self):
"""Binds reference objects to the proper parse actions."""
self.endline <<= attach(self.endline_ref, self.endline_handle)
self.moduledoc_item ... |
def lock(self, id=str(uuid.uuid4()), ttl=DEFAULT_TIMEOUT):
"""Create a Lock object given an ID and timeout
:param id: ID for the lock, creates a new uuid if not provided
:param ttl: timeout
:return: Lock object
"""
return Lock(id, ttl=ttl, client=self) | Create a Lock object given an ID and timeout
:param id: ID for the lock, creates a new uuid if not provided
:param ttl: timeout
:return: Lock object | Below is the the instruction that describes the task:
### Input:
Create a Lock object given an ID and timeout
:param id: ID for the lock, creates a new uuid if not provided
:param ttl: timeout
:return: Lock object
### Response:
def lock(self, id=str(uuid.uuid4()), ttl=DEFAULT_TIMEOUT):
... |
def text_cleanup(data, key, last_type):
""" I strip extra whitespace off multi-line strings if they are ready to be stripped!"""
if key in data and last_type == STRING_TYPE:
data[key] = data[key].strip()
return data | I strip extra whitespace off multi-line strings if they are ready to be stripped! | Below is the the instruction that describes the task:
### Input:
I strip extra whitespace off multi-line strings if they are ready to be stripped!
### Response:
def text_cleanup(data, key, last_type):
""" I strip extra whitespace off multi-line strings if they are ready to be stripped!"""
if key in data an... |
def fetch_batch(self):
""" Fetch a batch of data without waiting"""
inp, f = self.queue.get()
nr_input_var = len(inp)
batched, futures = [[] for _ in range(nr_input_var)], []
for k in range(nr_input_var):
batched[k].append(inp[k])
futures.append(f)
whi... | Fetch a batch of data without waiting | Below is the the instruction that describes the task:
### Input:
Fetch a batch of data without waiting
### Response:
def fetch_batch(self):
""" Fetch a batch of data without waiting"""
inp, f = self.queue.get()
nr_input_var = len(inp)
batched, futures = [[] for _ in range(nr_input_v... |
def _make_params_pb(params, param_types):
"""Helper for :meth:`execute_update`.
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``dml``.
:type param_types: dict[str -> Union[dict, .type... | Helper for :meth:`execute_update`.
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``dml``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Opt... | Below is the the instruction that describes the task:
### Input:
Helper for :meth:`execute_update`.
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``dml``.
:type param_types: dict[str -> U... |
def _validate_user_class(cls, user_class):
"""
Validates the supplied user_class to make sure that it has the
class methods necessary to function correctly.
Requirements:
- ``lookup`` method. Accepts a string parameter, returns instance
- ``identify`` method. Accepts an... | Validates the supplied user_class to make sure that it has the
class methods necessary to function correctly.
Requirements:
- ``lookup`` method. Accepts a string parameter, returns instance
- ``identify`` method. Accepts an identity parameter, returns instance | Below is the the instruction that describes the task:
### Input:
Validates the supplied user_class to make sure that it has the
class methods necessary to function correctly.
Requirements:
- ``lookup`` method. Accepts a string parameter, returns instance
- ``identify`` method. Acce... |
def urlopen(link):
"""Return urllib2 urlopen
"""
try:
return urllib2.urlopen(link)
except urllib2.URLError:
pass
except ValueError:
return ""
except KeyboardInterrupt:
print("")
raise SystemExit() | Return urllib2 urlopen | Below is the the instruction that describes the task:
### Input:
Return urllib2 urlopen
### Response:
def urlopen(link):
"""Return urllib2 urlopen
"""
try:
return urllib2.urlopen(link)
except urllib2.URLError:
pass
except ValueError:
return ""
except KeyboardInterrup... |
def set_providers(self, *providers):
"""Replace current providers with given ones"""
if self.providers:
self.clear()
for provider in providers:
self.add(provider) | Replace current providers with given ones | Below is the the instruction that describes the task:
### Input:
Replace current providers with given ones
### Response:
def set_providers(self, *providers):
"""Replace current providers with given ones"""
if self.providers:
self.clear()
for provider in providers:
se... |
def collect_string_fields(format_string) -> Iterable[Optional[str]]:
""" Given a format string, return an iterator
of all the valid format fields. It handles nested fields
as well.
"""
formatter = string.Formatter()
try:
parseiterator = formatter.parse(format_string)
for result i... | Given a format string, return an iterator
of all the valid format fields. It handles nested fields
as well. | Below is the the instruction that describes the task:
### Input:
Given a format string, return an iterator
of all the valid format fields. It handles nested fields
as well.
### Response:
def collect_string_fields(format_string) -> Iterable[Optional[str]]:
""" Given a format string, return an iterator
... |
def run_mainloop_with(self, target):
"""Start the OS's main loop to process asyncronous BLE events and then
run the specified target function in a background thread. Target
function should be a function that takes no parameters and optionally
return an integer response code. When the t... | Start the OS's main loop to process asyncronous BLE events and then
run the specified target function in a background thread. Target
function should be a function that takes no parameters and optionally
return an integer response code. When the target function stops
executing or return... | Below is the the instruction that describes the task:
### Input:
Start the OS's main loop to process asyncronous BLE events and then
run the specified target function in a background thread. Target
function should be a function that takes no parameters and optionally
return an integer respo... |
def currentRegion(self):
"""
Returns the current region based on the current cursor position.
:return <XDropZoneWidget>
"""
pos = QtGui.QCursor.pos()
pos = self.mapFromGlobal(pos)
for region in self.regions():
if region.testHovere... | Returns the current region based on the current cursor position.
:return <XDropZoneWidget> | Below is the the instruction that describes the task:
### Input:
Returns the current region based on the current cursor position.
:return <XDropZoneWidget>
### Response:
def currentRegion(self):
"""
Returns the current region based on the current cursor position.
... |
def decode_b64(data):
'''Wrapper for b64decode, without having to struggle with bytestrings.'''
byte_string = data.encode('utf-8')
decoded = base64.b64decode(byte_string)
return decoded.decode('utf-8') | Wrapper for b64decode, without having to struggle with bytestrings. | Below is the the instruction that describes the task:
### Input:
Wrapper for b64decode, without having to struggle with bytestrings.
### Response:
def decode_b64(data):
'''Wrapper for b64decode, without having to struggle with bytestrings.'''
byte_string = data.encode('utf-8')
decoded = base64.b64decod... |
def POST_AUTH(self, courseid): # pylint: disable=arguments-differ
""" POST request """
course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False)
errors = []
course_content = {}
try:
data = web.input()
course_content = self.course_fac... | POST request | Below is the the instruction that describes the task:
### Input:
POST request
### Response:
def POST_AUTH(self, courseid): # pylint: disable=arguments-differ
""" POST request """
course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False)
errors = []
course_cont... |
def fpy_interface(fpy, static, interface, typedict):
"""Splices the full list of subroutines and the module procedure list
into the static.f90 file.
:arg static: the string contents of the static.f90 file.
:arg interface: the name of the interface *field* being replaced.
:arg typedict: the dictiona... | Splices the full list of subroutines and the module procedure list
into the static.f90 file.
:arg static: the string contents of the static.f90 file.
:arg interface: the name of the interface *field* being replaced.
:arg typedict: the dictionary of dtypes and their kind and suffix combos. | Below is the the instruction that describes the task:
### Input:
Splices the full list of subroutines and the module procedure list
into the static.f90 file.
:arg static: the string contents of the static.f90 file.
:arg interface: the name of the interface *field* being replaced.
:arg typedict: the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.