code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def check_owners(self, request, **resources):
""" Check parents of current resource.
Recursive scanning of the fact that the child has FK
to the parent and in resources we have right objects.
We check that in request like /author/1/book/2/page/3
Page object with pk=3 has Forei... | Check parents of current resource.
Recursive scanning of the fact that the child has FK
to the parent and in resources we have right objects.
We check that in request like /author/1/book/2/page/3
Page object with pk=3 has ForeignKey field linked to Book object
with pk=2 and Bo... | Below is the the instruction that describes the task:
### Input:
Check parents of current resource.
Recursive scanning of the fact that the child has FK
to the parent and in resources we have right objects.
We check that in request like /author/1/book/2/page/3
Page object with pk=... |
def parse_exposure(self, node):
"""
Parses <Exposure>
@param node: Node containing the <Exposure> element
@type node: xml.etree.Element
@raise ParseError: Raised when the exposure name is not
being defined in the context of a component type.
"""
if self... | Parses <Exposure>
@param node: Node containing the <Exposure> element
@type node: xml.etree.Element
@raise ParseError: Raised when the exposure name is not
being defined in the context of a component type. | Below is the the instruction that describes the task:
### Input:
Parses <Exposure>
@param node: Node containing the <Exposure> element
@type node: xml.etree.Element
@raise ParseError: Raised when the exposure name is not
being defined in the context of a component type.
### Respons... |
def _default_styles_xml(cls):
"""
Return a bytestream containing XML for a default styles part.
"""
path = os.path.join(
os.path.split(__file__)[0], '..', 'templates',
'default-styles.xml'
)
with open(path, 'rb') as f:
xml_bytes = f.rea... | Return a bytestream containing XML for a default styles part. | Below is the the instruction that describes the task:
### Input:
Return a bytestream containing XML for a default styles part.
### Response:
def _default_styles_xml(cls):
"""
Return a bytestream containing XML for a default styles part.
"""
path = os.path.join(
os.path.s... |
def get_restore_path(filename):
""" get_restore_path: returns path to directory for restoration points
Args:
filename (str): Name of file to store
Returns: string path to file
"""
path = os.path.join(RESTORE_DIRECTORY, FILE_STORE_LOCATION)
if not os.path.exists(path):
... | get_restore_path: returns path to directory for restoration points
Args:
filename (str): Name of file to store
Returns: string path to file | Below is the the instruction that describes the task:
### Input:
get_restore_path: returns path to directory for restoration points
Args:
filename (str): Name of file to store
Returns: string path to file
### Response:
def get_restore_path(filename):
""" get_restore_path: returns pa... |
def strip_tail(sequence, values):
"""Strip `values` from the end of `sequence`."""
return list(reversed(list(strip_head(reversed(sequence), values)))) | Strip `values` from the end of `sequence`. | Below is the the instruction that describes the task:
### Input:
Strip `values` from the end of `sequence`.
### Response:
def strip_tail(sequence, values):
"""Strip `values` from the end of `sequence`."""
return list(reversed(list(strip_head(reversed(sequence), values)))) |
def _install_maya(use_threaded_wrapper):
"""Helper function to Autodesk Maya support"""
from maya import utils, cmds
def threaded_wrapper(func, *args, **kwargs):
return utils.executeInMainThreadWithResult(
func, *args, **kwargs)
sys.stdout.write("Setting up Pyblish QML in Maya\n")
... | Helper function to Autodesk Maya support | Below is the the instruction that describes the task:
### Input:
Helper function to Autodesk Maya support
### Response:
def _install_maya(use_threaded_wrapper):
"""Helper function to Autodesk Maya support"""
from maya import utils, cmds
def threaded_wrapper(func, *args, **kwargs):
return utils... |
def _from_dict(cls, _dict):
"""Initialize a LeadingSentence object from a json dictionary."""
args = {}
if 'text' in _dict:
args['text'] = _dict.get('text')
if 'location' in _dict:
args['location'] = Location._from_dict(_dict.get('location'))
if 'element_l... | Initialize a LeadingSentence object from a json dictionary. | Below is the the instruction that describes the task:
### Input:
Initialize a LeadingSentence object from a json dictionary.
### Response:
def _from_dict(cls, _dict):
"""Initialize a LeadingSentence object from a json dictionary."""
args = {}
if 'text' in _dict:
args['text'] = _... |
def extract_archive(archive, solver, put_inside = False):
"""
Unzips/untars a previously downloaded archive file.
"""
print('extracting {0}'.format(archive))
root = os.path.join('solvers', solver if put_inside else '')
if archive.endswith('.tar.gz'):
if os.path.exists(archive[:-7])... | Unzips/untars a previously downloaded archive file. | Below is the the instruction that describes the task:
### Input:
Unzips/untars a previously downloaded archive file.
### Response:
def extract_archive(archive, solver, put_inside = False):
"""
Unzips/untars a previously downloaded archive file.
"""
print('extracting {0}'.format(archive))
r... |
def bundle_apps(self, bundle_name, bundle_apps):
"""Bundle multiple Job or Playbook Apps (.tcx files) into a single zip file.
Args:
bundle_name (str): The output name of the bundle zip file.
bundle_apps (list): A list of Apps to include in the bundle.
"""
bundle_... | Bundle multiple Job or Playbook Apps (.tcx files) into a single zip file.
Args:
bundle_name (str): The output name of the bundle zip file.
bundle_apps (list): A list of Apps to include in the bundle. | Below is the the instruction that describes the task:
### Input:
Bundle multiple Job or Playbook Apps (.tcx files) into a single zip file.
Args:
bundle_name (str): The output name of the bundle zip file.
bundle_apps (list): A list of Apps to include in the bundle.
### Response:
def... |
def sim_same_and_diff_category_samples(self, df, cat_index=1, dist_type='cosine',
equal_var=False, plot_roc=True,
precalc_dist=False, calc_roc=True):
'''
Calculate the similarity of samples from the same and different categori... | Calculate the similarity of samples from the same and different categories. The
cat_index gives the index of the category, where 1 in the first category | Below is the the instruction that describes the task:
### Input:
Calculate the similarity of samples from the same and different categories. The
cat_index gives the index of the category, where 1 in the first category
### Response:
def sim_same_and_diff_category_samples(self, df, cat_index=1, dist_type='cosi... |
def reciprocal_lattice(self) -> "Lattice":
"""
Return the reciprocal lattice. Note that this is the standard
reciprocal lattice used for solid state physics with a factor of 2 *
pi. If you are looking for the crystallographic reciprocal lattice,
use the reciprocal_lattice_crystal... | Return the reciprocal lattice. Note that this is the standard
reciprocal lattice used for solid state physics with a factor of 2 *
pi. If you are looking for the crystallographic reciprocal lattice,
use the reciprocal_lattice_crystallographic property.
The property is lazily generated fo... | Below is the the instruction that describes the task:
### Input:
Return the reciprocal lattice. Note that this is the standard
reciprocal lattice used for solid state physics with a factor of 2 *
pi. If you are looking for the crystallographic reciprocal lattice,
use the reciprocal_lattice_c... |
def calc_directional_aop(self, report, parameter, parameter_dir):
"""
Will calcuate the directional AOP (only sub-surface rrs for now) if the direction is defined using @
e.g. rrs@32.0:45 where <zenith-theta>:<azimuth-phi>
:param report: The planarrad report dictionary. should include... | Will calcuate the directional AOP (only sub-surface rrs for now) if the direction is defined using @
e.g. rrs@32.0:45 where <zenith-theta>:<azimuth-phi>
:param report: The planarrad report dictionary. should include the quadtables and the directional info
:param parameter: parameter to calc. ... | Below is the the instruction that describes the task:
### Input:
Will calcuate the directional AOP (only sub-surface rrs for now) if the direction is defined using @
e.g. rrs@32.0:45 where <zenith-theta>:<azimuth-phi>
:param report: The planarrad report dictionary. should include the quadtables a... |
def build(self):
"""Create and start up the internal workers."""
# If there's no output tube, it means that this stage
# is at the end of a fork (hasn't been linked to any stage downstream).
# Therefore, create one output tube.
if not self._output_tubes:
self._output... | Create and start up the internal workers. | Below is the the instruction that describes the task:
### Input:
Create and start up the internal workers.
### Response:
def build(self):
"""Create and start up the internal workers."""
# If there's no output tube, it means that this stage
# is at the end of a fork (hasn't been linked to a... |
def find(pattern):
'''
Find all instances where the pattern is in the running command
.. code-block:: bash
salt '*' onyx.cmd find '^snmp-server.*$'
.. note::
This uses the `re.MULTILINE` regex format for python, and runs the
regex against the whole show_run output.
'''
... | Find all instances where the pattern is in the running command
.. code-block:: bash
salt '*' onyx.cmd find '^snmp-server.*$'
.. note::
This uses the `re.MULTILINE` regex format for python, and runs the
regex against the whole show_run output. | Below is the the instruction that describes the task:
### Input:
Find all instances where the pattern is in the running command
.. code-block:: bash
salt '*' onyx.cmd find '^snmp-server.*$'
.. note::
This uses the `re.MULTILINE` regex format for python, and runs the
regex against ... |
def visit_attribute(self, node):
"""check if the getattr is an access to a class member
if so, register it. Also check for access to protected
class member from outside its class (but ignore __special__
methods)
"""
# Check self
if self._uses_mandatory_method_para... | check if the getattr is an access to a class member
if so, register it. Also check for access to protected
class member from outside its class (but ignore __special__
methods) | Below is the the instruction that describes the task:
### Input:
check if the getattr is an access to a class member
if so, register it. Also check for access to protected
class member from outside its class (but ignore __special__
methods)
### Response:
def visit_attribute(self, node):
... |
def projective_transform_by_points(
x, src, dst, map_args=None, output_shape=None, order=1, mode='constant', cval=0.0, clip=True,
preserve_range=False
):
"""Projective transform by given coordinates, usually 4 coordinates.
see `scikit-image <http://scikit-image.org/docs/dev/auto_examples/applic... | Projective transform by given coordinates, usually 4 coordinates.
see `scikit-image <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
src : list or numpy
... | Below is the the instruction that describes the task:
### Input:
Projective transform by given coordinates, usually 4 coordinates.
see `scikit-image <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__.
Parameters
-----------
x : numpy.array
An image with di... |
def browse_dialog_file():
"""
Open up a GUI browse dialog window and let to user select one or more files
:return str _path: Target directory path
:return list _files: List of selected files
"""
logger_directory.info("enter browse_dialog")
# We make files a list, because the user can multi... | Open up a GUI browse dialog window and let to user select one or more files
:return str _path: Target directory path
:return list _files: List of selected files | Below is the the instruction that describes the task:
### Input:
Open up a GUI browse dialog window and let to user select one or more files
:return str _path: Target directory path
:return list _files: List of selected files
### Response:
def browse_dialog_file():
"""
Open up a GUI browse dialog w... |
def deserialize(cls, dict_model):
"""Returns an unsaved class object based on the valid properties passed in."""
kwargs = {}
for f in cls._meta.concrete_fields:
if f.attname in dict_model:
kwargs[f.attname] = dict_model[f.attname]
return cls(**kwargs) | Returns an unsaved class object based on the valid properties passed in. | Below is the the instruction that describes the task:
### Input:
Returns an unsaved class object based on the valid properties passed in.
### Response:
def deserialize(cls, dict_model):
"""Returns an unsaved class object based on the valid properties passed in."""
kwargs = {}
for f in cls._... |
def finalize(self):
"""Clean up the object.
After calling this method the object can't be used anymore.
This will be reworked when changing the logging model.
"""
self.pause_session_logging()
self._disable_logging()
self._msg_callback = None
self._error_m... | Clean up the object.
After calling this method the object can't be used anymore.
This will be reworked when changing the logging model. | Below is the the instruction that describes the task:
### Input:
Clean up the object.
After calling this method the object can't be used anymore.
This will be reworked when changing the logging model.
### Response:
def finalize(self):
"""Clean up the object.
After calling this met... |
def delta_e_cie1976(lab_color_vector, lab_color_matrix):
"""
Calculates the Delta E (CIE1976) between `lab_color_vector` and all
colors in `lab_color_matrix`.
"""
return numpy.sqrt(
numpy.sum(numpy.power(lab_color_vector - lab_color_matrix, 2), axis=1)) | Calculates the Delta E (CIE1976) between `lab_color_vector` and all
colors in `lab_color_matrix`. | Below is the the instruction that describes the task:
### Input:
Calculates the Delta E (CIE1976) between `lab_color_vector` and all
colors in `lab_color_matrix`.
### Response:
def delta_e_cie1976(lab_color_vector, lab_color_matrix):
"""
Calculates the Delta E (CIE1976) between `lab_color_vector` and a... |
def highlight_text(args, parser):
"""Outputs the result of highlighting a text."""
tokenizer = utils.get_tokenizer(args)
corpus = utils.get_corpus(args)
output_dir = os.path.abspath(args.output)
if os.path.exists(output_dir):
parser.exit(status=3, message='Output directory already exists, '
... | Outputs the result of highlighting a text. | Below is the the instruction that describes the task:
### Input:
Outputs the result of highlighting a text.
### Response:
def highlight_text(args, parser):
"""Outputs the result of highlighting a text."""
tokenizer = utils.get_tokenizer(args)
corpus = utils.get_corpus(args)
output_dir = os.path.abs... |
def _track_class_related_field(cls, field):
""" Track a field on a related model """
# field = field on current model
# related_field = field on related model
(field, related_field) = field.split('__', 1)
field_obj = cls._meta.get_field(field)
related_cls = field_obj.remote_field.model
relat... | Track a field on a related model | Below is the the instruction that describes the task:
### Input:
Track a field on a related model
### Response:
def _track_class_related_field(cls, field):
""" Track a field on a related model """
# field = field on current model
# related_field = field on related model
(field, related_field) = fie... |
def relaxation_decomp(P, p0, obs, times=[1], k=None, ncv=None):
r"""Relaxation experiment.
The relaxation experiment describes the time-evolution
of an expectation value starting in a non-equilibrium
situation.
Parameters
----------
P : (M, M) ndarray
Transition matrix
p0 : (M,... | r"""Relaxation experiment.
The relaxation experiment describes the time-evolution
of an expectation value starting in a non-equilibrium
situation.
Parameters
----------
P : (M, M) ndarray
Transition matrix
p0 : (M,) ndarray (optional)
Initial distribution for a relaxation e... | Below is the the instruction that describes the task:
### Input:
r"""Relaxation experiment.
The relaxation experiment describes the time-evolution
of an expectation value starting in a non-equilibrium
situation.
Parameters
----------
P : (M, M) ndarray
Transition matrix
p0 : (M... |
def get_all_users(resource_root, view=None):
"""
Get all users.
@param resource_root: The root Resource object
@param view: View to materialize ('full' or 'summary').
@return: A list of ApiUser objects.
"""
return call(resource_root.get, USERS_PATH, ApiUser, True,
params=view and dict(view=view) or... | Get all users.
@param resource_root: The root Resource object
@param view: View to materialize ('full' or 'summary').
@return: A list of ApiUser objects. | Below is the the instruction that describes the task:
### Input:
Get all users.
@param resource_root: The root Resource object
@param view: View to materialize ('full' or 'summary').
@return: A list of ApiUser objects.
### Response:
def get_all_users(resource_root, view=None):
"""
Get all users.
@par... |
def remove_send_last_message(self, connection):
"""Removes a send_last_message function previously registered
with the Dispatcher.
Args:
connection (str): A locally unique identifier provided
by the receiver of messages.
"""
if connection in self._sen... | Removes a send_last_message function previously registered
with the Dispatcher.
Args:
connection (str): A locally unique identifier provided
by the receiver of messages. | Below is the the instruction that describes the task:
### Input:
Removes a send_last_message function previously registered
with the Dispatcher.
Args:
connection (str): A locally unique identifier provided
by the receiver of messages.
### Response:
def remove_send_last_... |
def get_users(self, course):
""" Returns a sorted list of users """
users = OrderedDict(sorted(list(self.user_manager.get_users_info(self.user_manager.get_course_registered_users(course)).items()),
key=lambda k: k[1][0] if k[1] is not None else ""))
return users | Returns a sorted list of users | Below is the the instruction that describes the task:
### Input:
Returns a sorted list of users
### Response:
def get_users(self, course):
""" Returns a sorted list of users """
users = OrderedDict(sorted(list(self.user_manager.get_users_info(self.user_manager.get_course_registered_users(course)).i... |
def extant_file(file):
"""
'Type' for argparse - checks that file exists but does not open.
"""
if not os.path.exists(file):
# Argparse uses the ArgumentTypeError to give a rejection message like:
# error: argument input: file does not exist
raise argparse.ArgumentTypeError("{0} ... | 'Type' for argparse - checks that file exists but does not open. | Below is the the instruction that describes the task:
### Input:
'Type' for argparse - checks that file exists but does not open.
### Response:
def extant_file(file):
"""
'Type' for argparse - checks that file exists but does not open.
"""
if not os.path.exists(file):
# Argparse uses the Ar... |
def fileinfo(self, fid):
"""Ask lain about what he knows about given file. If the given file
exists in the file dict, it will get updated."""
if not isinstance(fid, str):
raise TypeError("Your file ID must be a string")
try:
info = self.conn.make_call_with_cb("ge... | Ask lain about what he knows about given file. If the given file
exists in the file dict, it will get updated. | Below is the the instruction that describes the task:
### Input:
Ask lain about what he knows about given file. If the given file
exists in the file dict, it will get updated.
### Response:
def fileinfo(self, fid):
"""Ask lain about what he knows about given file. If the given file
exists i... |
def trim_shared_prefix(ref, alt):
"""
Sometimes mutations are given with a shared prefix between the reference
and alternate strings. Examples: C>CT (nucleotides) or GYFP>G (amino acids).
This function trims the common prefix and returns the disjoint ref
and alt strings, along with the shared prefi... | Sometimes mutations are given with a shared prefix between the reference
and alternate strings. Examples: C>CT (nucleotides) or GYFP>G (amino acids).
This function trims the common prefix and returns the disjoint ref
and alt strings, along with the shared prefix. | Below is the the instruction that describes the task:
### Input:
Sometimes mutations are given with a shared prefix between the reference
and alternate strings. Examples: C>CT (nucleotides) or GYFP>G (amino acids).
This function trims the common prefix and returns the disjoint ref
and alt strings, alon... |
def remove_object(self, name):
"""
Remove the object exposed under that name. If no object is registered under the supplied
name, a RuntimeError is raised.
:param name: Name of object to be removed.
"""
if name not in self._object_map:
raise RuntimeError('No ... | Remove the object exposed under that name. If no object is registered under the supplied
name, a RuntimeError is raised.
:param name: Name of object to be removed. | Below is the the instruction that describes the task:
### Input:
Remove the object exposed under that name. If no object is registered under the supplied
name, a RuntimeError is raised.
:param name: Name of object to be removed.
### Response:
def remove_object(self, name):
"""
Remo... |
def devop_read(self, args, bustype):
'''read from device'''
if len(args) < 5:
print("Usage: devop read <spi|i2c> name bus address regstart count")
return
name = args[0]
bus = int(args[1],base=0)
address = int(args[2],base=0)
reg = int(args[3],base=... | read from device | Below is the the instruction that describes the task:
### Input:
read from device
### Response:
def devop_read(self, args, bustype):
'''read from device'''
if len(args) < 5:
print("Usage: devop read <spi|i2c> name bus address regstart count")
return
name = args[0]
... |
def get_events_by_tripI_and_dsut(self, trip_I, day_start_ut,
start_ut=None, end_ut=None):
"""
Get trip data as a list of events (i.e. dicts).
Parameters
----------
trip_I : int
shorthand index of the trip.
day_start_ut : i... | Get trip data as a list of events (i.e. dicts).
Parameters
----------
trip_I : int
shorthand index of the trip.
day_start_ut : int
the start time of the day in unix time (seconds)
start_ut : int, optional
consider only events that start after ... | Below is the the instruction that describes the task:
### Input:
Get trip data as a list of events (i.e. dicts).
Parameters
----------
trip_I : int
shorthand index of the trip.
day_start_ut : int
the start time of the day in unix time (seconds)
start_... |
def enable(self):
"""
Enable message carbons.
:raises RuntimeError: if the server does not support message carbons.
:raises aioxmpp.XMPPError: if the server responded with an error to the
request.
:raises: as specified in :meth:`aioxmpp.Client.... | Enable message carbons.
:raises RuntimeError: if the server does not support message carbons.
:raises aioxmpp.XMPPError: if the server responded with an error to the
request.
:raises: as specified in :meth:`aioxmpp.Client.send` | Below is the the instruction that describes the task:
### Input:
Enable message carbons.
:raises RuntimeError: if the server does not support message carbons.
:raises aioxmpp.XMPPError: if the server responded with an error to the
request.
:raises: as spec... |
def wait_for_readability(self):
"""
Stop current thread until the channel is readable.
:Return: `False` if it won't be readable (e.g. is closed)
"""
with self.lock:
while True:
if self._socket is None or self._eof:
return False
... | Stop current thread until the channel is readable.
:Return: `False` if it won't be readable (e.g. is closed) | Below is the the instruction that describes the task:
### Input:
Stop current thread until the channel is readable.
:Return: `False` if it won't be readable (e.g. is closed)
### Response:
def wait_for_readability(self):
"""
Stop current thread until the channel is readable.
:Retur... |
def set_position(x, y, stream=STD_OUTPUT_HANDLE):
''' Sets current position of the cursor. '''
stream = kernel32.GetStdHandle(stream)
value = x + (y << 16)
kernel32.SetConsoleCursorPosition(stream, c_long(value)) | Sets current position of the cursor. | Below is the the instruction that describes the task:
### Input:
Sets current position of the cursor.
### Response:
def set_position(x, y, stream=STD_OUTPUT_HANDLE):
''' Sets current position of the cursor. '''
stream = kernel32.GetStdHandle(stream)
value = x + (y << 16)
kernel32.SetConsoleCursorPo... |
def screenshot(self):
"""Take screenshot
Return:
PIL.Image
"""
url = urljoin(self.__device_url, "screenshot")
r = httpdo('GET', url)
raw_image = base64.b64decode(r.value)
return Image.open(StringIO(raw_image)) | Take screenshot
Return:
PIL.Image | Below is the the instruction that describes the task:
### Input:
Take screenshot
Return:
PIL.Image
### Response:
def screenshot(self):
"""Take screenshot
Return:
PIL.Image
"""
url = urljoin(self.__device_url, "screenshot")
r = httpdo('... |
def _set_valid_lifetime(self, v, load=False):
"""
Setter method for valid_lifetime, mapped from YANG variable /interface/fortygigabitethernet/ipv6/ipv6_nd_ra/ipv6_intf_cmds/nd/prefix/lifetime/valid_lifetime (common-def:time-interval-sec)
If this variable is read-only (config: false) in the
source YANG f... | Setter method for valid_lifetime, mapped from YANG variable /interface/fortygigabitethernet/ipv6/ipv6_nd_ra/ipv6_intf_cmds/nd/prefix/lifetime/valid_lifetime (common-def:time-interval-sec)
If this variable is read-only (config: false) in the
source YANG file, then _set_valid_lifetime is considered as a private
... | Below is the the instruction that describes the task:
### Input:
Setter method for valid_lifetime, mapped from YANG variable /interface/fortygigabitethernet/ipv6/ipv6_nd_ra/ipv6_intf_cmds/nd/prefix/lifetime/valid_lifetime (common-def:time-interval-sec)
If this variable is read-only (config: false) in the
so... |
async def get_power_parameters(self):
"""Get the power paramters for this node."""
data = await self._handler.power_parameters(system_id=self.system_id)
return data | Get the power paramters for this node. | Below is the the instruction that describes the task:
### Input:
Get the power paramters for this node.
### Response:
async def get_power_parameters(self):
"""Get the power paramters for this node."""
data = await self._handler.power_parameters(system_id=self.system_id)
return data |
async def __handle_ping(self, _ : Ping):
""" Handle a Ping message. Pong the backend """
self.__last_ping = time.time()
await ZMQUtils.send(self.__backend_socket, Pong()) | Handle a Ping message. Pong the backend | Below is the the instruction that describes the task:
### Input:
Handle a Ping message. Pong the backend
### Response:
async def __handle_ping(self, _ : Ping):
""" Handle a Ping message. Pong the backend """
self.__last_ping = time.time()
await ZMQUtils.send(self.__backend_socket, Pong()) |
def __query_options(self):
"""Get the query options string to use for this query."""
options = 0
if self.__tailable:
options |= _QUERY_OPTIONS["tailable_cursor"]
if self.__slave_okay or self.__pool._slave_okay:
options |= _QUERY_OPTIONS["slave_okay"]
if no... | Get the query options string to use for this query. | Below is the the instruction that describes the task:
### Input:
Get the query options string to use for this query.
### Response:
def __query_options(self):
"""Get the query options string to use for this query."""
options = 0
if self.__tailable:
options |= _QUERY_OPTIONS["tail... |
def query_raw(self, query, order_by=None, limit=None, offset=0):
"""
Do a full-text query on the OpenSearch API using the format specified in
https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
DEPRECATED: use :meth:`query(raw=...) <.query>` instead. This method w... | Do a full-text query on the OpenSearch API using the format specified in
https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
DEPRECATED: use :meth:`query(raw=...) <.query>` instead. This method will be removed in the next major release.
Parameters
----------
... | Below is the the instruction that describes the task:
### Input:
Do a full-text query on the OpenSearch API using the format specified in
https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
DEPRECATED: use :meth:`query(raw=...) <.query>` instead. This method will be removed i... |
def view(self, shape=None, chunks=None, dtype=None,
fill_value=None, filters=None, read_only=None,
synchronizer=None):
"""Return an array sharing the same data.
Parameters
----------
shape : int or tuple of ints
Array shape.
chunks : int or ... | Return an array sharing the same data.
Parameters
----------
shape : int or tuple of ints
Array shape.
chunks : int or tuple of ints, optional
Chunk shape.
dtype : string or dtype, optional
NumPy dtype.
fill_value : object
... | Below is the the instruction that describes the task:
### Input:
Return an array sharing the same data.
Parameters
----------
shape : int or tuple of ints
Array shape.
chunks : int or tuple of ints, optional
Chunk shape.
dtype : string or dtype, optio... |
def find_task(self, request, context):
"""Finds one specific task."""
_log_request(request, context)
task = self.listener.memory.tasks.get(request.task_uuid)
if not task:
return clearly_pb2.TaskMessage()
return ClearlyServer._event_to_pb(task)[1] | Finds one specific task. | Below is the the instruction that describes the task:
### Input:
Finds one specific task.
### Response:
def find_task(self, request, context):
"""Finds one specific task."""
_log_request(request, context)
task = self.listener.memory.tasks.get(request.task_uuid)
if not task:
... |
def reprovision_and_retry(func):
"""
Wraps the `errback` callback of the API functions, automatically trying to
re-provision if the app ID can not be found during the operation. If that's
unsuccessful, it will raise the UnknownAppID error.
"""
@functools.wraps(func)
def wrapper(*a, **kw):
errback = kw... | Wraps the `errback` callback of the API functions, automatically trying to
re-provision if the app ID can not be found during the operation. If that's
unsuccessful, it will raise the UnknownAppID error. | Below is the the instruction that describes the task:
### Input:
Wraps the `errback` callback of the API functions, automatically trying to
re-provision if the app ID can not be found during the operation. If that's
unsuccessful, it will raise the UnknownAppID error.
### Response:
def reprovision_and_retry(fun... |
def radio_calibration_send(self, aileron, elevator, rudder, gyro, pitch, throttle, force_mavlink1=False):
'''
Complete set of calibration parameters for the radio
aileron : Aileron setpoints: left, center, right (uint16_t)
elevator ... | Complete set of calibration parameters for the radio
aileron : Aileron setpoints: left, center, right (uint16_t)
elevator : Elevator setpoints: nose down, center, nose up (uint16_t)
rudder : Rudder setpoints: nose lef... | Below is the the instruction that describes the task:
### Input:
Complete set of calibration parameters for the radio
aileron : Aileron setpoints: left, center, right (uint16_t)
elevator : Elevator setpoints: nose down, center, nose up (uint16_t)
... |
def states(self):
"""
All valid states; "Q" in the mathematical description of a state
machine.
"""
return frozenset(
chain.from_iterable(
(inState, outState)
for
(inState, inputSymbol, outState, outputSymbol)
... | All valid states; "Q" in the mathematical description of a state
machine. | Below is the the instruction that describes the task:
### Input:
All valid states; "Q" in the mathematical description of a state
machine.
### Response:
def states(self):
"""
All valid states; "Q" in the mathematical description of a state
machine.
"""
return frozens... |
def pypi_register(server='pypitest'):
"""Register and prep user for PyPi upload.
.. note:: May need to weak ~/.pypirc file per issue:
http://stackoverflow.com/questions/1569315
"""
base_command = 'python setup.py register'
if server == 'pypitest':
command = base_command + ' -r http... | Register and prep user for PyPi upload.
.. note:: May need to weak ~/.pypirc file per issue:
http://stackoverflow.com/questions/1569315 | Below is the the instruction that describes the task:
### Input:
Register and prep user for PyPi upload.
.. note:: May need to weak ~/.pypirc file per issue:
http://stackoverflow.com/questions/1569315
### Response:
def pypi_register(server='pypitest'):
"""Register and prep user for PyPi upload.
... |
def requires_private_key(func):
"""
Decorator for functions that require the private key to be defined.
"""
def func_wrapper(self, *args, **kwargs):
if hasattr(self, "_DiffieHellman__private_key"):
func(self, *args, **kwargs)
else:
self.generate_private_key()
... | Decorator for functions that require the private key to be defined. | Below is the the instruction that describes the task:
### Input:
Decorator for functions that require the private key to be defined.
### Response:
def requires_private_key(func):
"""
Decorator for functions that require the private key to be defined.
"""
def func_wrapper(self, *args, **kwargs):
... |
def read_estimations(est_file, boundaries_id, labels_id=None, **params):
"""Reads the estimations (boundaries and/or labels) from a jams file
containing the estimations of an algorithm.
Parameters
----------
est_file : str
Path to the estimated file (JAMS file).
boundaries_id : str
... | Reads the estimations (boundaries and/or labels) from a jams file
containing the estimations of an algorithm.
Parameters
----------
est_file : str
Path to the estimated file (JAMS file).
boundaries_id : str
Identifier of the algorithm used to compute the boundaries.
labels_id : ... | Below is the the instruction that describes the task:
### Input:
Reads the estimations (boundaries and/or labels) from a jams file
containing the estimations of an algorithm.
Parameters
----------
est_file : str
Path to the estimated file (JAMS file).
boundaries_id : str
Identif... |
def binary_value_or_stdin(value):
"""
Return fsencoded value or read raw data from stdin if value is None.
"""
if value is None:
reader = io.open(sys.stdin.fileno(), mode='rb', closefd=False)
return reader.read()
elif six.PY3:
return os.fsencode(value)
else:
retur... | Return fsencoded value or read raw data from stdin if value is None. | Below is the the instruction that describes the task:
### Input:
Return fsencoded value or read raw data from stdin if value is None.
### Response:
def binary_value_or_stdin(value):
"""
Return fsencoded value or read raw data from stdin if value is None.
"""
if value is None:
reader = io.op... |
def get_column_list_prefixed(self):
"""
Returns a list of columns
"""
return map(
lambda x: ".".join([self.name, x]),
self.columns
) | Returns a list of columns | Below is the the instruction that describes the task:
### Input:
Returns a list of columns
### Response:
def get_column_list_prefixed(self):
"""
Returns a list of columns
"""
return map(
lambda x: ".".join([self.name, x]),
self.columns
) |
def _get_policies(minion_id, config):
'''
Get the policies that should be applied to a token for minion_id
'''
_, grains, _ = salt.utils.minions.get_minion_data(minion_id, __opts__)
policy_patterns = config.get(
'policies',
['saltstac... | Get the policies that should be applied to a token for minion_id | Below is the the instruction that describes the task:
### Input:
Get the policies that should be applied to a token for minion_id
### Response:
def _get_policies(minion_id, config):
'''
Get the policies that should be applied to a token for minion_id
'''
_, grains, _ = salt.utils.minions.get_minion... |
def show_configure(self):
"""
Show the configuration window, or deiconify (un-minimise) it if it's already open.
"""
logging.info("Displaying configuration window")
self.configWindow.show()
self.configWindow.showNormal()
self.configWindow.activateWindow() | Show the configuration window, or deiconify (un-minimise) it if it's already open. | Below is the the instruction that describes the task:
### Input:
Show the configuration window, or deiconify (un-minimise) it if it's already open.
### Response:
def show_configure(self):
"""
Show the configuration window, or deiconify (un-minimise) it if it's already open.
"""
logg... |
def chart_maker(Int, Top, start=100, outfile='chart.txt'):
"""
Makes a chart for performing IZZI experiments. Print out the file and
tape it to the oven. This chart will help keep track of the different
steps.
Z : performed in zero field - enter the temperature XXX.0 in the sio
formatted me... | Makes a chart for performing IZZI experiments. Print out the file and
tape it to the oven. This chart will help keep track of the different
steps.
Z : performed in zero field - enter the temperature XXX.0 in the sio
formatted measurement file created by the LabView program
I : performed in the ... | Below is the the instruction that describes the task:
### Input:
Makes a chart for performing IZZI experiments. Print out the file and
tape it to the oven. This chart will help keep track of the different
steps.
Z : performed in zero field - enter the temperature XXX.0 in the sio
formatted meas... |
def download(self, obj, path=None, show_progress=True, resume=True,
auto_retry=True, proapi=False):
"""
Download a file
:param obj: :class:`.File` object
:param str path: local path
:param bool show_progress: whether to show download progress
:param bool... | Download a file
:param obj: :class:`.File` object
:param str path: local path
:param bool show_progress: whether to show download progress
:param bool resume: whether to resume on unfinished downloads
identified by filename
:param bool auto_retry: whether to retry au... | Below is the the instruction that describes the task:
### Input:
Download a file
:param obj: :class:`.File` object
:param str path: local path
:param bool show_progress: whether to show download progress
:param bool resume: whether to resume on unfinished downloads
ident... |
def convert_field(self, value, conversion):
"""
Define some extra field conversion functions.
"""
try: # If the normal behaviour works, do it.
s = super(CustomFormatter, self)
return s.convert_field(value, conversion)
except ValueError:
funcs ... | Define some extra field conversion functions. | Below is the the instruction that describes the task:
### Input:
Define some extra field conversion functions.
### Response:
def convert_field(self, value, conversion):
"""
Define some extra field conversion functions.
"""
try: # If the normal behaviour works, do it.
s ... |
def tas2eas(Vtas, H):
"""True Airspeed to Equivalent Airspeed"""
rho = density(H)
Veas = Vtas * np.sqrt(rho/rho0)
return Veas | True Airspeed to Equivalent Airspeed | Below is the the instruction that describes the task:
### Input:
True Airspeed to Equivalent Airspeed
### Response:
def tas2eas(Vtas, H):
"""True Airspeed to Equivalent Airspeed"""
rho = density(H)
Veas = Vtas * np.sqrt(rho/rho0)
return Veas |
def _Download(campaign, subcampaign):
'''
Download all stars from a given campaign. This is
called from ``missions/k2/download.pbs``
'''
# Are we doing a subcampaign?
if subcampaign != -1:
campaign = campaign + 0.1 * subcampaign
# Get all star IDs for this campaign
stars = [s[0... | Download all stars from a given campaign. This is
called from ``missions/k2/download.pbs`` | Below is the the instruction that describes the task:
### Input:
Download all stars from a given campaign. This is
called from ``missions/k2/download.pbs``
### Response:
def _Download(campaign, subcampaign):
'''
Download all stars from a given campaign. This is
called from ``missions/k2/download.pb... |
def delete_refresh_token(self, refresh_token):
"""
Deletes a refresh token after use
:param refresh_token: The refresh token to delete.
"""
access_token = self.fetch_by_refresh_token(refresh_token)
self.mc.delete(self._generate_cache_key(access_token.token))
self.... | Deletes a refresh token after use
:param refresh_token: The refresh token to delete. | Below is the the instruction that describes the task:
### Input:
Deletes a refresh token after use
:param refresh_token: The refresh token to delete.
### Response:
def delete_refresh_token(self, refresh_token):
"""
Deletes a refresh token after use
:param refresh_token: The refresh ... |
def mixins(self, name):
""" Search mixins for name.
Allow '>' to be ignored. '.a .b()' == '.a > .b()'
Args:
name (string): Search term
Returns:
Mixin object list OR False
"""
m = self._smixins(name)
if m:
return m
return... | Search mixins for name.
Allow '>' to be ignored. '.a .b()' == '.a > .b()'
Args:
name (string): Search term
Returns:
Mixin object list OR False | Below is the the instruction that describes the task:
### Input:
Search mixins for name.
Allow '>' to be ignored. '.a .b()' == '.a > .b()'
Args:
name (string): Search term
Returns:
Mixin object list OR False
### Response:
def mixins(self, name):
""" Search mi... |
def general_setting(key, default=None, expected_type=None, qsettings=None):
"""Helper function to get a value from settings.
:param key: Unique key for setting.
:type key: basestring
:param default: The default value in case of the key is not found or there
is an error.
:type default: base... | Helper function to get a value from settings.
:param key: Unique key for setting.
:type key: basestring
:param default: The default value in case of the key is not found or there
is an error.
:type default: basestring, None, boolean, int, float
:param expected_type: The type of object exp... | Below is the the instruction that describes the task:
### Input:
Helper function to get a value from settings.
:param key: Unique key for setting.
:type key: basestring
:param default: The default value in case of the key is not found or there
is an error.
:type default: basestring, None, ... |
def add_slave(self, slave, container_name="widget"):
"""Add a slave delegate
"""
cont = getattr(self, container_name, None)
if cont is None:
raise AttributeError(
'Container name must be a member of the delegate')
cont.add(slave.widget)
self.sl... | Add a slave delegate | Below is the the instruction that describes the task:
### Input:
Add a slave delegate
### Response:
def add_slave(self, slave, container_name="widget"):
"""Add a slave delegate
"""
cont = getattr(self, container_name, None)
if cont is None:
raise AttributeError(
... |
def load_data():
'''Load dataset, use boston dataset'''
boston = load_boston()
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=99, test_size=0.25)
#normalize data
ss_X = StandardScaler()
ss_y = StandardScaler()
X_train = ss_X.fit_transform(X_trai... | Load dataset, use boston dataset | Below is the the instruction that describes the task:
### Input:
Load dataset, use boston dataset
### Response:
def load_data():
'''Load dataset, use boston dataset'''
boston = load_boston()
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=99, test_size=0.25)... |
def time(self, t):
"""Convert any timestamp into a datetime and save as _time"""
_time = arrow.get(t).format('YYYY-MM-DDTHH:mm:ss')
self._time = datetime.datetime.strptime(_time, '%Y-%m-%dT%H:%M:%S') | Convert any timestamp into a datetime and save as _time | Below is the the instruction that describes the task:
### Input:
Convert any timestamp into a datetime and save as _time
### Response:
def time(self, t):
"""Convert any timestamp into a datetime and save as _time"""
_time = arrow.get(t).format('YYYY-MM-DDTHH:mm:ss')
self._time = datetime.da... |
def _uncached_match(self, text, pos, cache, error):
"""Return length of match, ``None`` if no match."""
m = self.re.match(text, pos)
if m is not None:
span = m.span()
node = RegexNode(self, text, pos, pos + span[1] - span[0])
node.match = m # TODO: A terrible... | Return length of match, ``None`` if no match. | Below is the the instruction that describes the task:
### Input:
Return length of match, ``None`` if no match.
### Response:
def _uncached_match(self, text, pos, cache, error):
"""Return length of match, ``None`` if no match."""
m = self.re.match(text, pos)
if m is not None:
spa... |
def moment(inlist, moment=1):
"""
Calculates the nth moment about the mean for a sample (defaults to
the 1st moment). Used to calculate coefficients of skewness and kurtosis.
Usage: lmoment(inlist,moment=1)
Returns: appropriate moment (r) from pyLibrary. 1/n * SUM((inlist(i)-mean)**r)
"""
if moment == 1:
... | Calculates the nth moment about the mean for a sample (defaults to
the 1st moment). Used to calculate coefficients of skewness and kurtosis.
Usage: lmoment(inlist,moment=1)
Returns: appropriate moment (r) from pyLibrary. 1/n * SUM((inlist(i)-mean)**r) | Below is the the instruction that describes the task:
### Input:
Calculates the nth moment about the mean for a sample (defaults to
the 1st moment). Used to calculate coefficients of skewness and kurtosis.
Usage: lmoment(inlist,moment=1)
Returns: appropriate moment (r) from pyLibrary. 1/n * SUM((inlist(i)-mean)... |
def _proj_l1_scalar_root(v, gamma):
r"""Projection operator of the :math:`\ell_1` norm. The solution is
computed via the method of Sec. 6.5.2 in :cite:`parikh-2014-proximal`.
There is no `axis` parameter since the algorithm for computing the
solution treats the input `v` as a single vector.
Param... | r"""Projection operator of the :math:`\ell_1` norm. The solution is
computed via the method of Sec. 6.5.2 in :cite:`parikh-2014-proximal`.
There is no `axis` parameter since the algorithm for computing the
solution treats the input `v` as a single vector.
Parameters
----------
v : array_like
... | Below is the the instruction that describes the task:
### Input:
r"""Projection operator of the :math:`\ell_1` norm. The solution is
computed via the method of Sec. 6.5.2 in :cite:`parikh-2014-proximal`.
There is no `axis` parameter since the algorithm for computing the
solution treats the input `v` as... |
def knx_to_date(knxdata):
"""Convert a 3 byte KNX data object to a date"""
if len(knxdata) != 3:
raise KNXException("Can only convert a 3 Byte object to date")
year = knxdata[2]
if year >= 90:
year += 1900
else:
year += 2000
return date(year, knxdata[1], knxdata[0]) | Convert a 3 byte KNX data object to a date | Below is the the instruction that describes the task:
### Input:
Convert a 3 byte KNX data object to a date
### Response:
def knx_to_date(knxdata):
"""Convert a 3 byte KNX data object to a date"""
if len(knxdata) != 3:
raise KNXException("Can only convert a 3 Byte object to date")
year = knxd... |
def get_data_home(data_home=None):
"""Return the path of the arviz data dir.
This folder is used by some dataset loaders to avoid downloading the
data several times.
By default the data dir is set to a folder named 'arviz_data' in the
user home folder.
Alternatively, it can be set by the 'ARV... | Return the path of the arviz data dir.
This folder is used by some dataset loaders to avoid downloading the
data several times.
By default the data dir is set to a folder named 'arviz_data' in the
user home folder.
Alternatively, it can be set by the 'ARVIZ_DATA' environment
variable or progr... | Below is the the instruction that describes the task:
### Input:
Return the path of the arviz data dir.
This folder is used by some dataset loaders to avoid downloading the
data several times.
By default the data dir is set to a folder named 'arviz_data' in the
user home folder.
Alternatively... |
def run(self) -> None:
"""Thread run method implementation."""
while True:
request = self.input_queue.get()
response = self._handle_request(request)
self.output_queue.put(response) | Thread run method implementation. | Below is the the instruction that describes the task:
### Input:
Thread run method implementation.
### Response:
def run(self) -> None:
"""Thread run method implementation."""
while True:
request = self.input_queue.get()
response = self._handle_request(request)
s... |
def save_method_args(method):
"""
Wrap a method such that when it is called, the args and kwargs are
saved on the method.
>>> class MyClass:
... @save_method_args
... def method(self, a, b):
... print(a, b)
>>> my_ob = MyClass()
>>> my_ob.method(1, 2)
1 2
>>> my_ob._saved_method.args
(1, 2)... | Wrap a method such that when it is called, the args and kwargs are
saved on the method.
>>> class MyClass:
... @save_method_args
... def method(self, a, b):
... print(a, b)
>>> my_ob = MyClass()
>>> my_ob.method(1, 2)
1 2
>>> my_ob._saved_method.args
(1, 2)
>>> my_ob._saved_method.kwargs
{}... | Below is the the instruction that describes the task:
### Input:
Wrap a method such that when it is called, the args and kwargs are
saved on the method.
>>> class MyClass:
... @save_method_args
... def method(self, a, b):
... print(a, b)
>>> my_ob = MyClass()
>>> my_ob.method(1, 2)
1 2
>>>... |
def subseparable_conv(inputs, filters, kernel_size, **kwargs):
"""Sub-separable convolution. If separability == 0 it's a separable_conv."""
def conv_fn(inputs, filters, kernel_size, **kwargs):
"""Sub-separable convolution, splits into separability-many blocks."""
separability = None
if "separability" i... | Sub-separable convolution. If separability == 0 it's a separable_conv. | Below is the the instruction that describes the task:
### Input:
Sub-separable convolution. If separability == 0 it's a separable_conv.
### Response:
def subseparable_conv(inputs, filters, kernel_size, **kwargs):
"""Sub-separable convolution. If separability == 0 it's a separable_conv."""
def conv_fn(inputs, ... |
def read_sha1(
file_path,
buf_size = None,
start_byte = 0,
read_size = None,
extra_hashers = [], # update(data) will be called on all of these
):
'''
Determines the sha1 hash of a file in chunks, to prevent loading the entire file at once into memory
'''
read_size = read_size or os.s... | Determines the sha1 hash of a file in chunks, to prevent loading the entire file at once into memory | Below is the the instruction that describes the task:
### Input:
Determines the sha1 hash of a file in chunks, to prevent loading the entire file at once into memory
### Response:
def read_sha1(
file_path,
buf_size = None,
start_byte = 0,
read_size = None,
extra_hashers = [], # update(data) wil... |
def labelForAction(self, action):
"""
Returns the label that contains the inputed action.
:return <XDockActionLabel> || None
"""
for label in self.actionLabels():
if label.action() == action:
return label
return None | Returns the label that contains the inputed action.
:return <XDockActionLabel> || None | Below is the the instruction that describes the task:
### Input:
Returns the label that contains the inputed action.
:return <XDockActionLabel> || None
### Response:
def labelForAction(self, action):
"""
Returns the label that contains the inputed action.
... |
def _determine_spec(self, index):
"""
Determine how a value for a field should be constructed
:param index:
The field number
:return:
A tuple containing the following elements:
- unicode string of the field name
- Asn1Value class of the... | Determine how a value for a field should be constructed
:param index:
The field number
:return:
A tuple containing the following elements:
- unicode string of the field name
- Asn1Value class of the field spec
- Asn1Value class of the valu... | Below is the the instruction that describes the task:
### Input:
Determine how a value for a field should be constructed
:param index:
The field number
:return:
A tuple containing the following elements:
- unicode string of the field name
- Asn1Val... |
def update(self, **args):
""" Updates a Clip.
Parameters:
- args Dictionary of other fields
Accepted fields can be found here:
https://github.com/kippt/api-documentation/blob/master/objects/clip.md
"""
# JSONify our data.
data = json.dumps(args)
... | Updates a Clip.
Parameters:
- args Dictionary of other fields
Accepted fields can be found here:
https://github.com/kippt/api-documentation/blob/master/objects/clip.md | Below is the the instruction that describes the task:
### Input:
Updates a Clip.
Parameters:
- args Dictionary of other fields
Accepted fields can be found here:
https://github.com/kippt/api-documentation/blob/master/objects/clip.md
### Response:
def update(self, **args):
... |
def override_supported_formats(formats):
"""
Override the views class' supported formats for the decorated function.
Arguments:
formats -- A list of strings describing formats, e.g. ``['html', 'json']``.
"""
def decorator(function):
@wraps(function)
def wrapper(self, *args, **kw... | Override the views class' supported formats for the decorated function.
Arguments:
formats -- A list of strings describing formats, e.g. ``['html', 'json']``. | Below is the the instruction that describes the task:
### Input:
Override the views class' supported formats for the decorated function.
Arguments:
formats -- A list of strings describing formats, e.g. ``['html', 'json']``.
### Response:
def override_supported_formats(formats):
"""
Override the vi... |
def calculate_reduced_matrix_elements(fine_states, convention=1):
r"""Calculate the reduced matrix elements for a list of fine states.
This function calculates the reduced matrix elments
.. math::
\langle N,L,J||T^1(r)||N',L',J'\rangle
given a list of fine states.
We calculate the reduce... | r"""Calculate the reduced matrix elements for a list of fine states.
This function calculates the reduced matrix elments
.. math::
\langle N,L,J||T^1(r)||N',L',J'\rangle
given a list of fine states.
We calculate the reduced matrix elements found in [SteckRb87]_ for the \
D1 and D2 lines ... | Below is the the instruction that describes the task:
### Input:
r"""Calculate the reduced matrix elements for a list of fine states.
This function calculates the reduced matrix elments
.. math::
\langle N,L,J||T^1(r)||N',L',J'\rangle
given a list of fine states.
We calculate the reduced... |
def delegate_method(other, method, name=None):
"""Add a method to the current class that delegates to another method.
The *other* argument must be a property that returns the instance to
delegate to. Due to an implementation detail, the property must be defined
in the current class. The *method* argume... | Add a method to the current class that delegates to another method.
The *other* argument must be a property that returns the instance to
delegate to. Due to an implementation detail, the property must be defined
in the current class. The *method* argument specifies a method to delegate
to. It can be an... | Below is the the instruction that describes the task:
### Input:
Add a method to the current class that delegates to another method.
The *other* argument must be a property that returns the instance to
delegate to. Due to an implementation detail, the property must be defined
in the current class. The ... |
def file_client(self):
'''
Return a file client. Instantiates on first call.
'''
if not self._file_client:
self._file_client = salt.fileclient.get_file_client(
self.opts, self.pillar_rend)
return self._file_client | Return a file client. Instantiates on first call. | Below is the the instruction that describes the task:
### Input:
Return a file client. Instantiates on first call.
### Response:
def file_client(self):
'''
Return a file client. Instantiates on first call.
'''
if not self._file_client:
self._file_client = salt.fileclient... |
def unpack_hyperopt_vals(vals):
"""
Unpack values from a hyperopt return dictionary where values are wrapped in a list.
:param vals: dict
:return: dict
copy of the dictionary with unpacked values
"""
assert isinstance(vals, dict), "Parameter must be given as dict."
ret = {}
for k... | Unpack values from a hyperopt return dictionary where values are wrapped in a list.
:param vals: dict
:return: dict
copy of the dictionary with unpacked values | Below is the the instruction that describes the task:
### Input:
Unpack values from a hyperopt return dictionary where values are wrapped in a list.
:param vals: dict
:return: dict
copy of the dictionary with unpacked values
### Response:
def unpack_hyperopt_vals(vals):
"""
Unpack values fr... |
def writeDefinition(self, f, name):
"""Writes the string table to a file as a C const char array.
This writes out the string table as one single C char array for memory
size reasons, separating the individual strings with '\0' characters.
This way we can index directly into the string a... | Writes the string table to a file as a C const char array.
This writes out the string table as one single C char array for memory
size reasons, separating the individual strings with '\0' characters.
This way we can index directly into the string array and avoid the additional
storage c... | Below is the the instruction that describes the task:
### Input:
Writes the string table to a file as a C const char array.
This writes out the string table as one single C char array for memory
size reasons, separating the individual strings with '\0' characters.
This way we can index dire... |
def remove_policy(self, index=None, params=None):
"""
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-remove-policy.html>`_
:arg index: The name of the index to remove policy on
"""
return self.transport.perform_request(
"POST", _make_path(index... | `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-remove-policy.html>`_
:arg index: The name of the index to remove policy on | Below is the the instruction that describes the task:
### Input:
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-remove-policy.html>`_
:arg index: The name of the index to remove policy on
### Response:
def remove_policy(self, index=None, params=None):
"""
`<https://w... |
def export_urdf(mesh,
directory,
scale=1.0,
color=[0.75, 0.75, 0.75],
**kwargs):
"""
Convert a Trimesh object into a URDF package for physics simulation.
This breaks the mesh into convex pieces and writes them to the same
directory as the .... | Convert a Trimesh object into a URDF package for physics simulation.
This breaks the mesh into convex pieces and writes them to the same
directory as the .urdf file.
Parameters
---------
mesh : Trimesh object
directory : str
The directory path for the URDF package
Re... | Below is the the instruction that describes the task:
### Input:
Convert a Trimesh object into a URDF package for physics simulation.
This breaks the mesh into convex pieces and writes them to the same
directory as the .urdf file.
Parameters
---------
mesh : Trimesh object
directory : ... |
def localpath(*args):
"""construct an absolute path from a list relative to the root pycapnp directory"""
plist = [ROOT] + list(args)
return os.path.abspath(pjoin(*plist)) | construct an absolute path from a list relative to the root pycapnp directory | Below is the the instruction that describes the task:
### Input:
construct an absolute path from a list relative to the root pycapnp directory
### Response:
def localpath(*args):
"""construct an absolute path from a list relative to the root pycapnp directory"""
plist = [ROOT] + list(args)
return os.pa... |
def format_command(
command_args, # type: List[str]
command_output, # type: str
):
# type: (...) -> str
"""
Format command information for logging.
"""
text = 'Command arguments: {}\n'.format(command_args)
if not command_output:
text += 'Command output: None'
elif logger.g... | Format command information for logging. | Below is the the instruction that describes the task:
### Input:
Format command information for logging.
### Response:
def format_command(
command_args, # type: List[str]
command_output, # type: str
):
# type: (...) -> str
"""
Format command information for logging.
"""
text = 'Comman... |
def connect_handler(self, their_unl, events, force_master, hairpin, nonce):
# Figure out who should make the connection.
our_unl = self.value.encode("ascii")
their_unl = their_unl.encode("ascii")
master = self.is_master(their_unl)
"""
Master defines who connects i... | Master defines who connects if either side can. It's used to
eliminate having multiple connections with the same host. | Below is the the instruction that describes the task:
### Input:
Master defines who connects if either side can. It's used to
eliminate having multiple connections with the same host.
### Response:
def connect_handler(self, their_unl, events, force_master, hairpin, nonce):
# Figure out who should... |
def init(self, project_name='', template='base', quiet=False, debug=False):
'''Generate new Foliant project.'''
self.logger.setLevel(DEBUG if debug else WARNING)
self.logger.info('Project creation started.')
self.logger.debug(f'Template: {template}')
template_path = Path(temp... | Generate new Foliant project. | Below is the the instruction that describes the task:
### Input:
Generate new Foliant project.
### Response:
def init(self, project_name='', template='base', quiet=False, debug=False):
'''Generate new Foliant project.'''
self.logger.setLevel(DEBUG if debug else WARNING)
self.logger.info('... |
def get_sentence_id(self, element):
"""returns the ID of the sentence the given element belongs to."""
try:
sentence_elem = element.iterancestors('sentence').next()
except StopIteration as e:
warnings.warn("<{}> element is not a descendant of a <sentence> "
... | returns the ID of the sentence the given element belongs to. | Below is the the instruction that describes the task:
### Input:
returns the ID of the sentence the given element belongs to.
### Response:
def get_sentence_id(self, element):
"""returns the ID of the sentence the given element belongs to."""
try:
sentence_elem = element.iterancestors('... |
def post_install_postgresql():
"""
example default hook for installing postgresql
"""
from django.conf import settings as s
with settings(warn_only=True):
sudo('/etc/init.d/postgresql-8.4 restart')
sudo("""psql template1 -c "ALTER USER postgres with encrypted password '%s';" """% env... | example default hook for installing postgresql | Below is the the instruction that describes the task:
### Input:
example default hook for installing postgresql
### Response:
def post_install_postgresql():
"""
example default hook for installing postgresql
"""
from django.conf import settings as s
with settings(warn_only=True):
sudo('... |
def add_hydrogens(self, formal_charges=None):
"""Returns a molecular graph where hydrogens are added explicitely
When the bond order is unknown, it assumes bond order one. If the
graph has an attribute formal_charges, this routine will take it
into account when counting the nu... | Returns a molecular graph where hydrogens are added explicitely
When the bond order is unknown, it assumes bond order one. If the
graph has an attribute formal_charges, this routine will take it
into account when counting the number of hydrogens to be added. The
returned gr... | Below is the the instruction that describes the task:
### Input:
Returns a molecular graph where hydrogens are added explicitely
When the bond order is unknown, it assumes bond order one. If the
graph has an attribute formal_charges, this routine will take it
into account when cou... |
def transliterate(text,lang1_code,lang2_code):
"""
convert the source language script (lang1) to target language script (lang2)
text: text to transliterate
lang1_code: language 1 code
lang1_code: language 2 code
"""
if (lang1_code in langinfo.SCRIPT_RANGES) and... | convert the source language script (lang1) to target language script (lang2)
text: text to transliterate
lang1_code: language 1 code
lang1_code: language 2 code | Below is the the instruction that describes the task:
### Input:
convert the source language script (lang1) to target language script (lang2)
text: text to transliterate
lang1_code: language 1 code
lang1_code: language 2 code
### Response:
def transliterate(text,lang1_code,lang2_code):
... |
def replicate(self, dst_lun_id, max_time_out_of_sync,
replication_name=None, replicate_existing_snaps=None,
remote_system=None):
"""
Creates a replication session with a existing lun as destination.
:param dst_lun_id: destination lun id.
:param max_ti... | Creates a replication session with a existing lun as destination.
:param dst_lun_id: destination lun id.
:param max_time_out_of_sync: maximum time to wait before syncing the
source and destination. Value `-1` means the automatic sync is not
performed. `0` means it is a sync repl... | Below is the the instruction that describes the task:
### Input:
Creates a replication session with a existing lun as destination.
:param dst_lun_id: destination lun id.
:param max_time_out_of_sync: maximum time to wait before syncing the
source and destination. Value `-1` means the aut... |
async def authenticate_redirect(self, callback_uri: str = None) -> None:
"""Just like `~OAuthMixin.authorize_redirect`, but
auto-redirects if authorized.
This is generally the right interface to use if you are using
Twitter for single-sign on.
.. versionchanged:: 3.1
... | Just like `~OAuthMixin.authorize_redirect`, but
auto-redirects if authorized.
This is generally the right interface to use if you are using
Twitter for single-sign on.
.. versionchanged:: 3.1
Now returns a `.Future` and takes an optional callback, for
compatibilit... | Below is the the instruction that describes the task:
### Input:
Just like `~OAuthMixin.authorize_redirect`, but
auto-redirects if authorized.
This is generally the right interface to use if you are using
Twitter for single-sign on.
.. versionchanged:: 3.1
Now returns a ... |
def multidict_to_dict(d):
"""
Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with
list values
:param d: a MultiDict or MultiValueDict instance
:return: a dict instance
"""
return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d)) | Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with
list values
:param d: a MultiDict or MultiValueDict instance
:return: a dict instance | Below is the the instruction that describes the task:
### Input:
Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with
list values
:param d: a MultiDict or MultiValueDict instance
:return: a dict instance
### Response:
def multidict_to_dict(d):
"""
Turns a werkzeug.MultiDict or d... |
def estimate_umbrella_sampling(
us_trajs, us_dtrajs, us_centers, us_force_constants, md_trajs=None, md_dtrajs=None, kT=None,
maxiter=10000, maxerr=1.0E-15, save_convergence_info=0,
estimator='wham', lag=1, dt_traj='1 step', init=None, init_maxiter=10000, init_maxerr=1.0E-8,
width=None, **kwargs):
r"... | r"""
This function acts as a wrapper for ``tram()``, ``dtram()``, ``mbar()``, and ``wham()`` and
handles the calculation of bias energies (``bias``) and thermodynamic state trajectories
(``ttrajs``) when the data comes from umbrella sampling and (optional) unbiased simulations.
Parameters
---------... | Below is the the instruction that describes the task:
### Input:
r"""
This function acts as a wrapper for ``tram()``, ``dtram()``, ``mbar()``, and ``wham()`` and
handles the calculation of bias energies (``bias``) and thermodynamic state trajectories
(``ttrajs``) when the data comes from umbrella sampli... |
def convertPossibleValues(val, possibleValues, invalidDefault, emptyValue=''):
'''
convertPossibleValues - Convert input value to one of several possible values,
with a default for invalid entries
@param val <None/str> - The input value
... | convertPossibleValues - Convert input value to one of several possible values,
with a default for invalid entries
@param val <None/str> - The input value
@param possibleValues list<str> - A list of possible values
@param invalidDefa... | Below is the the instruction that describes the task:
### Input:
convertPossibleValues - Convert input value to one of several possible values,
with a default for invalid entries
@param val <None/str> - The input value
@param possibleValues ... |
def lex(self, text):
"""Split self.text into a list of tokens.
Args:
text (str): text to parse
Yields:
Token: the tokens generated from the given text.
"""
pos = 0
while text:
token_class, match = self.tokens.get_token(text)
... | Split self.text into a list of tokens.
Args:
text (str): text to parse
Yields:
Token: the tokens generated from the given text. | Below is the the instruction that describes the task:
### Input:
Split self.text into a list of tokens.
Args:
text (str): text to parse
Yields:
Token: the tokens generated from the given text.
### Response:
def lex(self, text):
"""Split self.text into a list of tok... |
def _parse_target(target):
"""Parse a binary targeting information structure.
This function only supports extracting the slot number or controller from
the target and will raise an ArgumentError if more complicated targeting
is desired.
Args:
target (bytes): The binary targeting data blob.... | Parse a binary targeting information structure.
This function only supports extracting the slot number or controller from
the target and will raise an ArgumentError if more complicated targeting
is desired.
Args:
target (bytes): The binary targeting data blob.
Returns:
dict: The p... | Below is the the instruction that describes the task:
### Input:
Parse a binary targeting information structure.
This function only supports extracting the slot number or controller from
the target and will raise an ArgumentError if more complicated targeting
is desired.
Args:
target (byte... |
def jsoned(struct, wrap=True, meta=None, struct_key='result', pre_render_callback=None):
""" Provides a json dump of the struct
Args:
struct: The data to dump
wrap (bool, optional): Specify whether to wrap the
struct in an enclosing dict
struct_key (str, optional): The strin... | Provides a json dump of the struct
Args:
struct: The data to dump
wrap (bool, optional): Specify whether to wrap the
struct in an enclosing dict
struct_key (str, optional): The string key which will
contain the struct in the result dict
meta (dict, optional):... | Below is the the instruction that describes the task:
### Input:
Provides a json dump of the struct
Args:
struct: The data to dump
wrap (bool, optional): Specify whether to wrap the
struct in an enclosing dict
struct_key (str, optional): The string key which will
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.