code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def render(self, context):
"""
The default Django render() method for the tag.
This method resolves the filter expressions, and calls :func:`render_tag`.
"""
# Resolve token kwargs
tag_args = [expr.resolve(context) for expr in self.args] if self.compile_args else self.ar... | The default Django render() method for the tag.
This method resolves the filter expressions, and calls :func:`render_tag`. | Below is the the instruction that describes the task:
### Input:
The default Django render() method for the tag.
This method resolves the filter expressions, and calls :func:`render_tag`.
### Response:
def render(self, context):
"""
The default Django render() method for the tag.
... |
def _pdf(self, x, dist, cache):
"""Probability density function."""
return evaluation.evaluate_density(
dist, numpy.arctan(x), cache=cache)/(1+x*x) | Probability density function. | Below is the the instruction that describes the task:
### Input:
Probability density function.
### Response:
def _pdf(self, x, dist, cache):
"""Probability density function."""
return evaluation.evaluate_density(
dist, numpy.arctan(x), cache=cache)/(1+x*x) |
def _finalize_nonblock_blob(self, sd, metadata, digest):
# type: (SyncCopy, blobxfer.models.synccopy.Descriptor, dict,
# str) -> None
"""Finalize Non-Block blob
:param SyncCopy self: this
:param blobxfer.models.synccopy.Descriptor sd: synccopy descriptor
:param dic... | Finalize Non-Block blob
:param SyncCopy self: this
:param blobxfer.models.synccopy.Descriptor sd: synccopy descriptor
:param dict metadata: metadata dict
:param str digest: md5 digest | Below is the the instruction that describes the task:
### Input:
Finalize Non-Block blob
:param SyncCopy self: this
:param blobxfer.models.synccopy.Descriptor sd: synccopy descriptor
:param dict metadata: metadata dict
:param str digest: md5 digest
### Response:
def _finalize_nonblo... |
def mtFeatureExtractionToFile(fileName, midTermSize, midTermStep, shortTermSize, shortTermStep, outPutFile,
storeStFeatures=False, storeToCSV=False, PLOT=False):
"""
This function is used as a wrapper to:
a) read the content of a WAV file
b) perform mid-term feature extract... | This function is used as a wrapper to:
a) read the content of a WAV file
b) perform mid-term feature extraction on that signal
c) write the mid-term feature sequences to a numpy file | Below is the the instruction that describes the task:
### Input:
This function is used as a wrapper to:
a) read the content of a WAV file
b) perform mid-term feature extraction on that signal
c) write the mid-term feature sequences to a numpy file
### Response:
def mtFeatureExtractionToFile(fileName, m... |
def getscale(self):
"""Obtain the scale values along a dimension.
Args::
no argument
Returns::
list with the scale values; the list length is equal to the
dimension length; the element type is equal to the dimension
data type, as set when the 'setdimsc... | Obtain the scale values along a dimension.
Args::
no argument
Returns::
list with the scale values; the list length is equal to the
dimension length; the element type is equal to the dimension
data type, as set when the 'setdimscale()' method was called.
... | Below is the the instruction that describes the task:
### Input:
Obtain the scale values along a dimension.
Args::
no argument
Returns::
list with the scale values; the list length is equal to the
dimension length; the element type is equal to the dimension
... |
def lang(self):
""" Languages this text is in
:return: List of available languages
"""
return str(self.graph.value(self.asNode(), DC.language)) | Languages this text is in
:return: List of available languages | Below is the the instruction that describes the task:
### Input:
Languages this text is in
:return: List of available languages
### Response:
def lang(self):
""" Languages this text is in
:return: List of available languages
"""
return str(self.graph.value(self.asNode(), D... |
def read_moc_json(moc, filename=None, file=None):
"""Read JSON encoded data into a MOC.
Either a filename, or an open file object can be specified.
"""
if file is not None:
obj = _read_json(file)
else:
with open(filename, 'rb') as f:
obj = _read_json(f)
for (order,... | Read JSON encoded data into a MOC.
Either a filename, or an open file object can be specified. | Below is the the instruction that describes the task:
### Input:
Read JSON encoded data into a MOC.
Either a filename, or an open file object can be specified.
### Response:
def read_moc_json(moc, filename=None, file=None):
"""Read JSON encoded data into a MOC.
Either a filename, or an open file obje... |
def get_fleet(self, airline_key):
"""Get the fleet for a particular airline.
Given a airline code form the get_airlines() method output, this method returns the fleet for the airline.
Args:
airline_key (str): The code for the airline on flightradar24
Returns:
A... | Get the fleet for a particular airline.
Given a airline code form the get_airlines() method output, this method returns the fleet for the airline.
Args:
airline_key (str): The code for the airline on flightradar24
Returns:
A list of dicts, one for each aircraft in the ... | Below is the the instruction that describes the task:
### Input:
Get the fleet for a particular airline.
Given a airline code form the get_airlines() method output, this method returns the fleet for the airline.
Args:
airline_key (str): The code for the airline on flightradar24
... |
def connect(self, dests=[], name=None, id='', props={}):
'''Connect this port to other ports.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provi... | Connect this port to other ports.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provided.
@param name The name of the connection. If None, a suit... | Below is the the instruction that describes the task:
### Input:
Connect this port to other ports.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be prov... |
def read_raw_parser_conf(data: str) -> dict:
"""We expect to have a section like this
```
[commitizen]
name = cz_jira
files = [
"commitizen/__version__.py",
"pyproject.toml"
] # this tab at the end is important
```
"""
config = configparser.ConfigParser(allow_no... | We expect to have a section like this
```
[commitizen]
name = cz_jira
files = [
"commitizen/__version__.py",
"pyproject.toml"
] # this tab at the end is important
``` | Below is the the instruction that describes the task:
### Input:
We expect to have a section like this
```
[commitizen]
name = cz_jira
files = [
"commitizen/__version__.py",
"pyproject.toml"
] # this tab at the end is important
```
### Response:
def read_raw_parser_con... |
def result_subsets(self, rs):
"""Break a result set into subsets with the same keys.
:param rs: Result set, rows of a result as a list of dicts
:type rs: list of dict
:return: A set with distinct keys (tuples), and a dict, by these tuples, of max. widths for each column
"""
... | Break a result set into subsets with the same keys.
:param rs: Result set, rows of a result as a list of dicts
:type rs: list of dict
:return: A set with distinct keys (tuples), and a dict, by these tuples, of max. widths for each column | Below is the the instruction that describes the task:
### Input:
Break a result set into subsets with the same keys.
:param rs: Result set, rows of a result as a list of dicts
:type rs: list of dict
:return: A set with distinct keys (tuples), and a dict, by these tuples, of max. widths for ... |
def blockSignals( self, state ):
"""
Blocks the signals for this widget and its sub-parts.
:param state | <bool>
"""
super(XLocationWidget, self).blockSignals(state)
self._locationEdit.blockSignals(state)
self._locationButton.blockSignals(sta... | Blocks the signals for this widget and its sub-parts.
:param state | <bool> | Below is the the instruction that describes the task:
### Input:
Blocks the signals for this widget and its sub-parts.
:param state | <bool>
### Response:
def blockSignals( self, state ):
"""
Blocks the signals for this widget and its sub-parts.
:param ... |
def enable_call_trace():
""" Enable trace for calls to any function. """
def tracer(frame, event, arg):
if event == 'call':
co = frame.f_code
func_name = co.co_name
if func_name == 'write' or func_name == 'print':
# ignore write() calls from print stat... | Enable trace for calls to any function. | Below is the the instruction that describes the task:
### Input:
Enable trace for calls to any function.
### Response:
def enable_call_trace():
""" Enable trace for calls to any function. """
def tracer(frame, event, arg):
if event == 'call':
co = frame.f_code
func_name = co... |
def _get_model_param_names(cls):
r"""Get parameter names for the model"""
# fetch model parameters
if hasattr(cls, 'set_model_params'):
# introspect the constructor arguments to find the model parameters
# to represent
args, varargs, kw, default = getargspec_n... | r"""Get parameter names for the model | Below is the the instruction that describes the task:
### Input:
r"""Get parameter names for the model
### Response:
def _get_model_param_names(cls):
r"""Get parameter names for the model"""
# fetch model parameters
if hasattr(cls, 'set_model_params'):
# introspect the construct... |
def count_stages(self, matrix_name):
"""
Number of registered stages for given matrix name.
Parameters:
matrix_name (str): name of the matrix
Returns:
int: number of reported stages for given matrix name.
"""
return len(self.data[matrix_name]) if... | Number of registered stages for given matrix name.
Parameters:
matrix_name (str): name of the matrix
Returns:
int: number of reported stages for given matrix name. | Below is the the instruction that describes the task:
### Input:
Number of registered stages for given matrix name.
Parameters:
matrix_name (str): name of the matrix
Returns:
int: number of reported stages for given matrix name.
### Response:
def count_stages(self, matrix_... |
def commit_fw_db_result(self):
"""Calls routine to update the FW create/delete result in DB. """
fw_dict = self.get_fw_dict()
self.update_fw_db_result(fw_dict.get('fw_id'), fw_dict) | Calls routine to update the FW create/delete result in DB. | Below is the the instruction that describes the task:
### Input:
Calls routine to update the FW create/delete result in DB.
### Response:
def commit_fw_db_result(self):
"""Calls routine to update the FW create/delete result in DB. """
fw_dict = self.get_fw_dict()
self.update_fw_db_result(fw... |
def _open_url(cls, url):
"""Given a CFURL Python object, return an opened ExtAudioFileRef.
"""
file_obj = ctypes.c_void_p()
check(_coreaudio.ExtAudioFileOpenURL(
url._obj, ctypes.byref(file_obj)
))
return file_obj | Given a CFURL Python object, return an opened ExtAudioFileRef. | Below is the the instruction that describes the task:
### Input:
Given a CFURL Python object, return an opened ExtAudioFileRef.
### Response:
def _open_url(cls, url):
"""Given a CFURL Python object, return an opened ExtAudioFileRef.
"""
file_obj = ctypes.c_void_p()
check(_coreaudio.... |
def CheckHeaderFileIncluded(filename, include_state, error):
"""Logs an error if a source file does not include its header."""
# Do not check test files
fileinfo = FileInfo(filename)
if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
return
for ext in GetHeaderExtensions():
basefilename = filename... | Logs an error if a source file does not include its header. | Below is the the instruction that describes the task:
### Input:
Logs an error if a source file does not include its header.
### Response:
def CheckHeaderFileIncluded(filename, include_state, error):
"""Logs an error if a source file does not include its header."""
# Do not check test files
fileinfo = FileI... |
def transform_26_27(inst, new_inst, i, n, offset,
instructions, new_asm):
"""Change JUMP_IF_FALSE and JUMP_IF_TRUE to
POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE"""
if inst.opname in ('JUMP_IF_FALSE', 'JUMP_IF_TRUE'):
i += 1
assert i < n
assert instructions[i].opname =... | Change JUMP_IF_FALSE and JUMP_IF_TRUE to
POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE | Below is the the instruction that describes the task:
### Input:
Change JUMP_IF_FALSE and JUMP_IF_TRUE to
POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE
### Response:
def transform_26_27(inst, new_inst, i, n, offset,
instructions, new_asm):
"""Change JUMP_IF_FALSE and JUMP_IF_TRUE to
POP_JU... |
def kernel(self, kernel):
"""
Sets the kernel.
:param kernel: the kernel to set
:type kernel: Kernel
"""
result = javabridge.static_call(
"weka/classifiers/KernelHelper", "setKernel",
"(Ljava/lang/Object;Lweka/classifiers/functions/supportVector/K... | Sets the kernel.
:param kernel: the kernel to set
:type kernel: Kernel | Below is the the instruction that describes the task:
### Input:
Sets the kernel.
:param kernel: the kernel to set
:type kernel: Kernel
### Response:
def kernel(self, kernel):
"""
Sets the kernel.
:param kernel: the kernel to set
:type kernel: Kernel
"""
... |
def _create_axes_grid(length_plotters, rows, cols, **kwargs):
"""Create figure and axes for grids with multiple plots.
Parameters
----------
n_items : int
Number of panels required
rows : int
Number of rows
cols : int
Number of columns
Returns
-------
fig : ... | Create figure and axes for grids with multiple plots.
Parameters
----------
n_items : int
Number of panels required
rows : int
Number of rows
cols : int
Number of columns
Returns
-------
fig : matplotlib figure
ax : matplotlib axes | Below is the the instruction that describes the task:
### Input:
Create figure and axes for grids with multiple plots.
Parameters
----------
n_items : int
Number of panels required
rows : int
Number of rows
cols : int
Number of columns
Returns
-------
fig : ... |
def update_build_configuration(id, **kwargs):
"""
Update an existing BuildConfiguration with new information
:param id: ID of BuildConfiguration to update
:param name: Name of BuildConfiguration to update
:return:
"""
data = update_build_configuration_raw(id, **kwargs)
if data:
... | Update an existing BuildConfiguration with new information
:param id: ID of BuildConfiguration to update
:param name: Name of BuildConfiguration to update
:return: | Below is the the instruction that describes the task:
### Input:
Update an existing BuildConfiguration with new information
:param id: ID of BuildConfiguration to update
:param name: Name of BuildConfiguration to update
:return:
### Response:
def update_build_configuration(id, **kwargs):
"""
U... |
def sigma(G, corpus, featureset_name, B=None, **kwargs):
"""
Calculate sigma (from `Chen 2009 <http://arxiv.org/pdf/0904.1439.pdf>`_)
for all of the nodes in a :class:`.GraphCollection`\.
You can set parameters for burstness estimation using ``kwargs``:
========= ================================... | Calculate sigma (from `Chen 2009 <http://arxiv.org/pdf/0904.1439.pdf>`_)
for all of the nodes in a :class:`.GraphCollection`\.
You can set parameters for burstness estimation using ``kwargs``:
========= ===============================================================
Parameter Description
=====... | Below is the the instruction that describes the task:
### Input:
Calculate sigma (from `Chen 2009 <http://arxiv.org/pdf/0904.1439.pdf>`_)
for all of the nodes in a :class:`.GraphCollection`\.
You can set parameters for burstness estimation using ``kwargs``:
========= ================================... |
def symbol_bollinger(symbol='GOOG',
start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='close', cleaner=clean_dataframe,
window=20, sigma=1.):
"""Calculate the Bolinger indicator value
>>> symbol_bollinger("goog", '2008-1-1', '2008-2-1')[-1] # doctest: +ELLIPSIS, +NOR... | Calculate the Bolinger indicator value
>>> symbol_bollinger("goog", '2008-1-1', '2008-2-1')[-1] # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
-1.8782... | Below is the the instruction that describes the task:
### Input:
Calculate the Bolinger indicator value
>>> symbol_bollinger("goog", '2008-1-1', '2008-2-1')[-1] # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
-1.8782...
### Response:
def symbol_bollinger(symbol='GOOG',
start=datetime.datetime(2008, 1, 1)... |
async def unixlisten(path, onlink):
'''
Start an PF_UNIX server listening on the given path.
'''
info = {'path': path, 'unix': True}
async def onconn(reader, writer):
link = await Link.anit(reader, writer, info=info)
link.schedCoro(onlink(link))
return await asyncio.start_unix_se... | Start an PF_UNIX server listening on the given path. | Below is the the instruction that describes the task:
### Input:
Start an PF_UNIX server listening on the given path.
### Response:
async def unixlisten(path, onlink):
'''
Start an PF_UNIX server listening on the given path.
'''
info = {'path': path, 'unix': True}
async def onconn(reader, write... |
def set_comment(self, format, *args):
"""
Add comment to config item before saving to disk. You can add as many
comment lines as you like. If you use a null format, all comments are
deleted.
"""
return lib.zconfig_set_comment(self._as_parameter_, format, *args) | Add comment to config item before saving to disk. You can add as many
comment lines as you like. If you use a null format, all comments are
deleted. | Below is the the instruction that describes the task:
### Input:
Add comment to config item before saving to disk. You can add as many
comment lines as you like. If you use a null format, all comments are
deleted.
### Response:
def set_comment(self, format, *args):
"""
Add comment to config item be... |
def _query(self, variables, operation, evidence=None, joint=True):
"""
This is a generalized query method that can be used for both query and map query.
Parameters
----------
variables: list
list of variables for which you want to compute the probability
oper... | This is a generalized query method that can be used for both query and map query.
Parameters
----------
variables: list
list of variables for which you want to compute the probability
operation: str ('marginalize' | 'maximize')
The operation to do for passing mes... | Below is the the instruction that describes the task:
### Input:
This is a generalized query method that can be used for both query and map query.
Parameters
----------
variables: list
list of variables for which you want to compute the probability
operation: str ('margi... |
def getCurrentFadeColor(self, bBackground):
"""Get current fade color value."""
fn = self.function_table.getCurrentFadeColor
result = fn(bBackground)
return result | Get current fade color value. | Below is the the instruction that describes the task:
### Input:
Get current fade color value.
### Response:
def getCurrentFadeColor(self, bBackground):
"""Get current fade color value."""
fn = self.function_table.getCurrentFadeColor
result = fn(bBackground)
return result |
def Execute(cmd,
args,
time_limit=-1,
bypass_whitelist=False,
daemon=False,
use_client_context=False,
cwd=None):
"""Executes commands on the client.
This function is the only place where commands will be executed
by the GRR client. This make... | Executes commands on the client.
This function is the only place where commands will be executed
by the GRR client. This makes sure that all issued commands are compared to a
white list and no malicious commands are issued on the client machine.
Args:
cmd: The command to be executed.
args: List of arg... | Below is the the instruction that describes the task:
### Input:
Executes commands on the client.
This function is the only place where commands will be executed
by the GRR client. This makes sure that all issued commands are compared to a
white list and no malicious commands are issued on the client machine... |
def dataset(self, ref, load_all=False, exception=True):
"""Return a dataset, given a vid or id
:param ref: Vid or id for a dataset. If an id is provided, will it will return the one with the
largest revision number
:param load_all: Use a query that eagerly loads everything.
:re... | Return a dataset, given a vid or id
:param ref: Vid or id for a dataset. If an id is provided, will it will return the one with the
largest revision number
:param load_all: Use a query that eagerly loads everything.
:return: :class:`ambry.orm.Dataset` | Below is the the instruction that describes the task:
### Input:
Return a dataset, given a vid or id
:param ref: Vid or id for a dataset. If an id is provided, will it will return the one with the
largest revision number
:param load_all: Use a query that eagerly loads everything.
:... |
def createCard( self, parent, record ):
"""
Creates a new widget that will represent the card view for the inpued
record.
:param parent | <QWidget>
record | <orb.Table>
:return <QWidget> || None
"""
cls = se... | Creates a new widget that will represent the card view for the inpued
record.
:param parent | <QWidget>
record | <orb.Table>
:return <QWidget> || None | Below is the the instruction that describes the task:
### Input:
Creates a new widget that will represent the card view for the inpued
record.
:param parent | <QWidget>
record | <orb.Table>
:return <QWidget> || None
### Response:
def crea... |
def _get(self, obj):
''' Internal implementation of instance attribute access for the
``BasicPropertyDescriptor`` getter.
If the value has not been explicitly set by a user, return that
value. Otherwise, return the default.
Args:
obj (HasProps) : the instance to get... | Internal implementation of instance attribute access for the
``BasicPropertyDescriptor`` getter.
If the value has not been explicitly set by a user, return that
value. Otherwise, return the default.
Args:
obj (HasProps) : the instance to get a value of this property for
... | Below is the the instruction that describes the task:
### Input:
Internal implementation of instance attribute access for the
``BasicPropertyDescriptor`` getter.
If the value has not been explicitly set by a user, return that
value. Otherwise, return the default.
Args:
... |
def save_to_file(self, text, filename, name):
'''
Called by the engine to push a say command onto the queue.
@param text: Text to speak
@type text: unicode
@param name: Name to associate with the utterance
@type name: str
'''
self._push(self._driver.save_... | Called by the engine to push a say command onto the queue.
@param text: Text to speak
@type text: unicode
@param name: Name to associate with the utterance
@type name: str | Below is the the instruction that describes the task:
### Input:
Called by the engine to push a say command onto the queue.
@param text: Text to speak
@type text: unicode
@param name: Name to associate with the utterance
@type name: str
### Response:
def save_to_file(self, text, fi... |
def save_data(self, trigger_id, **data):
"""
let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the sa... | let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | Below is the the instruction that describes the task:
### Input:
let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of th... |
def intersection(self):
"""Compute the intersection with the given MOC.
This command takes the name of a MOC file and forms the intersection
of the running MOC with that file.
::
pymoctool a.fits --intersection b.fits --output intersection.fits
"""
if self... | Compute the intersection with the given MOC.
This command takes the name of a MOC file and forms the intersection
of the running MOC with that file.
::
pymoctool a.fits --intersection b.fits --output intersection.fits | Below is the the instruction that describes the task:
### Input:
Compute the intersection with the given MOC.
This command takes the name of a MOC file and forms the intersection
of the running MOC with that file.
::
pymoctool a.fits --intersection b.fits --output intersection... |
def _compute_mean(self, C, rup, dists, sites, imt):
"""
Returns the mean ground motion acceleration and velocity
"""
mean = (self._get_magnitude_scaling_term(C, rup.mag) +
self._get_distance_scaling_term(C, rup.mag, dists.rrup) +
self._get_site_amplificati... | Returns the mean ground motion acceleration and velocity | Below is the the instruction that describes the task:
### Input:
Returns the mean ground motion acceleration and velocity
### Response:
def _compute_mean(self, C, rup, dists, sites, imt):
"""
Returns the mean ground motion acceleration and velocity
"""
mean = (self._get_magnitude_sc... |
def _is_converged(self):
'''Determine if calculation converged; for a relaxation (static) run
we look for ionic (electronic) convergence in the output'''
if self.is_relaxed():
# relaxation run case
return self._get_line(['End of', 'Geometry Optimization'], self.outputf, r... | Determine if calculation converged; for a relaxation (static) run
we look for ionic (electronic) convergence in the output | Below is the the instruction that describes the task:
### Input:
Determine if calculation converged; for a relaxation (static) run
we look for ionic (electronic) convergence in the output
### Response:
def _is_converged(self):
'''Determine if calculation converged; for a relaxation (static) run
... |
def generate_operators(name, n_vars=1, hermitian=None, commutative=False):
"""Generates a number of commutative or noncommutative operators
:param name: The prefix in the symbolic representation of the noncommuting
variables. This will be suffixed by a number from 0 to
n_vars-... | Generates a number of commutative or noncommutative operators
:param name: The prefix in the symbolic representation of the noncommuting
variables. This will be suffixed by a number from 0 to
n_vars-1 if n_vars > 1.
:type name: str.
:param n_vars: The number of variables.
... | Below is the the instruction that describes the task:
### Input:
Generates a number of commutative or noncommutative operators
:param name: The prefix in the symbolic representation of the noncommuting
variables. This will be suffixed by a number from 0 to
n_vars-1 if n_vars >... |
def _stormpath_authenticate(self, username, password):
"""Check if Stormpath authentication works
:param username: Can be actual username or email
:param password: Account password
Returns an account object if successful or None otherwise.
"""
APPLICATION = get_applicat... | Check if Stormpath authentication works
:param username: Can be actual username or email
:param password: Account password
Returns an account object if successful or None otherwise. | Below is the the instruction that describes the task:
### Input:
Check if Stormpath authentication works
:param username: Can be actual username or email
:param password: Account password
Returns an account object if successful or None otherwise.
### Response:
def _stormpath_authenticate(... |
def get_neighbors(index, lattice_length, width=0, periodic=False):
"""Get the forward neighbors of a site in a lattice.
:param index: Linear index of operator.
:type index: int.
:param lattice_length: The size of the 2D lattice in either dimension
:type lattice_length: int.
:param width: Option... | Get the forward neighbors of a site in a lattice.
:param index: Linear index of operator.
:type index: int.
:param lattice_length: The size of the 2D lattice in either dimension
:type lattice_length: int.
:param width: Optional parameter to define width.
:type width: int.
:param periodic: O... | Below is the the instruction that describes the task:
### Input:
Get the forward neighbors of a site in a lattice.
:param index: Linear index of operator.
:type index: int.
:param lattice_length: The size of the 2D lattice in either dimension
:type lattice_length: int.
:param width: Optional pa... |
def server_hardware_types(self):
"""
Gets the ServerHardwareTypes API client.
Returns:
ServerHardwareTypes:
"""
if not self.__server_hardware_types:
self.__server_hardware_types = ServerHardwareTypes(
self.__connection)
return self... | Gets the ServerHardwareTypes API client.
Returns:
ServerHardwareTypes: | Below is the the instruction that describes the task:
### Input:
Gets the ServerHardwareTypes API client.
Returns:
ServerHardwareTypes:
### Response:
def server_hardware_types(self):
"""
Gets the ServerHardwareTypes API client.
Returns:
ServerHardwareTypes:... |
def _CreateShapePointFolder(self, shapes_folder, shape):
"""Create a KML Folder containing all the shape points in a shape.
The folder contains placemarks for each shapepoint.
Args:
shapes_folder: A KML Shape Folder ElementTree.Element instance
shape: The shape to plot.
Returns:
The... | Create a KML Folder containing all the shape points in a shape.
The folder contains placemarks for each shapepoint.
Args:
shapes_folder: A KML Shape Folder ElementTree.Element instance
shape: The shape to plot.
Returns:
The Folder ElementTree.Element instance or None. | Below is the the instruction that describes the task:
### Input:
Create a KML Folder containing all the shape points in a shape.
The folder contains placemarks for each shapepoint.
Args:
shapes_folder: A KML Shape Folder ElementTree.Element instance
shape: The shape to plot.
Returns:
... |
def _do_autopaginating_api_call(self, path, params, method, parser_func,
next_marker_xpath, next_marker_param_name,
next_type_xpath=None, parser_kwargs=None):
"""
Given an API method, the arguments passed to it, and a function to
hand parsing off to, loop through the record sets ... | Given an API method, the arguments passed to it, and a function to
hand parsing off to, loop through the record sets in the API call
until all records have been yielded.
:param str method: The API method on the endpoint.
:param dict params: The kwargs from the top-level API method.
... | Below is the the instruction that describes the task:
### Input:
Given an API method, the arguments passed to it, and a function to
hand parsing off to, loop through the record sets in the API call
until all records have been yielded.
:param str method: The API method on the endpoint.
... |
def merge(self, other):
"""
Merge properties of other into self
Raises ValueError if any them are a blank
"""
if self.is_blank() or other.is_blank():
raise ValueError('Cannot merge if there is a blank.')
else:
self.properties.update(other.properti... | Merge properties of other into self
Raises ValueError if any them are a blank | Below is the the instruction that describes the task:
### Input:
Merge properties of other into self
Raises ValueError if any them are a blank
### Response:
def merge(self, other):
"""
Merge properties of other into self
Raises ValueError if any them are a blank
"""
... |
def paste_template(self, template_name, template=None, deploy_dir=None):
" Paste template. "
LOGGER.debug("Paste template: %s" % template_name)
deploy_dir = deploy_dir or self.deploy_dir
template = template or self._get_template_path(template_name)
self.read([op.join(template, s... | Paste template. | Below is the the instruction that describes the task:
### Input:
Paste template.
### Response:
def paste_template(self, template_name, template=None, deploy_dir=None):
" Paste template. "
LOGGER.debug("Paste template: %s" % template_name)
deploy_dir = deploy_dir or self.deploy_dir
... |
def returnSplineList(dependentVar, independentVar, subsetPercentage=0.4,
cycles=10, minKnotPoints=10, initialKnots=200,
splineOrder=2, terminalExpansion=0.1
):
""" #TODO: docstring
Note: Expects sorted arrays.
:param dependentVar: #TODO: docst... | #TODO: docstring
Note: Expects sorted arrays.
:param dependentVar: #TODO: docstring
:param independentVar: #TODO: docstring
:param subsetPercentage: #TODO: docstring
:param cycles: #TODO: docstring
:param minKnotPoints: #TODO: docstring
:param initialKnots: #TODO: docstring
:param spli... | Below is the the instruction that describes the task:
### Input:
#TODO: docstring
Note: Expects sorted arrays.
:param dependentVar: #TODO: docstring
:param independentVar: #TODO: docstring
:param subsetPercentage: #TODO: docstring
:param cycles: #TODO: docstring
:param minKnotPoints: #TODO... |
def consume(self, event):
"""
process the current event, setup new state and teardown current state
"""
future_states = self.can(event)
new_state = future_states[0]
if len(future_states) > 1:
new_state = self.choose(event)
event.execute()
self... | process the current event, setup new state and teardown current state | Below is the the instruction that describes the task:
### Input:
process the current event, setup new state and teardown current state
### Response:
def consume(self, event):
"""
process the current event, setup new state and teardown current state
"""
future_states = self.can(event... |
def _Enum(docstring, *names):
"""Utility to generate enum classes used by annotations.
Args:
docstring: Docstring for the generated enum class.
*names: Enum names.
Returns:
A class that contains enum names as attributes.
"""
enums = dict(zip(names, range(len(names))))
reverse = dict((value, ke... | Utility to generate enum classes used by annotations.
Args:
docstring: Docstring for the generated enum class.
*names: Enum names.
Returns:
A class that contains enum names as attributes. | Below is the the instruction that describes the task:
### Input:
Utility to generate enum classes used by annotations.
Args:
docstring: Docstring for the generated enum class.
*names: Enum names.
Returns:
A class that contains enum names as attributes.
### Response:
def _Enum(docstring, *names):
... |
def preview(src_path):
''' Generates a preview of src_path in the requested format.
:returns: A list of preview paths, one for each page. Blank list if unsupported.
'''
preview = embedded_preview(src_path)
if not is_valid_preview(preview):
preview = generator_preview(src_path)
if not is_valid_preview(... | Generates a preview of src_path in the requested format.
:returns: A list of preview paths, one for each page. Blank list if unsupported. | Below is the the instruction that describes the task:
### Input:
Generates a preview of src_path in the requested format.
:returns: A list of preview paths, one for each page. Blank list if unsupported.
### Response:
def preview(src_path):
''' Generates a preview of src_path in the requested format.
:returns... |
def detect_os(self, ip):
"""
Runs the checker.py scripts to detect the os.
"""
process = subprocess.run(['python2', os.path.join(self.datadir, 'MS17-010', 'checker.py'), str(ip)], stdout=subprocess.PIPE)
out = process.stdout.decode('utf-8').split('\n')
system_os = ''
... | Runs the checker.py scripts to detect the os. | Below is the the instruction that describes the task:
### Input:
Runs the checker.py scripts to detect the os.
### Response:
def detect_os(self, ip):
"""
Runs the checker.py scripts to detect the os.
"""
process = subprocess.run(['python2', os.path.join(self.datadir, 'MS17-010',... |
def rehearse(
folders, references, handler,
repeat=0, roles=1, strict=False,
loop=None
):
"""Cast a set of objects into a sequence of scene scripts. Deliver the performance.
:param folders: A sequence of
:py:class:`turberfield.dialogue.model.SceneScript.Folder` objects.
:param reference... | Cast a set of objects into a sequence of scene scripts. Deliver the performance.
:param folders: A sequence of
:py:class:`turberfield.dialogue.model.SceneScript.Folder` objects.
:param references: A sequence of Python objects.
:param handler: A callable object. This will be invoked with every event... | Below is the the instruction that describes the task:
### Input:
Cast a set of objects into a sequence of scene scripts. Deliver the performance.
:param folders: A sequence of
:py:class:`turberfield.dialogue.model.SceneScript.Folder` objects.
:param references: A sequence of Python objects.
:pa... |
def write(self, data):
"""Encrypt and write the given bytes"""
self._check_not_closed()
if not data:
return 0
enc_data = self.encryptor.update(data)
self.next_fp.write(enc_data)
self.offset += len(data)
return len(data) | Encrypt and write the given bytes | Below is the the instruction that describes the task:
### Input:
Encrypt and write the given bytes
### Response:
def write(self, data):
"""Encrypt and write the given bytes"""
self._check_not_closed()
if not data:
return 0
enc_data = self.encryptor.update(data)
s... |
def _set_auto_fields(self, model_obj):
"""Set the values of the auto field using counter"""
for field_name, field_obj in \
self.entity_cls.meta_.auto_fields:
counter_key = f'{self.schema_name}_{field_name}'
if not (field_name in model_obj and model_obj[field_name]... | Set the values of the auto field using counter | Below is the the instruction that describes the task:
### Input:
Set the values of the auto field using counter
### Response:
def _set_auto_fields(self, model_obj):
"""Set the values of the auto field using counter"""
for field_name, field_obj in \
self.entity_cls.meta_.auto_fields:... |
def kxtrct(keywd, terms, nterms, instring, termlen=_default_len_out, stringlen=_default_len_out, substrlen=_default_len_out):
"""
Locate a keyword in a string and extract the substring from
the beginning of the first word following the keyword to the
beginning of the first subsequent recognized terminat... | Locate a keyword in a string and extract the substring from
the beginning of the first word following the keyword to the
beginning of the first subsequent recognized terminator of a list.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/kxtrct_c.html
:param keywd: Word that marks the beginning ... | Below is the the instruction that describes the task:
### Input:
Locate a keyword in a string and extract the substring from
the beginning of the first word following the keyword to the
beginning of the first subsequent recognized terminator of a list.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/c... |
def qos_rcv_queue_multicast_threshold_traffic_class4(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
rcv_queue = ET.SubElement(qos, "rcv-queue")
multicast = ET.SubElemen... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def qos_rcv_queue_multicast_threshold_traffic_class4(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com... |
def _get_text_id(self, witness):
"""Returns the database ID of the Text record for `witness`.
This may require creating such a record.
If `text`\'s checksum does not match an existing record's
checksum, the record's checksum is updated and all associated
TextNGram and TextHasNG... | Returns the database ID of the Text record for `witness`.
This may require creating such a record.
If `text`\'s checksum does not match an existing record's
checksum, the record's checksum is updated and all associated
TextNGram and TextHasNGram records are deleted.
:param wit... | Below is the the instruction that describes the task:
### Input:
Returns the database ID of the Text record for `witness`.
This may require creating such a record.
If `text`\'s checksum does not match an existing record's
checksum, the record's checksum is updated and all associated
... |
def update_variable(self, var, grad_var):
"""Update the variable and its slots."""
params = self.params
global_step = tf.to_float(self.global_step) + 1
# compute learning rate
lrate = params.learning_rate
if params.learning_rate_decay_scheme == "noam":
lrate *= tf.minimum(global_step * pa... | Update the variable and its slots. | Below is the the instruction that describes the task:
### Input:
Update the variable and its slots.
### Response:
def update_variable(self, var, grad_var):
"""Update the variable and its slots."""
params = self.params
global_step = tf.to_float(self.global_step) + 1
# compute learning rate
lrat... |
def NOAJS_metric(bpmn_graph):
"""
Returns the value of the NOAJS metric (Number of Activities, joins and splits)
for the BPMNDiagramGraph instance.
:param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model.
"""
activities_count = all_activities_count(bpmn_graph)
gateways_c... | Returns the value of the NOAJS metric (Number of Activities, joins and splits)
for the BPMNDiagramGraph instance.
:param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. | Below is the the instruction that describes the task:
### Input:
Returns the value of the NOAJS metric (Number of Activities, joins and splits)
for the BPMNDiagramGraph instance.
:param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model.
### Response:
def NOAJS_metric(bpmn_graph):
"""... |
def concatechain(*generators: types.FrameGenerator, separator: str = ''):
"""Return a generator that in each iteration takes one value from each of the
supplied generators, joins them together with the specified separator and
yields the result. Stops as soon as any iterator raises StopIteration and
retu... | Return a generator that in each iteration takes one value from each of the
supplied generators, joins them together with the specified separator and
yields the result. Stops as soon as any iterator raises StopIteration and
returns the value contained in it.
Primarily created for chaining string generat... | Below is the the instruction that describes the task:
### Input:
Return a generator that in each iteration takes one value from each of the
supplied generators, joins them together with the specified separator and
yields the result. Stops as soon as any iterator raises StopIteration and
returns the valu... |
def will_tag(self):
"""
Check whether the feed should be tagged
"""
wanttags = self.retrieve_config('Tag', 'no')
if wanttags == 'yes':
if aux.staggerexists:
willtag = True
else:
willtag = False
print(("You wa... | Check whether the feed should be tagged | Below is the the instruction that describes the task:
### Input:
Check whether the feed should be tagged
### Response:
def will_tag(self):
"""
Check whether the feed should be tagged
"""
wanttags = self.retrieve_config('Tag', 'no')
if wanttags == 'yes':
if aux.st... |
def set_output(self, outfile):
''' Set's the output file, currently only useful with context-managers.
Note:
This function is experimental and may not last.
'''
if self._orig_stdout: # restore Usted
sys.stdout = self._orig_stdout
self._stream = ... | Set's the output file, currently only useful with context-managers.
Note:
This function is experimental and may not last. | Below is the the instruction that describes the task:
### Input:
Set's the output file, currently only useful with context-managers.
Note:
This function is experimental and may not last.
### Response:
def set_output(self, outfile):
''' Set's the output file, currently only usef... |
def cos_zen(utc_time, lon, lat):
"""Cosine of the sun-zenith angle for *lon*, *lat* at *utc_time*.
utc_time: datetime.datetime instance of the UTC time
lon and lat in degrees.
"""
lon = np.deg2rad(lon)
lat = np.deg2rad(lat)
r_a, dec = sun_ra_dec(utc_time)
h__ = _local_hour_angle(utc_tim... | Cosine of the sun-zenith angle for *lon*, *lat* at *utc_time*.
utc_time: datetime.datetime instance of the UTC time
lon and lat in degrees. | Below is the the instruction that describes the task:
### Input:
Cosine of the sun-zenith angle for *lon*, *lat* at *utc_time*.
utc_time: datetime.datetime instance of the UTC time
lon and lat in degrees.
### Response:
def cos_zen(utc_time, lon, lat):
"""Cosine of the sun-zenith angle for *lon*, *lat* ... |
def configure(self, org_name, api_token=None, base_url='okta.com', ttl=None, max_ttl=None, bypass_okta_mfa=False,
mount_point=DEFAULT_MOUNT_POINT):
"""Configure the connection parameters for Okta.
This path honors the distinction between the create and update capabilities inside ACL p... | Configure the connection parameters for Okta.
This path honors the distinction between the create and update capabilities inside ACL policies.
Supported methods:
POST: /auth/{mount_point}/config. Produces: 204 (empty body)
:param org_name: Name of the organization to be used in t... | Below is the the instruction that describes the task:
### Input:
Configure the connection parameters for Okta.
This path honors the distinction between the create and update capabilities inside ACL policies.
Supported methods:
POST: /auth/{mount_point}/config. Produces: 204 (empty body... |
def translate_exception(exc_info, initial_skip=0):
"""If passed an exc_info it will automatically rewrite the exceptions
all the way down to the correct line numbers and frames.
"""
tb = exc_info[2]
frames = []
# skip some internal frames if wanted
for x in range(initial_skip):
if t... | If passed an exc_info it will automatically rewrite the exceptions
all the way down to the correct line numbers and frames. | Below is the the instruction that describes the task:
### Input:
If passed an exc_info it will automatically rewrite the exceptions
all the way down to the correct line numbers and frames.
### Response:
def translate_exception(exc_info, initial_skip=0):
"""If passed an exc_info it will automatically rewrit... |
def get_formatted_as_type(self, value, default=None, out_type=str):
"""Return formatted value for input value, returns as out_type.
Caveat emptor: if out_type is bool and value a string,
return will be True if str is 'True'. It will be False for all other
cases.
Args:
... | Return formatted value for input value, returns as out_type.
Caveat emptor: if out_type is bool and value a string,
return will be True if str is 'True'. It will be False for all other
cases.
Args:
value: the value to format
default: if value is None, set to thi... | Below is the the instruction that describes the task:
### Input:
Return formatted value for input value, returns as out_type.
Caveat emptor: if out_type is bool and value a string,
return will be True if str is 'True'. It will be False for all other
cases.
Args:
value: ... |
def fake_KATCP_client_resource_factory(
KATCPClientResourceClass, fake_options, resource_spec, *args, **kwargs):
"""Create a fake KATCPClientResource-like class and a fake-manager
Parameters
----------
KATCPClientResourceClass : class
Subclass of :class:`katcp.resource_client.KATCPClien... | Create a fake KATCPClientResource-like class and a fake-manager
Parameters
----------
KATCPClientResourceClass : class
Subclass of :class:`katcp.resource_client.KATCPClientResource`
fake_options : dict
Options for the faking process. Keys:
allow_any_request : bool, default F... | Below is the the instruction that describes the task:
### Input:
Create a fake KATCPClientResource-like class and a fake-manager
Parameters
----------
KATCPClientResourceClass : class
Subclass of :class:`katcp.resource_client.KATCPClientResource`
fake_options : dict
Options for the ... |
def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the object.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the report.
"""
if remove... | Creates a dictionary representation of the object.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the report. | Below is the the instruction that describes the task:
### Input:
Creates a dictionary representation of the object.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the report.
### Response:
def t... |
def k_to_R_value(k, SI=True):
r'''Returns the R-value of a substance given its thermal conductivity,
Will return R-value in SI units unless SI is false. SI units are
m^2 K/(W*inch); Imperial units of R-value are ft^2 deg F*h/(BTU*inch).
Parameters
----------
k : float
Thermal conductivi... | r'''Returns the R-value of a substance given its thermal conductivity,
Will return R-value in SI units unless SI is false. SI units are
m^2 K/(W*inch); Imperial units of R-value are ft^2 deg F*h/(BTU*inch).
Parameters
----------
k : float
Thermal conductivity of a substance [W/m/K]
SI :... | Below is the the instruction that describes the task:
### Input:
r'''Returns the R-value of a substance given its thermal conductivity,
Will return R-value in SI units unless SI is false. SI units are
m^2 K/(W*inch); Imperial units of R-value are ft^2 deg F*h/(BTU*inch).
Parameters
----------
k... |
def with_cpu(ops, model):
"""Wrap a model that should run on CPU, transferring inputs and outputs
as necessary."""
model.to_cpu()
def with_cpu_forward(inputs, drop=0.0):
cpu_outputs, backprop = model.begin_update(_to_cpu(inputs), drop=drop)
gpu_outputs = _to_device(ops, cpu_outputs)
... | Wrap a model that should run on CPU, transferring inputs and outputs
as necessary. | Below is the the instruction that describes the task:
### Input:
Wrap a model that should run on CPU, transferring inputs and outputs
as necessary.
### Response:
def with_cpu(ops, model):
"""Wrap a model that should run on CPU, transferring inputs and outputs
as necessary."""
model.to_cpu()
de... |
def bookmarks_index_changed(self):
"""Update the UI when the bookmarks combobox has changed."""
index = self.bookmarks_list.currentIndex()
if index >= 0:
self.tool.reset()
rectangle = self.bookmarks_list.itemData(index)
self.tool.set_rectangle(rectangle)
... | Update the UI when the bookmarks combobox has changed. | Below is the the instruction that describes the task:
### Input:
Update the UI when the bookmarks combobox has changed.
### Response:
def bookmarks_index_changed(self):
"""Update the UI when the bookmarks combobox has changed."""
index = self.bookmarks_list.currentIndex()
if index >= 0:
... |
def grad(func, argnum=None):
"""Return function that computes gradient of arguments.
Parameters
----------
func: a python function
The forward (loss) function.
argnum: an int or a list of int
The index of argument to calculate gradient for.
Returns
-------
grad_func: a ... | Return function that computes gradient of arguments.
Parameters
----------
func: a python function
The forward (loss) function.
argnum: an int or a list of int
The index of argument to calculate gradient for.
Returns
-------
grad_func: a python function
A function t... | Below is the the instruction that describes the task:
### Input:
Return function that computes gradient of arguments.
Parameters
----------
func: a python function
The forward (loss) function.
argnum: an int or a list of int
The index of argument to calculate gradient for.
Retu... |
def gather(self):
"""Return all the messages represented by this object. This will convert
the batch data into individual Message objects, which may be one
or more if multi_messages is set to `True`.
:rtype: list[~uamqp.message.Message]
"""
if self._multi_messages:
... | Return all the messages represented by this object. This will convert
the batch data into individual Message objects, which may be one
or more if multi_messages is set to `True`.
:rtype: list[~uamqp.message.Message] | Below is the the instruction that describes the task:
### Input:
Return all the messages represented by this object. This will convert
the batch data into individual Message objects, which may be one
or more if multi_messages is set to `True`.
:rtype: list[~uamqp.message.Message]
### Respon... |
def best_match(supported, header):
"""Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the format of the HTTP Accept: he... | Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the format of the HTTP Accept: header. The value of 'supported'
is a li... | Below is the the instruction that describes the task:
### Input:
Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the fo... |
def _attach_arguments(self):
"""Add the registered arguments to the parser."""
for arg in self.arguments:
self.parser.add_argument(*arg[0], **arg[1]) | Add the registered arguments to the parser. | Below is the the instruction that describes the task:
### Input:
Add the registered arguments to the parser.
### Response:
def _attach_arguments(self):
"""Add the registered arguments to the parser."""
for arg in self.arguments:
self.parser.add_argument(*arg[0], **arg[1]) |
def desymbolize(self):
"""
We believe this was a pointer and symbolized it before. Now we want to desymbolize it.
The following actions are performed:
- Reload content from memory
- Mark the sort as 'unknown'
:return: None
"""
self.sort = 'unknown'
... | We believe this was a pointer and symbolized it before. Now we want to desymbolize it.
The following actions are performed:
- Reload content from memory
- Mark the sort as 'unknown'
:return: None | Below is the the instruction that describes the task:
### Input:
We believe this was a pointer and symbolized it before. Now we want to desymbolize it.
The following actions are performed:
- Reload content from memory
- Mark the sort as 'unknown'
:return: None
### Response:
def de... |
def find_rt_coefficients_tot_intens(self, depth0=None):
"""Figure out total-intensity emission and absorption coefficients for the
current parameters.
**Argument**
*depth0* (default None)
A first guess to use for a good integration depth, in cm. If None,
the most re... | Figure out total-intensity emission and absorption coefficients for the
current parameters.
**Argument**
*depth0* (default None)
A first guess to use for a good integration depth, in cm. If None,
the most recent value is used.
**Return value**
A tuple ``(j... | Below is the the instruction that describes the task:
### Input:
Figure out total-intensity emission and absorption coefficients for the
current parameters.
**Argument**
*depth0* (default None)
A first guess to use for a good integration depth, in cm. If None,
the most ... |
def open(self):
"""
Load topology elements
"""
if self._status == "opened":
return
self.reset()
self._loading = True
self._status = "opened"
path = self._topology_file()
if not os.path.exists(path):
self._loading = False
... | Load topology elements | Below is the the instruction that describes the task:
### Input:
Load topology elements
### Response:
def open(self):
"""
Load topology elements
"""
if self._status == "opened":
return
self.reset()
self._loading = True
self._status = "opened"
... |
def load_file_to_str(path):
# type: (str) -> str
"""
Load file into a string removing newlines
Args:
path (str): Path to file
Returns:
str: String contents of file
"""
with open(path, 'rt') as f:
string = f.read().replace(linesep, '')
if not string:
rai... | Load file into a string removing newlines
Args:
path (str): Path to file
Returns:
str: String contents of file | Below is the the instruction that describes the task:
### Input:
Load file into a string removing newlines
Args:
path (str): Path to file
Returns:
str: String contents of file
### Response:
def load_file_to_str(path):
# type: (str) -> str
"""
Load file into a string removing n... |
def refresh(self):
"""刷新 Answer object 的属性.
例如赞同数增加了, 先调用 ``refresh()``
再访问 upvote_num属性, 可获得更新后的赞同数.
:return: None
"""
super().refresh()
self._html = None
self._upvote_num = None
self._content = None
self._collect_num = None
... | 刷新 Answer object 的属性.
例如赞同数增加了, 先调用 ``refresh()``
再访问 upvote_num属性, 可获得更新后的赞同数.
:return: None | Below is the the instruction that describes the task:
### Input:
刷新 Answer object 的属性.
例如赞同数增加了, 先调用 ``refresh()``
再访问 upvote_num属性, 可获得更新后的赞同数.
:return: None
### Response:
def refresh(self):
"""刷新 Answer object 的属性.
例如赞同数增加了, 先调用 ``refresh()``
再访问 upvot... |
def transfer_options(cls, obj, new_obj, backend=None):
"""
Transfers options for all backends from one object to another.
Drops any options defined in the supplied drop list.
"""
backend = cls.current_backend if backend is None else backend
type_name = type(new_obj).__nam... | Transfers options for all backends from one object to another.
Drops any options defined in the supplied drop list. | Below is the the instruction that describes the task:
### Input:
Transfers options for all backends from one object to another.
Drops any options defined in the supplied drop list.
### Response:
def transfer_options(cls, obj, new_obj, backend=None):
"""
Transfers options for all backends fr... |
def query(scope, blueprint, debug, output, with_metadata, realtime, **description):
"""
e.g.
googleanalytics --identity debrouwere --account debrouwere --webproperty http://debrouwere.org \
query pageviews \
--start yesterday --limit -10 --sort -pageviews \
--dimensi... | e.g.
googleanalytics --identity debrouwere --account debrouwere --webproperty http://debrouwere.org \
query pageviews \
--start yesterday --limit -10 --sort -pageviews \
--dimensions pagepath \
--debug | Below is the the instruction that describes the task:
### Input:
e.g.
googleanalytics --identity debrouwere --account debrouwere --webproperty http://debrouwere.org \
query pageviews \
--start yesterday --limit -10 --sort -pageviews \
--dimensions pagepath \
... |
def getopt(args, shortopts, longopts = []):
"""getopt(args, options[, long_options]) -> opts, args
Parses command line options and parameter list. args is the
argument list to be parsed, without the leading reference to the
running program. Typically, this means "sys.argv[1:]". shortopts
is the ... | getopt(args, options[, long_options]) -> opts, args
Parses command line options and parameter list. args is the
argument list to be parsed, without the leading reference to the
running program. Typically, this means "sys.argv[1:]". shortopts
is the string of option letters that the script wants to
... | Below is the the instruction that describes the task:
### Input:
getopt(args, options[, long_options]) -> opts, args
Parses command line options and parameter list. args is the
argument list to be parsed, without the leading reference to the
running program. Typically, this means "sys.argv[1:]". sho... |
def set_system_date_time(years=None,
months=None,
days=None,
hours=None,
minutes=None,
seconds=None,
utc_offset=None):
'''
Set the system date and time. Each argu... | Set the system date and time. Each argument is an element of the date, but
not required. If an element is not passed, the current system value for
that element will be used. For example, if you don't pass the year, the
current system year will be used. (Used by set_system_date and
set_system_time)
... | Below is the the instruction that describes the task:
### Input:
Set the system date and time. Each argument is an element of the date, but
not required. If an element is not passed, the current system value for
that element will be used. For example, if you don't pass the year, the
current system year ... |
def save(self, *args, **kwargs):
"""
Update ``self.modified``.
"""
self.modified = timezone.now()
super(AbstractBaseModel, self).save(*args, **kwargs) | Update ``self.modified``. | Below is the the instruction that describes the task:
### Input:
Update ``self.modified``.
### Response:
def save(self, *args, **kwargs):
"""
Update ``self.modified``.
"""
self.modified = timezone.now()
super(AbstractBaseModel, self).save(*args, **kwargs) |
def _scroll_when_linewrapping(self, ui_content, width, height, cli):
"""
Scroll to make sure the cursor position is visible and that we maintain
the requested scroll offset.
Set `self.horizontal_scroll/vertical_scroll`.
"""
scroll_offsets_bottom = self.scroll_offsets.bot... | Scroll to make sure the cursor position is visible and that we maintain
the requested scroll offset.
Set `self.horizontal_scroll/vertical_scroll`. | Below is the the instruction that describes the task:
### Input:
Scroll to make sure the cursor position is visible and that we maintain
the requested scroll offset.
Set `self.horizontal_scroll/vertical_scroll`.
### Response:
def _scroll_when_linewrapping(self, ui_content, width, height, cli):
... |
def abspath(self, path):
"""Return absolute path for a path relative to the current file."""
return os.path.abspath(os.path.join(os.path.dirname(self.path), path)) | Return absolute path for a path relative to the current file. | Below is the the instruction that describes the task:
### Input:
Return absolute path for a path relative to the current file.
### Response:
def abspath(self, path):
"""Return absolute path for a path relative to the current file."""
return os.path.abspath(os.path.join(os.path.dirname(self.path), p... |
def profile(self, name, parName, logemin=None, logemax=None,
reoptimize=False,
xvals=None, npts=None, savestate=True, **kwargs):
"""Profile the likelihood for the given source and parameter.
Parameters
----------
name : str
Source name.
... | Profile the likelihood for the given source and parameter.
Parameters
----------
name : str
Source name.
parName : str
Parameter name.
reoptimize : bool
Re-fit nuisance parameters at each step in the scan. Note
that enabling this o... | Below is the the instruction that describes the task:
### Input:
Profile the likelihood for the given source and parameter.
Parameters
----------
name : str
Source name.
parName : str
Parameter name.
reoptimize : bool
Re-fit nuisance param... |
def get_results_msg(self, results, study):
"""Return summary for GOEA results."""
# To convert msg list to string: "\n".join(msg)
msg = []
if results:
fmt = "{M:6,} GO terms are associated with {N:6,} of {NT:6,}"
stu_items, num_gos_stu = self.get_item_cnt(results,... | Return summary for GOEA results. | Below is the the instruction that describes the task:
### Input:
Return summary for GOEA results.
### Response:
def get_results_msg(self, results, study):
"""Return summary for GOEA results."""
# To convert msg list to string: "\n".join(msg)
msg = []
if results:
fmt = "{... |
def reindex_similar(self, other, n_sphere=4):
"""Reindex ``other`` to be similarly indexed as ``self``.
Returns a reindexed copy of ``other`` that minimizes the
distance for each atom to itself in the same chemical environemt
from ``self`` to ``other``.
Read more about the defin... | Reindex ``other`` to be similarly indexed as ``self``.
Returns a reindexed copy of ``other`` that minimizes the
distance for each atom to itself in the same chemical environemt
from ``self`` to ``other``.
Read more about the definition of the chemical environment in
:func:`Carte... | Below is the the instruction that describes the task:
### Input:
Reindex ``other`` to be similarly indexed as ``self``.
Returns a reindexed copy of ``other`` that minimizes the
distance for each atom to itself in the same chemical environemt
from ``self`` to ``other``.
Read more abo... |
def copy_file_to_master(
file_path,
remote_path='.',
username=None,
key_path=None
):
""" Copy a file to the Mesos master
"""
return copy_file(shakedown.master_ip(), file_path, remote_path, username, key_path) | Copy a file to the Mesos master | Below is the the instruction that describes the task:
### Input:
Copy a file to the Mesos master
### Response:
def copy_file_to_master(
file_path,
remote_path='.',
username=None,
key_path=None
):
""" Copy a file to the Mesos master
"""
return copy_file(shakedown.master_... |
def compile(self, name, contents, path=None):
"""Compile the given Thrift document into a Python module.
The generated module contains,
.. py:attribute:: __services__
A collection of generated classes for all services defined in the
thrift file.
.. version... | Compile the given Thrift document into a Python module.
The generated module contains,
.. py:attribute:: __services__
A collection of generated classes for all services defined in the
thrift file.
.. versionchanged:: 1.0
Renamed from ``services`` ... | Below is the the instruction that describes the task:
### Input:
Compile the given Thrift document into a Python module.
The generated module contains,
.. py:attribute:: __services__
A collection of generated classes for all services defined in the
thrift file.
... |
def Jar(env, target = None, source = [], *args, **kw):
"""
A pseudo-Builder wrapper around the separate Jar sources{File,Dir}
Builders.
"""
# jar target should not be a list so assume they passed
# no target and want implicit target to be made and the arg
# was actaully the list of sources
... | A pseudo-Builder wrapper around the separate Jar sources{File,Dir}
Builders. | Below is the the instruction that describes the task:
### Input:
A pseudo-Builder wrapper around the separate Jar sources{File,Dir}
Builders.
### Response:
def Jar(env, target = None, source = [], *args, **kw):
"""
A pseudo-Builder wrapper around the separate Jar sources{File,Dir}
Builders.
"""... |
def get_commit(self, commit_id: str) -> Commit:
"""
Get the specified commit.
:param str commit_id: hash of the commit to analyze
:return: Commit
"""
return Commit(self.repo.commit(commit_id), self.path, self.main_branch) | Get the specified commit.
:param str commit_id: hash of the commit to analyze
:return: Commit | Below is the the instruction that describes the task:
### Input:
Get the specified commit.
:param str commit_id: hash of the commit to analyze
:return: Commit
### Response:
def get_commit(self, commit_id: str) -> Commit:
"""
Get the specified commit.
:param str commit_id: ... |
def dump(node):
""" Dump initialized object structure to yaml
"""
from qubell.api.private.platform import Auth, QubellPlatform
from qubell.api.private.organization import Organization
from qubell.api.private.application import Application
from qubell.api.private.instance import Instance
fro... | Dump initialized object structure to yaml | Below is the the instruction that describes the task:
### Input:
Dump initialized object structure to yaml
### Response:
def dump(node):
""" Dump initialized object structure to yaml
"""
from qubell.api.private.platform import Auth, QubellPlatform
from qubell.api.private.organization import Organi... |
def read(self, structure):
""" Read and advance. """
start = self.offset
self.skip(structure.size)
return structure.read(self.buf, start) | Read and advance. | Below is the the instruction that describes the task:
### Input:
Read and advance.
### Response:
def read(self, structure):
""" Read and advance. """
start = self.offset
self.skip(structure.size)
return structure.read(self.buf, start) |
def _add_extra_handlers(self, handlers):
"""
Adds the extra handler (defined by the user)
:param handlers: a list of :py:class:`tornado.web.RequestHandler` instances.
:return:
"""
extra_handlers = [(h[0], h[1], {"microservice": self}) for h in self.extra_handlers]
... | Adds the extra handler (defined by the user)
:param handlers: a list of :py:class:`tornado.web.RequestHandler` instances.
:return: | Below is the the instruction that describes the task:
### Input:
Adds the extra handler (defined by the user)
:param handlers: a list of :py:class:`tornado.web.RequestHandler` instances.
:return:
### Response:
def _add_extra_handlers(self, handlers):
"""
Adds the extra handler (def... |
def unmasked(self, depth=0.01):
"""Return the unmasked overfitting metric for a given transit depth."""
return 1 - (np.hstack(self._O2) +
np.hstack(self._O3) / depth) / np.hstack(self._O1) | Return the unmasked overfitting metric for a given transit depth. | Below is the the instruction that describes the task:
### Input:
Return the unmasked overfitting metric for a given transit depth.
### Response:
def unmasked(self, depth=0.01):
"""Return the unmasked overfitting metric for a given transit depth."""
return 1 - (np.hstack(self._O2) +
... |
def read_settings(filename=None, defs=None):
"""
:param filename: Force load a file
:param defs: arguments you want to accept
:param default_filename: A config file from an environment variable (a fallback config file, if no other provided)
:return:
"""
# READ SETTINGS
defs = listwrap(de... | :param filename: Force load a file
:param defs: arguments you want to accept
:param default_filename: A config file from an environment variable (a fallback config file, if no other provided)
:return: | Below is the the instruction that describes the task:
### Input:
:param filename: Force load a file
:param defs: arguments you want to accept
:param default_filename: A config file from an environment variable (a fallback config file, if no other provided)
:return:
### Response:
def read_settings(filen... |
def write_acls(self, acls):
"""Writes the given autocorrelation lengths.
The ACL of each parameter is saved to
``[sampler_group]/acls/{param}']``. The maximum over all the
parameters is saved to the file's 'acl' attribute.
Parameters
----------
acls : dict
... | Writes the given autocorrelation lengths.
The ACL of each parameter is saved to
``[sampler_group]/acls/{param}']``. The maximum over all the
parameters is saved to the file's 'acl' attribute.
Parameters
----------
acls : dict
A dictionary of ACLs keyed by t... | Below is the the instruction that describes the task:
### Input:
Writes the given autocorrelation lengths.
The ACL of each parameter is saved to
``[sampler_group]/acls/{param}']``. The maximum over all the
parameters is saved to the file's 'acl' attribute.
Parameters
-----... |
def update_cluster_topology(self, assignment):
"""Modify the cluster-topology with given assignment.
Change the replica set of partitions as in given assignment.
:param assignment: dict representing actions to be used to update the current
cluster-topology
:raises: InvalidBroke... | Modify the cluster-topology with given assignment.
Change the replica set of partitions as in given assignment.
:param assignment: dict representing actions to be used to update the current
cluster-topology
:raises: InvalidBrokerIdError when broker-id is invalid
:raises: Invali... | Below is the the instruction that describes the task:
### Input:
Modify the cluster-topology with given assignment.
Change the replica set of partitions as in given assignment.
:param assignment: dict representing actions to be used to update the current
cluster-topology
:raises: I... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.