code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def wr_xlsx(self, fout_xlsx, nts):
"""Write specified namedtuples into an Excel spreadsheet."""
wr_xlsx(fout_xlsx, nts, prt_flds=self.prt_flds, fld2col_widths=self.fld2col_widths) | Write specified namedtuples into an Excel spreadsheet. | Below is the the instruction that describes the task:
### Input:
Write specified namedtuples into an Excel spreadsheet.
### Response:
def wr_xlsx(self, fout_xlsx, nts):
"""Write specified namedtuples into an Excel spreadsheet."""
wr_xlsx(fout_xlsx, nts, prt_flds=self.prt_flds, fld2col_widths=self.f... |
def generateDiff(self, oldWarnings, newWarnings):
"""
Generate diff between given two lists of warnings.
@param oldWarnings: parsed old warnings
@param newWarnings: parsed new warnings
@return: a dict object of diff
"""
diffWarnings = {}
for modulename i... | Generate diff between given two lists of warnings.
@param oldWarnings: parsed old warnings
@param newWarnings: parsed new warnings
@return: a dict object of diff | Below is the the instruction that describes the task:
### Input:
Generate diff between given two lists of warnings.
@param oldWarnings: parsed old warnings
@param newWarnings: parsed new warnings
@return: a dict object of diff
### Response:
def generateDiff(self, oldWarnings, newWarnings):... |
def put(self, request, bot_id, id, format=None):
"""
Update existing KikBot
---
serializer: KikBotUpdateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
""" ... | Update existing KikBot
---
serializer: KikBotUpdateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request | Below is the the instruction that describes the task:
### Input:
Update existing KikBot
---
serializer: KikBotUpdateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
### Response:
de... |
def calculate_size(name, items):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += INT_SIZE_IN_BYTES
for items_item in items:
data_size += calculate_size_data(items_item)
return data_size | Calculates the request payload size | Below is the the instruction that describes the task:
### Input:
Calculates the request payload size
### Response:
def calculate_size(name, items):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += INT_SIZE_IN_BYTES
for items_item in ite... |
def load(config_path: str):
"""
Load a configuration and keep it alive for the given context
:param config_path: path to a configuration file
"""
# we bind the config to _ to keep it alive
if os.path.splitext(config_path)[1] in ('.yaml', '.yml'):
_ = load_yaml_configuration(config_path,... | Load a configuration and keep it alive for the given context
:param config_path: path to a configuration file | Below is the the instruction that describes the task:
### Input:
Load a configuration and keep it alive for the given context
:param config_path: path to a configuration file
### Response:
def load(config_path: str):
"""
Load a configuration and keep it alive for the given context
:param config_p... |
def _format_fields(self, fields, title_width=12):
"""Formats a list of fields for display.
Parameters
----------
fields : list
A list of 2-tuples: (field_title, field_content)
title_width : int
How many characters to pad titles to. Default 12.
"""
... | Formats a list of fields for display.
Parameters
----------
fields : list
A list of 2-tuples: (field_title, field_content)
title_width : int
How many characters to pad titles to. Default 12. | Below is the the instruction that describes the task:
### Input:
Formats a list of fields for display.
Parameters
----------
fields : list
A list of 2-tuples: (field_title, field_content)
title_width : int
How many characters to pad titles to. Default 12.
### Res... |
def state_call(self, addr, *args, **kwargs):
"""
Create a native or a Java call state.
:param addr: Soot or native addr of the invoke target.
:param args: List of SootArgument values.
"""
state = kwargs.pop('base_state', None)
# check if we need to setup a n... | Create a native or a Java call state.
:param addr: Soot or native addr of the invoke target.
:param args: List of SootArgument values. | Below is the the instruction that describes the task:
### Input:
Create a native or a Java call state.
:param addr: Soot or native addr of the invoke target.
:param args: List of SootArgument values.
### Response:
def state_call(self, addr, *args, **kwargs):
"""
Create a nativ... |
def auto2unicode(text):
"""
This function tries to identify encode in available encodings.
If it finds, then it will convert text into unicode string.
Author : Arulalan.T
04.08.2014
"""
_all_unique_encodes_, _all_common_encodes_ = _get_unique_common_encodes()
# get unique... | This function tries to identify encode in available encodings.
If it finds, then it will convert text into unicode string.
Author : Arulalan.T
04.08.2014 | Below is the the instruction that describes the task:
### Input:
This function tries to identify encode in available encodings.
If it finds, then it will convert text into unicode string.
Author : Arulalan.T
04.08.2014
### Response:
def auto2unicode(text):
"""
This function tries to id... |
def wrap(name, project, sprefix=None, python=sys.executable):
""" Wrap the binary :name: with the runtime extension of the project.
This module generates a python tool that replaces :name:
The function in runner only accepts the replaced binaries
name as argument. We use the cloudpickle package to
... | Wrap the binary :name: with the runtime extension of the project.
This module generates a python tool that replaces :name:
The function in runner only accepts the replaced binaries
name as argument. We use the cloudpickle package to
perform the serialization, make sure :runner: can be serialized
wi... | Below is the the instruction that describes the task:
### Input:
Wrap the binary :name: with the runtime extension of the project.
This module generates a python tool that replaces :name:
The function in runner only accepts the replaced binaries
name as argument. We use the cloudpickle package to
p... |
def calacs(input_file, exec_path=None, time_stamps=False, temp_files=False,
verbose=False, debug=False, quiet=False, single_core=False,
exe_args=None):
"""
Run the calacs.e executable as from the shell.
By default this will run the calacs given by 'calacs.e'.
Parameters
-----... | Run the calacs.e executable as from the shell.
By default this will run the calacs given by 'calacs.e'.
Parameters
----------
input_file : str
Name of input file.
exec_path : str, optional
The complete path to a calacs executable.
time_stamps : bool, optional
Set to T... | Below is the the instruction that describes the task:
### Input:
Run the calacs.e executable as from the shell.
By default this will run the calacs given by 'calacs.e'.
Parameters
----------
input_file : str
Name of input file.
exec_path : str, optional
The complete path to a ... |
def json_from_cov_df(df, threshold=.5, gain=2., n=None, indent=1):
"""Produce a json string describing the graph (list of edges) from a square auto-correlation/covariance matrix
{ "nodes": [{"group": 1, "name": "the"},
{"group": 1, "name": "and"},
{"group": 1, "name": "our"},
... | Produce a json string describing the graph (list of edges) from a square auto-correlation/covariance matrix
{ "nodes": [{"group": 1, "name": "the"},
{"group": 1, "name": "and"},
{"group": 1, "name": "our"},
{"group": 2, "name": "that"},...
"links": [{"sour... | Below is the the instruction that describes the task:
### Input:
Produce a json string describing the graph (list of edges) from a square auto-correlation/covariance matrix
{ "nodes": [{"group": 1, "name": "the"},
{"group": 1, "name": "and"},
{"group": 1, "name": "our"},
... |
def property_present(properties, admin_username='root', admin_password='calvin', host=None, **kwargs):
'''
properties = {}
'''
ret = {'name': host,
'context': {'Host': host},
'result': True,
'changes': {},
'comment': ''}
if host is None:
output =... | properties = {} | Below is the the instruction that describes the task:
### Input:
properties = {}
### Response:
def property_present(properties, admin_username='root', admin_password='calvin', host=None, **kwargs):
'''
properties = {}
'''
ret = {'name': host,
'context': {'Host': host},
'resul... |
def ipopo_factories(self):
"""
List of iPOPO factories
"""
try:
with use_ipopo(self.__context) as ipopo:
return {
name: ipopo.get_factory_details(name)
for name in ipopo.get_factories()
}
except B... | List of iPOPO factories | Below is the the instruction that describes the task:
### Input:
List of iPOPO factories
### Response:
def ipopo_factories(self):
"""
List of iPOPO factories
"""
try:
with use_ipopo(self.__context) as ipopo:
return {
name: ipopo.get_fa... |
def amax_files():
"""
Return all annual maximum flow (`*.am`) files in cache folder and sub folders.
:return: List of file paths
:rtype: list
"""
return [os.path.join(dp, f) for dp, dn, filenames in os.walk(CACHE_FOLDER)
for f in filenames if os.path.splitext(f)[1].lower() == '.am'] | Return all annual maximum flow (`*.am`) files in cache folder and sub folders.
:return: List of file paths
:rtype: list | Below is the the instruction that describes the task:
### Input:
Return all annual maximum flow (`*.am`) files in cache folder and sub folders.
:return: List of file paths
:rtype: list
### Response:
def amax_files():
"""
Return all annual maximum flow (`*.am`) files in cache folder and sub folders... |
def writeImageToFile(self, filename, _format="PNG"):
'''
Write the View image to the specified filename in the specified format.
@type filename: str
@param filename: Absolute path and optional filename receiving the image. If this points to
a directory, then the... | Write the View image to the specified filename in the specified format.
@type filename: str
@param filename: Absolute path and optional filename receiving the image. If this points to
a directory, then the filename is determined by this View unique ID and
... | Below is the the instruction that describes the task:
### Input:
Write the View image to the specified filename in the specified format.
@type filename: str
@param filename: Absolute path and optional filename receiving the image. If this points to
a directory, then the fil... |
def add_comment(self, post=None, name=None, email=None, pub_date=None,
website=None, body=None):
"""
Adds a comment to the post provided.
"""
if post is None:
if not self.posts:
raise CommandError("Cannot add comments without posts")
... | Adds a comment to the post provided. | Below is the the instruction that describes the task:
### Input:
Adds a comment to the post provided.
### Response:
def add_comment(self, post=None, name=None, email=None, pub_date=None,
website=None, body=None):
"""
Adds a comment to the post provided.
"""
if po... |
def _get_enterprise_admin_users_batch(self, start, end):
"""
Returns a batched queryset of User objects.
"""
LOGGER.info('Fetching new batch of enterprise admin users from indexes: %s to %s', start, end)
return User.objects.filter(groups__name=ENTERPRISE_DATA_API_ACCESS_GROUP, is... | Returns a batched queryset of User objects. | Below is the the instruction that describes the task:
### Input:
Returns a batched queryset of User objects.
### Response:
def _get_enterprise_admin_users_batch(self, start, end):
"""
Returns a batched queryset of User objects.
"""
LOGGER.info('Fetching new batch of enterprise admin... |
def _long_to_bytes(n, length, byteorder):
"""Convert a long to a bytestring
For use in python version prior to 3.2
Source:
http://bugs.python.org/issue16580#msg177208
"""
if byteorder == 'little':
indexes = range(length)
else:
indexes = reversed(range(length))
return byte... | Convert a long to a bytestring
For use in python version prior to 3.2
Source:
http://bugs.python.org/issue16580#msg177208 | Below is the the instruction that describes the task:
### Input:
Convert a long to a bytestring
For use in python version prior to 3.2
Source:
http://bugs.python.org/issue16580#msg177208
### Response:
def _long_to_bytes(n, length, byteorder):
"""Convert a long to a bytestring
For use in python ... |
def format_args(options):
""" Convert hash/key options into arguments list """
args = list()
for key, value in options.items():
# convert foo_bar key into --foo-bar option
key = key.replace('_', '-')
if value is True:
# key: True
# --key
args.app... | Convert hash/key options into arguments list | Below is the the instruction that describes the task:
### Input:
Convert hash/key options into arguments list
### Response:
def format_args(options):
""" Convert hash/key options into arguments list """
args = list()
for key, value in options.items():
# convert foo_bar key into --foo-bar optio... |
def db_get_map(self, table, record, column):
"""
Gets dict type value of 'column' in 'record' in 'table'.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl get TBL REC COL
"""
val = self.db_get_val(table, record, column)
assert is... | Gets dict type value of 'column' in 'record' in 'table'.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl get TBL REC COL | Below is the the instruction that describes the task:
### Input:
Gets dict type value of 'column' in 'record' in 'table'.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl get TBL REC COL
### Response:
def db_get_map(self, table, record, column):
"""
... |
def _unregister_lookup(cls, lookup, lookup_name=None):
"""
Remove given lookup from cls lookups. For use in tests only as it's
not thread-safe.
"""
if lookup_name is None:
lookup_name = lookup.lookup_name
del cls.class_lookups[lookup_name] | Remove given lookup from cls lookups. For use in tests only as it's
not thread-safe. | Below is the the instruction that describes the task:
### Input:
Remove given lookup from cls lookups. For use in tests only as it's
not thread-safe.
### Response:
def _unregister_lookup(cls, lookup, lookup_name=None):
"""
Remove given lookup from cls lookups. For use in tests only as it's
... |
def predictions(self, image, strict=True, return_details=False):
"""Interface to model.predictions for attacks.
Parameters
----------
image : `numpy.ndarray`
Single input with shape as expected by the model
(without the batch dimension).
strict : bool
... | Interface to model.predictions for attacks.
Parameters
----------
image : `numpy.ndarray`
Single input with shape as expected by the model
(without the batch dimension).
strict : bool
Controls if the bounds for the pixel values should be checked. | Below is the the instruction that describes the task:
### Input:
Interface to model.predictions for attacks.
Parameters
----------
image : `numpy.ndarray`
Single input with shape as expected by the model
(without the batch dimension).
strict : bool
... |
def randomtable(numflds=5, numrows=100, wait=0, seed=None):
"""
Construct a table with random numerical data. Use `numflds` and `numrows` to
specify the number of fields and rows respectively. Set `wait` to a float
greater than zero to simulate a delay on each row generation (number of
seconds per r... | Construct a table with random numerical data. Use `numflds` and `numrows` to
specify the number of fields and rows respectively. Set `wait` to a float
greater than zero to simulate a delay on each row generation (number of
seconds per row). E.g.::
>>> import petl as etl
>>> table = etl.rand... | Below is the the instruction that describes the task:
### Input:
Construct a table with random numerical data. Use `numflds` and `numrows` to
specify the number of fields and rows respectively. Set `wait` to a float
greater than zero to simulate a delay on each row generation (number of
seconds per row)... |
def post_revert_tags(self, post_id, history_id):
"""Function to reverts a post to a previous set of tags
(Requires login) (UNTESTED).
Parameters:
post_id (int): The post id number to update.
history_id (int): The id number of the tag history.
"""
params =... | Function to reverts a post to a previous set of tags
(Requires login) (UNTESTED).
Parameters:
post_id (int): The post id number to update.
history_id (int): The id number of the tag history. | Below is the the instruction that describes the task:
### Input:
Function to reverts a post to a previous set of tags
(Requires login) (UNTESTED).
Parameters:
post_id (int): The post id number to update.
history_id (int): The id number of the tag history.
### Response:
def ... |
def configure_modrpaf(self):
"""
Installs the mod-rpaf Apache module.
https://github.com/gnif/mod_rpaf
"""
r = self.local_renderer
if r.env.modrpaf_enabled:
self.install_packages()
self.enable_mod('rpaf')
else:
if self.last_man... | Installs the mod-rpaf Apache module.
https://github.com/gnif/mod_rpaf | Below is the the instruction that describes the task:
### Input:
Installs the mod-rpaf Apache module.
https://github.com/gnif/mod_rpaf
### Response:
def configure_modrpaf(self):
"""
Installs the mod-rpaf Apache module.
https://github.com/gnif/mod_rpaf
"""
r = self.... |
def pretty_tree(x, kids, show):
"""(a, (a -> list(a)), (a -> str)) -> str
Returns a pseudographic tree representation of x similar to the tree command
in Unix.
"""
(MID, END, CONT, LAST, ROOT) = (u'|-- ', u'`-- ', u'| ', u' ', u'')
def rec(x, indent, sym):
line = indent + sym + sh... | (a, (a -> list(a)), (a -> str)) -> str
Returns a pseudographic tree representation of x similar to the tree command
in Unix. | Below is the the instruction that describes the task:
### Input:
(a, (a -> list(a)), (a -> str)) -> str
Returns a pseudographic tree representation of x similar to the tree command
in Unix.
### Response:
def pretty_tree(x, kids, show):
"""(a, (a -> list(a)), (a -> str)) -> str
Returns a pseudogra... |
def getConfig(self):
"""Return the configuration of the city.
:return: configuration of the city.
:rtype: dict.
"""
config = {}
config["name"] = self.city
config["intervals"] = self.__intervals
config["last_date"] = self.__lastDay
config["excluded... | Return the configuration of the city.
:return: configuration of the city.
:rtype: dict. | Below is the the instruction that describes the task:
### Input:
Return the configuration of the city.
:return: configuration of the city.
:rtype: dict.
### Response:
def getConfig(self):
"""Return the configuration of the city.
:return: configuration of the city.
:rtype: ... |
def sid(self):
"""Semantic id."""
pnames = list(self.terms)+list(self.dterms)
pnames.sort()
return (self.__class__, tuple([(k, id(self.__dict__[k])) for k in pnames if k in self.__dict__])) | Semantic id. | Below is the the instruction that describes the task:
### Input:
Semantic id.
### Response:
def sid(self):
"""Semantic id."""
pnames = list(self.terms)+list(self.dterms)
pnames.sort()
return (self.__class__, tuple([(k, id(self.__dict__[k])) for k in pnames if k in self.__dict__])) |
def __live_receivers(signal):
"""Return all signal handlers that are currently still alive for the
input `signal`.
Args:
signal: A signal name.
Returns:
A list of callable receivers for the input signal.
"""
with __lock:
__purge()
receivers = [funcref() for func... | Return all signal handlers that are currently still alive for the
input `signal`.
Args:
signal: A signal name.
Returns:
A list of callable receivers for the input signal. | Below is the the instruction that describes the task:
### Input:
Return all signal handlers that are currently still alive for the
input `signal`.
Args:
signal: A signal name.
Returns:
A list of callable receivers for the input signal.
### Response:
def __live_receivers(signal):
"... |
def is_subset(self, other):
"""Check that every element in self has a count <= in other.
Args:
other (Set)
"""
if isinstance(other, _basebag):
for elem, count in self.counts():
if not count <= other.count(elem):
return False
else:
for elem in self:
if self.count(elem) > 1 or elem not in... | Check that every element in self has a count <= in other.
Args:
other (Set) | Below is the the instruction that describes the task:
### Input:
Check that every element in self has a count <= in other.
Args:
other (Set)
### Response:
def is_subset(self, other):
"""Check that every element in self has a count <= in other.
Args:
other (Set)
"""
if isinstance(other, _basebag):... |
def get_range(self, process_err_pct=0.05):
"""
Returns slant range to the object. Call once for each
new measurement at dt time from last call.
"""
vel = self.vel + 5 * randn()
alt = self.alt + 10 * randn()
self.pos += vel*self.dt
err = (self.pos * proc... | Returns slant range to the object. Call once for each
new measurement at dt time from last call. | Below is the the instruction that describes the task:
### Input:
Returns slant range to the object. Call once for each
new measurement at dt time from last call.
### Response:
def get_range(self, process_err_pct=0.05):
"""
Returns slant range to the object. Call once for each
new me... |
def cleanup(self):
"""Forcefully delete objects from memory
In an ideal world, this shouldn't be necessary. Garbage
collection guarantees that anything without reference
is automatically removed.
However, because this application is designed to be run
multiple times fro... | Forcefully delete objects from memory
In an ideal world, this shouldn't be necessary. Garbage
collection guarantees that anything without reference
is automatically removed.
However, because this application is designed to be run
multiple times from the same interpreter process... | Below is the the instruction that describes the task:
### Input:
Forcefully delete objects from memory
In an ideal world, this shouldn't be necessary. Garbage
collection guarantees that anything without reference
is automatically removed.
However, because this application is design... |
def _delete(self, *args, **kwargs):
"""
A wrapper for deleting things
:returns: The response of your delete
:rtype: dict
"""
response = requests.delete(*args, **kwargs)
response.raise_for_status() | A wrapper for deleting things
:returns: The response of your delete
:rtype: dict | Below is the the instruction that describes the task:
### Input:
A wrapper for deleting things
:returns: The response of your delete
:rtype: dict
### Response:
def _delete(self, *args, **kwargs):
"""
A wrapper for deleting things
:returns: The response of your delete
... |
def _get_output_nodes(self, output_path, error_path):
"""
Extracts output nodes from the standard output and standard error
files.
"""
from aiida.orm.data.array.trajectory import TrajectoryData
import re
state = None
step = None
scale = None
... | Extracts output nodes from the standard output and standard error
files. | Below is the the instruction that describes the task:
### Input:
Extracts output nodes from the standard output and standard error
files.
### Response:
def _get_output_nodes(self, output_path, error_path):
"""
Extracts output nodes from the standard output and standard error
files.
... |
def reset_api_secret(context, id, etag):
"""reset_api_secret(context, id, etag)
Reset a Feeder api_secret.
>>> dcictl feeder-reset-api-secret [OPTIONS]
:param string id: ID of the feeder [required]
:param string etag: Entity tag of the feeder resource [required]
"""
result = feeder.reset_... | reset_api_secret(context, id, etag)
Reset a Feeder api_secret.
>>> dcictl feeder-reset-api-secret [OPTIONS]
:param string id: ID of the feeder [required]
:param string etag: Entity tag of the feeder resource [required] | Below is the the instruction that describes the task:
### Input:
reset_api_secret(context, id, etag)
Reset a Feeder api_secret.
>>> dcictl feeder-reset-api-secret [OPTIONS]
:param string id: ID of the feeder [required]
:param string etag: Entity tag of the feeder resource [required]
### Response:... |
def run_individual(sim_var,
reference,
neuroml_file,
nml_doc,
still_included,
generate_dir,
target,
sim_time,
dt,
simulator,
cl... | Run an individual simulation.
The candidate data has been flattened into the sim_var dict. The
sim_var dict contains parameter:value key value pairs, which are
applied to the model before it is simulated. | Below is the the instruction that describes the task:
### Input:
Run an individual simulation.
The candidate data has been flattened into the sim_var dict. The
sim_var dict contains parameter:value key value pairs, which are
applied to the model before it is simulated.
### Response:
def run_individual... |
def apply_filter_rule(self, _filter, query='in:inbox', way='in'):
"""
:param: _filter _filter a zobjects.FilterRule or the filter name
:param: query on what will the filter be applied
:param: way string discribing if filter is for 'in' or 'out' messages
:returns: list of impacted... | :param: _filter _filter a zobjects.FilterRule or the filter name
:param: query on what will the filter be applied
:param: way string discribing if filter is for 'in' or 'out' messages
:returns: list of impacted message's ids | Below is the the instruction that describes the task:
### Input:
:param: _filter _filter a zobjects.FilterRule or the filter name
:param: query on what will the filter be applied
:param: way string discribing if filter is for 'in' or 'out' messages
:returns: list of impacted message's ids
##... |
def unset_default_org(self):
""" unset the default orgs for tasks """
for org in self.list_orgs():
org_config = self.get_org(org)
if org_config.default:
del org_config.config["default"]
self.set_org(org_config) | unset the default orgs for tasks | Below is the the instruction that describes the task:
### Input:
unset the default orgs for tasks
### Response:
def unset_default_org(self):
""" unset the default orgs for tasks """
for org in self.list_orgs():
org_config = self.get_org(org)
if org_config.default:
... |
def close(self):
"""
Disconnect and error-out all requests.
"""
with self.lock:
if self.is_closed:
return
self.is_closed = True
log.debug("Closing connection (%s) to %s", id(self), self.endpoint)
reactor.callFromThread(self.connect... | Disconnect and error-out all requests. | Below is the the instruction that describes the task:
### Input:
Disconnect and error-out all requests.
### Response:
def close(self):
"""
Disconnect and error-out all requests.
"""
with self.lock:
if self.is_closed:
return
self.is_closed = Tr... |
def find_frame_urls(self, site, frametype, gpsstart, gpsend,
match=None, urltype=None, on_gaps="warn"):
"""Find the framefiles for the given type in the [start, end) interval
frame
@param site:
single-character name of site to match
@param frametype:
... | Find the framefiles for the given type in the [start, end) interval
frame
@param site:
single-character name of site to match
@param frametype:
name of frametype to match
@param gpsstart:
integer GPS start time of query
@param gpsend:
... | Below is the the instruction that describes the task:
### Input:
Find the framefiles for the given type in the [start, end) interval
frame
@param site:
single-character name of site to match
@param frametype:
name of frametype to match
@param gpsstart:
... |
def get_atom_sequence_to_rosetta_map(self):
'''Uses the Rosetta->ATOM injective map to construct an injective mapping from ATOM->Rosetta.
We do not extend the injection to include ATOM residues which have no corresponding Rosetta residue.
e.g. atom_sequence_to_rosetta_mapping[c].map.get(... | Uses the Rosetta->ATOM injective map to construct an injective mapping from ATOM->Rosetta.
We do not extend the injection to include ATOM residues which have no corresponding Rosetta residue.
e.g. atom_sequence_to_rosetta_mapping[c].map.get('A 45 ') will return None if there is no corresponding... | Below is the the instruction that describes the task:
### Input:
Uses the Rosetta->ATOM injective map to construct an injective mapping from ATOM->Rosetta.
We do not extend the injection to include ATOM residues which have no corresponding Rosetta residue.
e.g. atom_sequence_to_rosetta_mappi... |
def encode_request(self, fields, files):
"""
Encode fields and files for posting to an HTTP server.
:param fields: The fields to send as a list of (fieldname, value)
tuples.
:param files: The files to send as a list of (fieldname, filename,
f... | Encode fields and files for posting to an HTTP server.
:param fields: The fields to send as a list of (fieldname, value)
tuples.
:param files: The files to send as a list of (fieldname, filename,
file_bytes) tuple. | Below is the the instruction that describes the task:
### Input:
Encode fields and files for posting to an HTTP server.
:param fields: The fields to send as a list of (fieldname, value)
tuples.
:param files: The files to send as a list of (fieldname, filename,
... |
def dumps(obj, *args, **kwargs):
"""Serialize a object to string
Basic Usage:
>>> import simplekit.objson
>>> obj = {'name':'wendy'}
>>> print simplekit.objson.dumps(obj)
:param obj: a object which need to dump
:param args: Optional arguments that :func:`json.dumps` takes.
:param kwa... | Serialize a object to string
Basic Usage:
>>> import simplekit.objson
>>> obj = {'name':'wendy'}
>>> print simplekit.objson.dumps(obj)
:param obj: a object which need to dump
:param args: Optional arguments that :func:`json.dumps` takes.
:param kwargs: Keys arguments that :py:func:`json.... | Below is the the instruction that describes the task:
### Input:
Serialize a object to string
Basic Usage:
>>> import simplekit.objson
>>> obj = {'name':'wendy'}
>>> print simplekit.objson.dumps(obj)
:param obj: a object which need to dump
:param args: Optional arguments that :func:`json... |
def _parse_relationships(self, relationships):
""" Ensure compliance with the spec's relationships section
Specifically, the relationships object of the single resource
object. For modifications we only support relationships via
the `data` key referred to as Resource Linkage.
:... | Ensure compliance with the spec's relationships section
Specifically, the relationships object of the single resource
object. For modifications we only support relationships via
the `data` key referred to as Resource Linkage.
:param relationships:
dict JSON API relationship... | Below is the the instruction that describes the task:
### Input:
Ensure compliance with the spec's relationships section
Specifically, the relationships object of the single resource
object. For modifications we only support relationships via
the `data` key referred to as Resource Linkage.
... |
def chopurl(url):
'''
A sane "stand alone" url parser.
Example:
info = chopurl(url)
'''
ret = {}
if url.find('://') == -1:
raise s_exc.BadUrl(':// not found in [{}]!'.format(url))
scheme, remain = url.split('://', 1)
ret['scheme'] = scheme.lower()
# carve query pa... | A sane "stand alone" url parser.
Example:
info = chopurl(url) | Below is the the instruction that describes the task:
### Input:
A sane "stand alone" url parser.
Example:
info = chopurl(url)
### Response:
def chopurl(url):
'''
A sane "stand alone" url parser.
Example:
info = chopurl(url)
'''
ret = {}
if url.find('://') == -1:
... |
def color_palette(name=None, n_colors=6, desat=None):
"""Return a list of colors defining a color palette.
Availible seaborn palette names:
deep, muted, bright, pastel, dark, colorblind
Other options:
hls, husl, any matplotlib palette
Matplotlib paletes can be specified as reversed pa... | Return a list of colors defining a color palette.
Availible seaborn palette names:
deep, muted, bright, pastel, dark, colorblind
Other options:
hls, husl, any matplotlib palette
Matplotlib paletes can be specified as reversed palettes by appending
"_r" to the name or as dark palettes ... | Below is the the instruction that describes the task:
### Input:
Return a list of colors defining a color palette.
Availible seaborn palette names:
deep, muted, bright, pastel, dark, colorblind
Other options:
hls, husl, any matplotlib palette
Matplotlib paletes can be specified as rev... |
def _get_cpu_virtualization(self):
"""get cpu virtualization status."""
try:
cpu_vt = self._get_bios_setting('ProcVirtualization')
except exception.IloCommandNotSupportedError:
return False
if cpu_vt == 'Enabled':
vt_status = True
else:
... | get cpu virtualization status. | Below is the the instruction that describes the task:
### Input:
get cpu virtualization status.
### Response:
def _get_cpu_virtualization(self):
"""get cpu virtualization status."""
try:
cpu_vt = self._get_bios_setting('ProcVirtualization')
except exception.IloCommandNotSupporte... |
def getGroundResolution(self, latitude, level):
'''
returns the ground resolution for based on latitude and zoom level.
'''
latitude = self.clipValue(latitude, self.min_lat, self.max_lat);
mapSize = self.getMapDimensionsByZoomLevel(level)
return math.cos(
lati... | returns the ground resolution for based on latitude and zoom level. | Below is the the instruction that describes the task:
### Input:
returns the ground resolution for based on latitude and zoom level.
### Response:
def getGroundResolution(self, latitude, level):
'''
returns the ground resolution for based on latitude and zoom level.
'''
latitude = s... |
def perform_import(val):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.
"""
if val is None:
return None
elif isinstance(val, str):
return import_from_string(val)
elif isinstance(val, (list, tuple)):
return [import_f... | If the given setting is a string import notation,
then perform the necessary import or imports. | Below is the the instruction that describes the task:
### Input:
If the given setting is a string import notation,
then perform the necessary import or imports.
### Response:
def perform_import(val):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.... |
def cmd_adb(self, *args):
'''
Run adb from the Android SDK.
Args must come after --, or use
--alias to make an alias
'''
self.check_requirements()
self.install_platform()
args = args[0]
if args and args[0] == '--alias':
print('To set up... | Run adb from the Android SDK.
Args must come after --, or use
--alias to make an alias | Below is the the instruction that describes the task:
### Input:
Run adb from the Android SDK.
Args must come after --, or use
--alias to make an alias
### Response:
def cmd_adb(self, *args):
'''
Run adb from the Android SDK.
Args must come after --, or use
--alias t... |
def release(self, args):
"""
Set the Out_Of_Service property to False - to release the I/O point back to
the controller's control.
:param args: String with <addr> <type> <inst>
"""
if not self._started:
raise ApplicationNotStarted("BACnet stack not... | Set the Out_Of_Service property to False - to release the I/O point back to
the controller's control.
:param args: String with <addr> <type> <inst> | Below is the the instruction that describes the task:
### Input:
Set the Out_Of_Service property to False - to release the I/O point back to
the controller's control.
:param args: String with <addr> <type> <inst>
### Response:
def release(self, args):
"""
Set the Out_Of_Servi... |
def write_modes_to_file(self, filename="mode.dat", plot=True, analyse=True):
"""
Writes the mode fields to a file and optionally plots them.
Args:
filename (str): The nominal filename to use for the saved
data. The suffix will be automatically be changed to
... | Writes the mode fields to a file and optionally plots them.
Args:
filename (str): The nominal filename to use for the saved
data. The suffix will be automatically be changed to
identifiy each mode number. Default is 'mode.dat'
plot (bool): `True` if plo... | Below is the the instruction that describes the task:
### Input:
Writes the mode fields to a file and optionally plots them.
Args:
filename (str): The nominal filename to use for the saved
data. The suffix will be automatically be changed to
identifiy each mode ... |
def _add_existing_weight(self, weight, trainable=None):
"""Calls add_weight() to register but not create an existing weight."""
if trainable is None: trainable = weight.trainable
self.add_weight(name=weight.name, shape=weight.shape, dtype=weight.dtype,
trainable=trainable, getter=lambda ... | Calls add_weight() to register but not create an existing weight. | Below is the the instruction that describes the task:
### Input:
Calls add_weight() to register but not create an existing weight.
### Response:
def _add_existing_weight(self, weight, trainable=None):
"""Calls add_weight() to register but not create an existing weight."""
if trainable is None: trainable = ... |
def script_dir(pyobject, follow_symlinks=True):
"""Get current script's directory
Args:
pyobject (Any): Any Python object in the script
follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True.
Returns:
str: Current script's directory
"""
if getattr(sys, '... | Get current script's directory
Args:
pyobject (Any): Any Python object in the script
follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True.
Returns:
str: Current script's directory | Below is the the instruction that describes the task:
### Input:
Get current script's directory
Args:
pyobject (Any): Any Python object in the script
follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True.
Returns:
str: Current script's directory
### Response:
... |
def vm_monitoring(name, call=None):
'''
Returns the monitoring records for a given virtual machine. A VM name must be
supplied.
The monitoring information returned is a list of VM elements. Each VM element
contains the complete dictionary of the VM with the updated information returned
by the p... | Returns the monitoring records for a given virtual machine. A VM name must be
supplied.
The monitoring information returned is a list of VM elements. Each VM element
contains the complete dictionary of the VM with the updated information returned
by the poll action.
.. versionadded:: 2016.3.0
... | Below is the the instruction that describes the task:
### Input:
Returns the monitoring records for a given virtual machine. A VM name must be
supplied.
The monitoring information returned is a list of VM elements. Each VM element
contains the complete dictionary of the VM with the updated information ... |
def get_njobs_in_queue(self, username=None):
"""
returns the number of jobs in the queue, probably using subprocess or shutil to
call a command like 'qstat'. returns None when the number of jobs cannot be determined.
Args:
username: (str) the username of the jobs to count (d... | returns the number of jobs in the queue, probably using subprocess or shutil to
call a command like 'qstat'. returns None when the number of jobs cannot be determined.
Args:
username: (str) the username of the jobs to count (default is to autodetect) | Below is the the instruction that describes the task:
### Input:
returns the number of jobs in the queue, probably using subprocess or shutil to
call a command like 'qstat'. returns None when the number of jobs cannot be determined.
Args:
username: (str) the username of the jobs to coun... |
def trace_in_process_link(self, link_bytes):
'''Creates a tracer for tracing asynchronous related processing in the same process.
For more information see :meth:`create_in_process_link`.
:param bytes link_bytes: An in-process link created using :meth:`create_in_process_link`.
:rtype: ... | Creates a tracer for tracing asynchronous related processing in the same process.
For more information see :meth:`create_in_process_link`.
:param bytes link_bytes: An in-process link created using :meth:`create_in_process_link`.
:rtype: tracers.InProcessLinkTracer
.. versionadded:: 1... | Below is the the instruction that describes the task:
### Input:
Creates a tracer for tracing asynchronous related processing in the same process.
For more information see :meth:`create_in_process_link`.
:param bytes link_bytes: An in-process link created using :meth:`create_in_process_link`.
... |
def ptb_raw_data(data_path):
"""Load PTB raw data from data directory "data_path".
Reads PTB text files, converts strings to integer ids,
and performs mini-batching of the inputs.
The PTB dataset comes from Tomas Mikolov's webpage:
http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz
Args:
da... | Load PTB raw data from data directory "data_path".
Reads PTB text files, converts strings to integer ids,
and performs mini-batching of the inputs.
The PTB dataset comes from Tomas Mikolov's webpage:
http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz
Args:
data_path: string path to the direct... | Below is the the instruction that describes the task:
### Input:
Load PTB raw data from data directory "data_path".
Reads PTB text files, converts strings to integer ids,
and performs mini-batching of the inputs.
The PTB dataset comes from Tomas Mikolov's webpage:
http://www.fit.vutbr.cz/~imikolov/rnnlm/... |
def displayhtml(public_key,
attrs,
use_ssl=False,
error=None):
"""Gets the HTML to display for reCAPTCHA
public_key -- The public api key
use_ssl -- Should the request be sent over ssl?
error -- An error message to display (from RecaptchaResponse.error_co... | Gets the HTML to display for reCAPTCHA
public_key -- The public api key
use_ssl -- Should the request be sent over ssl?
error -- An error message to display (from RecaptchaResponse.error_code) | Below is the the instruction that describes the task:
### Input:
Gets the HTML to display for reCAPTCHA
public_key -- The public api key
use_ssl -- Should the request be sent over ssl?
error -- An error message to display (from RecaptchaResponse.error_code)
### Response:
def displayhtml(public_key,
... |
def _nameFromHeaderInfo(headerInfo, isDecoy, decoyTag):
"""Generates a protein name from headerInfo. If "isDecoy" is True, the
"decoyTag" is added to beginning of the generated protein name.
:param headerInfo: dict, must contain a key "name" or "id"
:param isDecoy: bool, determines if the "decoyTag" is... | Generates a protein name from headerInfo. If "isDecoy" is True, the
"decoyTag" is added to beginning of the generated protein name.
:param headerInfo: dict, must contain a key "name" or "id"
:param isDecoy: bool, determines if the "decoyTag" is added or not.
:param decoyTag: str, a tag that identifies ... | Below is the the instruction that describes the task:
### Input:
Generates a protein name from headerInfo. If "isDecoy" is True, the
"decoyTag" is added to beginning of the generated protein name.
:param headerInfo: dict, must contain a key "name" or "id"
:param isDecoy: bool, determines if the "decoyT... |
def create_empty_table_serial_primary(conn, schema, table, columns=None,
id_col='id'):
r"""New database table with primary key type serial and empty columns
Parameters
----------
conn : sqlalchemy connection object
A valid connection to a database
schem... | r"""New database table with primary key type serial and empty columns
Parameters
----------
conn : sqlalchemy connection object
A valid connection to a database
schema : str
The database schema
table : str
The database table
columns : list, optional
Columns that ... | Below is the the instruction that describes the task:
### Input:
r"""New database table with primary key type serial and empty columns
Parameters
----------
conn : sqlalchemy connection object
A valid connection to a database
schema : str
The database schema
table : str
... |
def to_api_repr(self):
"""Generate a resource for :meth:`_begin`."""
source_refs = [
{
"projectId": table.project,
"datasetId": table.dataset_id,
"tableId": table.table_id,
}
for table in self.sources
]
... | Generate a resource for :meth:`_begin`. | Below is the the instruction that describes the task:
### Input:
Generate a resource for :meth:`_begin`.
### Response:
def to_api_repr(self):
"""Generate a resource for :meth:`_begin`."""
source_refs = [
{
"projectId": table.project,
"datasetId": table.d... |
def set_asset(self, asset_id, asset_content_type=None):
"""stub"""
if asset_id is None:
raise NullArgument('asset_id cannot be None')
if not isinstance(asset_id, Id):
raise InvalidArgument('asset_id must be an instance of Id')
if asset_content_type is not None and... | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def set_asset(self, asset_id, asset_content_type=None):
"""stub"""
if asset_id is None:
raise NullArgument('asset_id cannot be None')
if not isinstance(asset_id, Id):
raise InvalidArg... |
def run(self, data_loaders, workflow, max_epochs, **kwargs):
"""Start running.
Args:
data_loaders (list[:obj:`DataLoader`]): Dataloaders for training
and validation.
workflow (list[tuple]): A list of (phase, epochs) to specify the
running order an... | Start running.
Args:
data_loaders (list[:obj:`DataLoader`]): Dataloaders for training
and validation.
workflow (list[tuple]): A list of (phase, epochs) to specify the
running order and epochs. E.g, [('train', 2), ('val', 1)] means
running ... | Below is the the instruction that describes the task:
### Input:
Start running.
Args:
data_loaders (list[:obj:`DataLoader`]): Dataloaders for training
and validation.
workflow (list[tuple]): A list of (phase, epochs) to specify the
running order and e... |
def Read(self, timeout=None):
'''
Reads the context menu
:param timeout: Optional. Any value other than None indicates a non-blocking read
:return:
'''
# if not self.Shown:
# self.Shown = True
# self.TrayIcon.show()
timeout1 = timeout
... | Reads the context menu
:param timeout: Optional. Any value other than None indicates a non-blocking read
:return: | Below is the the instruction that describes the task:
### Input:
Reads the context menu
:param timeout: Optional. Any value other than None indicates a non-blocking read
:return:
### Response:
def Read(self, timeout=None):
'''
Reads the context menu
:param timeout: Optional... |
def train_epoch(self, epoch_info, source: 'vel.api.Source', interactive=True):
""" Run a single training epoch """
self.train()
if interactive:
iterator = tqdm.tqdm(source.train_loader(), desc="Training", unit="iter", file=sys.stdout)
else:
iterator = source.trai... | Run a single training epoch | Below is the the instruction that describes the task:
### Input:
Run a single training epoch
### Response:
def train_epoch(self, epoch_info, source: 'vel.api.Source', interactive=True):
""" Run a single training epoch """
self.train()
if interactive:
iterator = tqdm.tqdm(source... |
def from_proto(brain_param_proto):
"""
Converts brain parameter proto to BrainParameter object.
:param brain_param_proto: protobuf object.
:return: BrainParameter object.
"""
resolution = [{
"height": x.height,
"width": x.width,
"blackA... | Converts brain parameter proto to BrainParameter object.
:param brain_param_proto: protobuf object.
:return: BrainParameter object. | Below is the the instruction that describes the task:
### Input:
Converts brain parameter proto to BrainParameter object.
:param brain_param_proto: protobuf object.
:return: BrainParameter object.
### Response:
def from_proto(brain_param_proto):
"""
Converts brain parameter proto to... |
def fulltext_scan_ids(self, query_id=None, query_fc=None,
preserve_order=True, indexes=None):
'''Fulltext search for identifiers.
Yields an iterable of triples (score, identifier)
corresponding to the search results of the fulltext search
in ``query``. This wil... | Fulltext search for identifiers.
Yields an iterable of triples (score, identifier)
corresponding to the search results of the fulltext search
in ``query``. This will only search text indexed under the
given feature named ``fname``.
Note that, unless ``preserve_order`` is set to... | Below is the the instruction that describes the task:
### Input:
Fulltext search for identifiers.
Yields an iterable of triples (score, identifier)
corresponding to the search results of the fulltext search
in ``query``. This will only search text indexed under the
given feature nam... |
def read_notes_file(file_path):
"""
Returns the contents of a notes file.
If the notes file does not exist, None is returned
"""
if not os.path.isfile(file_path):
return None
with open(file_path, 'r', encoding=_default_encoding) as f:
return f.read() | Returns the contents of a notes file.
If the notes file does not exist, None is returned | Below is the the instruction that describes the task:
### Input:
Returns the contents of a notes file.
If the notes file does not exist, None is returned
### Response:
def read_notes_file(file_path):
"""
Returns the contents of a notes file.
If the notes file does not exist, None is returned
... |
def _validate_measure_sampling(self, experiment):
"""Determine if measure sampling is allowed for an experiment
Args:
experiment (QobjExperiment): a qobj experiment.
"""
# If shots=1 we should disable measure sampling.
# This is also required for statevector simulato... | Determine if measure sampling is allowed for an experiment
Args:
experiment (QobjExperiment): a qobj experiment. | Below is the the instruction that describes the task:
### Input:
Determine if measure sampling is allowed for an experiment
Args:
experiment (QobjExperiment): a qobj experiment.
### Response:
def _validate_measure_sampling(self, experiment):
"""Determine if measure sampling is allowed ... |
def is_active(self, name):
"""
Returns True if plugin exists and is active.
If plugin does not exist, it returns None
:param name: plugin name
:return: boolean or None
"""
if name in self._plugins.keys():
return self._plugins["name"].active
re... | Returns True if plugin exists and is active.
If plugin does not exist, it returns None
:param name: plugin name
:return: boolean or None | Below is the the instruction that describes the task:
### Input:
Returns True if plugin exists and is active.
If plugin does not exist, it returns None
:param name: plugin name
:return: boolean or None
### Response:
def is_active(self, name):
"""
Returns True if plugin exis... |
def get_items(self):
"""Get the items contained in `self`.
:return: the items contained.
:returntype: `list` of `DiscoItem`"""
ret=[]
l=self.xpath_ctxt.xpathEval("d:item")
if l is not None:
for i in l:
ret.append(DiscoItem(self, i))
re... | Get the items contained in `self`.
:return: the items contained.
:returntype: `list` of `DiscoItem` | Below is the the instruction that describes the task:
### Input:
Get the items contained in `self`.
:return: the items contained.
:returntype: `list` of `DiscoItem`
### Response:
def get_items(self):
"""Get the items contained in `self`.
:return: the items contained.
:retu... |
def _Pairs(data):
"""dictionary -> list of pairs"""
keys = sorted(data)
return [{'@key': k, '@value': data[k]} for k in keys] | dictionary -> list of pairs | Below is the the instruction that describes the task:
### Input:
dictionary -> list of pairs
### Response:
def _Pairs(data):
"""dictionary -> list of pairs"""
keys = sorted(data)
return [{'@key': k, '@value': data[k]} for k in keys] |
def probabilities(self, choosers, alternatives, filter_tables=True):
"""
Returns the probabilities for a set of choosers to choose
from among a set of alternatives.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, ... | Returns the probabilities for a set of choosers to choose
from among a set of alternatives.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataFrame
Table describing the... | Below is the the instruction that describes the task:
### Input:
Returns the probabilities for a set of choosers to choose
from among a set of alternatives.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
... |
def get_book_progress(self, asin):
"""Returns the progress data available for a book.
NOTE: A summary of the two progress formats can be found in the
docstring for `ReadingProgress`.
Args:
asin: The asin of the book to be queried.
Returns:
A `ReadingProgress` instance corresponding to... | Returns the progress data available for a book.
NOTE: A summary of the two progress formats can be found in the
docstring for `ReadingProgress`.
Args:
asin: The asin of the book to be queried.
Returns:
A `ReadingProgress` instance corresponding to the book associated with
`asin`. | Below is the the instruction that describes the task:
### Input:
Returns the progress data available for a book.
NOTE: A summary of the two progress formats can be found in the
docstring for `ReadingProgress`.
Args:
asin: The asin of the book to be queried.
Returns:
A `ReadingProgress... |
def query(dataset_key, query, query_type='sql', profile='default',
parameters=None, **kwargs):
"""Query an existing dataset
:param dataset_key: Dataset identifier, in the form of owner/id or of a url
:type dataset_key: str
:param query: SQL or SPARQL query
:type query: str
:param quer... | Query an existing dataset
:param dataset_key: Dataset identifier, in the form of owner/id or of a url
:type dataset_key: str
:param query: SQL or SPARQL query
:type query: str
:param query_type: The type of the query. Must be either 'sql' or 'sparql'.
(Default value = 'sql')
:type query... | Below is the the instruction that describes the task:
### Input:
Query an existing dataset
:param dataset_key: Dataset identifier, in the form of owner/id or of a url
:type dataset_key: str
:param query: SQL or SPARQL query
:type query: str
:param query_type: The type of the query. Must be eith... |
def download(self, local, remote):
"""
Performs synchronization from a remote file to a local file. The
remote path is the source and the local path is the destination.
"""
self.sync(RemoteFile(remote, self.api), LocalFile(local)) | Performs synchronization from a remote file to a local file. The
remote path is the source and the local path is the destination. | Below is the the instruction that describes the task:
### Input:
Performs synchronization from a remote file to a local file. The
remote path is the source and the local path is the destination.
### Response:
def download(self, local, remote):
"""
Performs synchronization from a remote file... |
def setup(app):
"""Setup sphinx-gallery sphinx extension"""
app.add_config_value('plot_gallery', True, 'html')
app.add_config_value('abort_on_example_error', False, 'html')
app.add_config_value('sphinx_gallery_conf', gallery_conf, 'html')
app.add_stylesheet('gallery.css')
app.connect('builder-i... | Setup sphinx-gallery sphinx extension | Below is the the instruction that describes the task:
### Input:
Setup sphinx-gallery sphinx extension
### Response:
def setup(app):
"""Setup sphinx-gallery sphinx extension"""
app.add_config_value('plot_gallery', True, 'html')
app.add_config_value('abort_on_example_error', False, 'html')
app.add_c... |
def rmp_pixel_deg_xys(vecX, vecY, vecPrfSd, tplPngSize,
varExtXmin, varExtXmax, varExtYmin, varExtYmax):
"""Remap x, y, sigma parameters from pixel to degree.
Parameters
----------
vecX : 1D numpy array
Array with possible x parametrs in pixels
vecY : 1D numpy array
... | Remap x, y, sigma parameters from pixel to degree.
Parameters
----------
vecX : 1D numpy array
Array with possible x parametrs in pixels
vecY : 1D numpy array
Array with possible y parametrs in pixels
vecPrfSd : 1D numpy array
Array with possible sd parametrs in pixels
t... | Below is the the instruction that describes the task:
### Input:
Remap x, y, sigma parameters from pixel to degree.
Parameters
----------
vecX : 1D numpy array
Array with possible x parametrs in pixels
vecY : 1D numpy array
Array with possible y parametrs in pixels
vecPrfSd : 1D... |
def page(self, to=values.unset, from_=values.unset,
date_sent_before=values.unset, date_sent=values.unset,
date_sent_after=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of MessageInstance record... | Retrieve a single page of MessageInstance records from the API.
Request is executed immediately
:param unicode to: Filter by messages sent to this number
:param unicode from_: Filter by from number
:param datetime date_sent_before: Filter by date sent
:param datetime date_sent: ... | Below is the the instruction that describes the task:
### Input:
Retrieve a single page of MessageInstance records from the API.
Request is executed immediately
:param unicode to: Filter by messages sent to this number
:param unicode from_: Filter by from number
:param datetime date... |
def offset_random_rgb(seed, amount=1):
"""
Given a seed color, generate a specified number of random colors (1 color by default) determined by a randomized
offset from the seed.
:param seed:
:param amount:
:return:
"""
r, g, b = seed
results = []
for _ in range(amount):
... | Given a seed color, generate a specified number of random colors (1 color by default) determined by a randomized
offset from the seed.
:param seed:
:param amount:
:return: | Below is the the instruction that describes the task:
### Input:
Given a seed color, generate a specified number of random colors (1 color by default) determined by a randomized
offset from the seed.
:param seed:
:param amount:
:return:
### Response:
def offset_random_rgb(seed, amount=1):
"""
... |
def condition(condition=None, statement=None, _else=None, **kwargs):
"""
Run an statement if input condition is checked and return statement result.
:param condition: condition to check.
:type condition: str or dict
:param statement: statement to process if condition is checked.
:type statement... | Run an statement if input condition is checked and return statement result.
:param condition: condition to check.
:type condition: str or dict
:param statement: statement to process if condition is checked.
:type statement: str or dict
:param _else: else statement.
:type _else: str or dict
... | Below is the the instruction that describes the task:
### Input:
Run an statement if input condition is checked and return statement result.
:param condition: condition to check.
:type condition: str or dict
:param statement: statement to process if condition is checked.
:type statement: str or dic... |
def _build(self):
"""Connects the module to the graph.
Returns:
The learnable state, which has the same type, structure and shape as
the `initial_state` passed to the constructor.
"""
flat_initial_state = nest.flatten(self._initial_state)
if self._mask is not None:
flat_mask = n... | Connects the module to the graph.
Returns:
The learnable state, which has the same type, structure and shape as
the `initial_state` passed to the constructor. | Below is the the instruction that describes the task:
### Input:
Connects the module to the graph.
Returns:
The learnable state, which has the same type, structure and shape as
the `initial_state` passed to the constructor.
### Response:
def _build(self):
"""Connects the module to the graph.... |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidFragment, self).init_widget()
f = self.fragment
f.setFragmentListener(f.getId())
f.onCreateView.connect(self.on_create_view)
f.onDestroyView.connect(self.on_destroy_view) | Initialize the underlying widget. | Below is the the instruction that describes the task:
### Input:
Initialize the underlying widget.
### Response:
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidFragment, self).init_widget()
f = self.fragment
f.setFragmentListener(f.getId())
... |
def update(self, spec, document, upsert=False, manipulate=False,
safe=True, multi=False, callback=None, **kwargs):
"""Update a document(s) in this collection.
Raises :class:`TypeError` if either `spec` or `document` is
not an instance of ``dict`` or `upsert` is not an ins... | Update a document(s) in this collection.
Raises :class:`TypeError` if either `spec` or `document` is
not an instance of ``dict`` or `upsert` is not an instance of
``bool``. If `safe` is ``True`` then the update will be
checked for errors, raising
:class:`~pymongo.errors.... | Below is the the instruction that describes the task:
### Input:
Update a document(s) in this collection.
Raises :class:`TypeError` if either `spec` or `document` is
not an instance of ``dict`` or `upsert` is not an instance of
``bool``. If `safe` is ``True`` then the update will be... |
def _connect_signal(self, index):
"""Create signals for building indexes."""
post_save_signal = ElasticSignal(index, 'build')
post_save_signal.connect(post_save, sender=index.object_type)
self.signals.append(post_save_signal)
post_delete_signal = ElasticSignal(index, 'remove_obj... | Create signals for building indexes. | Below is the the instruction that describes the task:
### Input:
Create signals for building indexes.
### Response:
def _connect_signal(self, index):
"""Create signals for building indexes."""
post_save_signal = ElasticSignal(index, 'build')
post_save_signal.connect(post_save, sender=index.... |
def tune(self):
"""XML node representing tune."""
if self._node.get('activities'):
tune = self._node['activities'].get('tune')
if type(tune) is collections.OrderedDict:
return tune
elif type(tune) is list:
return tune[0]
ret... | XML node representing tune. | Below is the the instruction that describes the task:
### Input:
XML node representing tune.
### Response:
def tune(self):
"""XML node representing tune."""
if self._node.get('activities'):
tune = self._node['activities'].get('tune')
if type(tune) is collections.OrderedDict:... |
def moveEvent(self, event):
"""Reimplement Qt method"""
if not self.isMaximized() and not self.fullscreen_flag:
self.window_position = self.pos()
QMainWindow.moveEvent(self, event)
# To be used by the tour to be able to move
self.sig_moved.emit(event) | Reimplement Qt method | Below is the the instruction that describes the task:
### Input:
Reimplement Qt method
### Response:
def moveEvent(self, event):
"""Reimplement Qt method"""
if not self.isMaximized() and not self.fullscreen_flag:
self.window_position = self.pos()
QMainWindow.moveEvent(self, ... |
def add_inclusion(self, role, value):
"""Include item if `role` equals `value`
Attributes:
role (int): Qt role to compare `value` to
value (object): Value to exclude
"""
self._add_rule(self.includes, role, value) | Include item if `role` equals `value`
Attributes:
role (int): Qt role to compare `value` to
value (object): Value to exclude | Below is the the instruction that describes the task:
### Input:
Include item if `role` equals `value`
Attributes:
role (int): Qt role to compare `value` to
value (object): Value to exclude
### Response:
def add_inclusion(self, role, value):
"""Include item if `role` equals... |
def stdout_logging(loglevel=logging.INFO):
"""Setup basic logging
Args:
loglevel (int): minimum loglevel for emitting messages
"""
logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(lineno)d: %(message)s"
logging.config.dictConfig(level=loglevel, stream=sys.stdout,
... | Setup basic logging
Args:
loglevel (int): minimum loglevel for emitting messages | Below is the the instruction that describes the task:
### Input:
Setup basic logging
Args:
loglevel (int): minimum loglevel for emitting messages
### Response:
def stdout_logging(loglevel=logging.INFO):
"""Setup basic logging
Args:
loglevel (int): minimum loglevel for emitting messages
... |
def get_primitive_structure(self, tolerance=0.25, use_site_props=False,
constrain_latt=None):
"""
This finds a smaller unit cell than the input. Sometimes it doesn"t
find the smallest possible one, so this method is recursively called
until it is unable to... | This finds a smaller unit cell than the input. Sometimes it doesn"t
find the smallest possible one, so this method is recursively called
until it is unable to find a smaller cell.
NOTE: if the tolerance is greater than 1/2 the minimum inter-site
distance in the primitive cell, the algor... | Below is the the instruction that describes the task:
### Input:
This finds a smaller unit cell than the input. Sometimes it doesn"t
find the smallest possible one, so this method is recursively called
until it is unable to find a smaller cell.
NOTE: if the tolerance is greater than 1/2 the... |
def refresh(self):
""" Refresh/Obtain an account's data from the API server
"""
import re
if re.match(r"^1\.2\.[0-9]*$", self.identifier):
account = self.blockchain.rpc.get_objects([self.identifier])[0]
else:
account = self.blockchain.rpc.lookup_account_n... | Refresh/Obtain an account's data from the API server | Below is the the instruction that describes the task:
### Input:
Refresh/Obtain an account's data from the API server
### Response:
def refresh(self):
""" Refresh/Obtain an account's data from the API server
"""
import re
if re.match(r"^1\.2\.[0-9]*$", self.identifier):
... |
def is_device(obj):
"""
Returns True if obj is a device type (derived from DeviceBase), but not defined in
:mod:`lewis.core.devices` or :mod:`lewis.devices`.
:param obj: Object to test.
:return: True if obj is a device type.
"""
return isinstance(obj, type) and issubclass(
obj, Devi... | Returns True if obj is a device type (derived from DeviceBase), but not defined in
:mod:`lewis.core.devices` or :mod:`lewis.devices`.
:param obj: Object to test.
:return: True if obj is a device type. | Below is the the instruction that describes the task:
### Input:
Returns True if obj is a device type (derived from DeviceBase), but not defined in
:mod:`lewis.core.devices` or :mod:`lewis.devices`.
:param obj: Object to test.
:return: True if obj is a device type.
### Response:
def is_device(obj):
... |
def reverse(self):
"""Toggles direction of test
:rtype: bool
"""
enabled = self.lib.iperf_get_test_reverse(self._test)
if enabled:
self._reverse = True
else:
self._reverse = False
return self._reverse | Toggles direction of test
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Toggles direction of test
:rtype: bool
### Response:
def reverse(self):
"""Toggles direction of test
:rtype: bool
"""
enabled = self.lib.iperf_get_test_reverse(self._test)
if enabled:
sel... |
def itemData(self, treeItem, column, role=Qt.DisplayRole):
""" Returns the data stored under the given role for the item. O
"""
if role == Qt.DisplayRole:
if column == self.COL_NODE_NAME:
return treeItem.nodeName
elif column == self.COL_NODE_PATH:
... | Returns the data stored under the given role for the item. O | Below is the the instruction that describes the task:
### Input:
Returns the data stored under the given role for the item. O
### Response:
def itemData(self, treeItem, column, role=Qt.DisplayRole):
""" Returns the data stored under the given role for the item. O
"""
if role == Qt.DisplayRo... |
def dBinaryRochedz(r, D, q, F):
"""
Computes a derivative of the potential with respect to z.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
"""
return -r[2]*(r[0]*r[0]+r[1]*r... | Computes a derivative of the potential with respect to z.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter | Below is the the instruction that describes the task:
### Input:
Computes a derivative of the potential with respect to z.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
### Response:
def... |
def read_micromanager_metadata(fh):
"""Read MicroManager non-TIFF settings from open file and return as dict.
The settings can be used to read image data without parsing the TIFF file.
Raise ValueError if the file does not contain valid MicroManager metadata.
"""
fh.seek(0)
try:
byteo... | Read MicroManager non-TIFF settings from open file and return as dict.
The settings can be used to read image data without parsing the TIFF file.
Raise ValueError if the file does not contain valid MicroManager metadata. | Below is the the instruction that describes the task:
### Input:
Read MicroManager non-TIFF settings from open file and return as dict.
The settings can be used to read image data without parsing the TIFF file.
Raise ValueError if the file does not contain valid MicroManager metadata.
### Response:
def r... |
def extract_command(outputdir, domain_methods, text_domain, keywords,
comment_tags, base_dir, project, version,
msgid_bugs_address):
"""Extracts strings into .pot files
:arg domain: domains to generate strings for or 'all' for all domains
:arg outputdir: output dir f... | Extracts strings into .pot files
:arg domain: domains to generate strings for or 'all' for all domains
:arg outputdir: output dir for .pot files; usually
locale/templates/LC_MESSAGES/
:arg domain_methods: DOMAIN_METHODS setting
:arg text_domain: TEXT_DOMAIN settings
:arg keywords: KEYWORDS ... | Below is the the instruction that describes the task:
### Input:
Extracts strings into .pot files
:arg domain: domains to generate strings for or 'all' for all domains
:arg outputdir: output dir for .pot files; usually
locale/templates/LC_MESSAGES/
:arg domain_methods: DOMAIN_METHODS setting
... |
def items(self, region_codes, include_subregions=False):
"""
Returns calendar classes for regions
:param region_codes list of ISO codes for selected regions
:param include_subregions boolean if subregions
of selected regions should be included in result
:rtype dict
... | Returns calendar classes for regions
:param region_codes list of ISO codes for selected regions
:param include_subregions boolean if subregions
of selected regions should be included in result
:rtype dict
:return dict where keys are ISO codes strings
and values are calen... | Below is the the instruction that describes the task:
### Input:
Returns calendar classes for regions
:param region_codes list of ISO codes for selected regions
:param include_subregions boolean if subregions
of selected regions should be included in result
:rtype dict
:retu... |
async def parallel_results(future_map: Sequence[Tuple]) -> Dict:
"""
Run parallel execution of futures and return mapping of their results to the provided keys.
Just a neat shortcut around ``asyncio.gather()``
:param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_conten... | Run parallel execution of futures and return mapping of their results to the provided keys.
Just a neat shortcut around ``asyncio.gather()``
:param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) )
:return: Dict with futures results mapped to keys {'nav': {1:2}, '... | Below is the the instruction that describes the task:
### Input:
Run parallel execution of futures and return mapping of their results to the provided keys.
Just a neat shortcut around ``asyncio.gather()``
:param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) )
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.