code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def tornadopath2openapi(urlspec, method):
"""Convert Tornado URLSpec to OpenAPI-compliant path.
:param urlspec:
:type urlspec: URLSpec
:param method: Handler http method
:type method: function
"""
if sys.version_info >= (3, 3):
args = list(inspect.sig... | Convert Tornado URLSpec to OpenAPI-compliant path.
:param urlspec:
:type urlspec: URLSpec
:param method: Handler http method
:type method: function | Below is the the instruction that describes the task:
### Input:
Convert Tornado URLSpec to OpenAPI-compliant path.
:param urlspec:
:type urlspec: URLSpec
:param method: Handler http method
:type method: function
### Response:
def tornadopath2openapi(urlspec, method):
"""Co... |
def retrieve_instances(self, query=None):
"""
Executes either the supplied query or the one set via options (or the 'query' property).
:param query: query to execute if not the currently set one
:type query: str
:return: the generated dataq
:rtype: Instances
"""
... | Executes either the supplied query or the one set via options (or the 'query' property).
:param query: query to execute if not the currently set one
:type query: str
:return: the generated dataq
:rtype: Instances | Below is the the instruction that describes the task:
### Input:
Executes either the supplied query or the one set via options (or the 'query' property).
:param query: query to execute if not the currently set one
:type query: str
:return: the generated dataq
:rtype: Instances
### R... |
def apply(self, root):
"""
Apply the import (rule) to the specified schema.
If the schema does not already contain an import for the
I{namespace} specified here, it is added.
@param root: A schema root.
@type root: L{Element}
"""
if not self.filter.match(r... | Apply the import (rule) to the specified schema.
If the schema does not already contain an import for the
I{namespace} specified here, it is added.
@param root: A schema root.
@type root: L{Element} | Below is the the instruction that describes the task:
### Input:
Apply the import (rule) to the specified schema.
If the schema does not already contain an import for the
I{namespace} specified here, it is added.
@param root: A schema root.
@type root: L{Element}
### Response:
def a... |
def add_rule(self, config_name, value, plugins, destination):
"""
Adds a rule. Use add_action_rule or add_match_rule instead
:param rule_wrapper: Rule wrapper class (ActionRule or MatchRule)
:param config_name: config_name of the plugin to add
:param value: configuration informat... | Adds a rule. Use add_action_rule or add_match_rule instead
:param rule_wrapper: Rule wrapper class (ActionRule or MatchRule)
:param config_name: config_name of the plugin to add
:param value: configuration information for the rule
:param plugins: list of all available plugins
:pa... | Below is the the instruction that describes the task:
### Input:
Adds a rule. Use add_action_rule or add_match_rule instead
:param rule_wrapper: Rule wrapper class (ActionRule or MatchRule)
:param config_name: config_name of the plugin to add
:param value: configuration information for the r... |
def resample_to_num_points(self, num_points):
"""
Resample the line to a specified number of points.
:param num_points:
Integer number of points the resulting line should have.
:returns:
A new line with that many points as requested.
"""
assert le... | Resample the line to a specified number of points.
:param num_points:
Integer number of points the resulting line should have.
:returns:
A new line with that many points as requested. | Below is the the instruction that describes the task:
### Input:
Resample the line to a specified number of points.
:param num_points:
Integer number of points the resulting line should have.
:returns:
A new line with that many points as requested.
### Response:
def resampl... |
def _theorem5p4(adj, ub):
"""By Theorem 5.4, if any two vertices have ub + 1 common neighbors
then we can add an edge between them.
"""
new_edges = set()
for u, v in itertools.combinations(adj, 2):
if u in adj[v]:
# already an edge
continue
if len(adj[u].inte... | By Theorem 5.4, if any two vertices have ub + 1 common neighbors
then we can add an edge between them. | Below is the the instruction that describes the task:
### Input:
By Theorem 5.4, if any two vertices have ub + 1 common neighbors
then we can add an edge between them.
### Response:
def _theorem5p4(adj, ub):
"""By Theorem 5.4, if any two vertices have ub + 1 common neighbors
then we can add an edge bet... |
def remove_tenant_user_role(request, project=None, user=None, role=None,
group=None, domain=None):
"""Removes a given single role for a user from a tenant."""
manager = keystoneclient(request, admin=True).roles
if VERSIONS.active < 3:
return manager.remove_user_role(user,... | Removes a given single role for a user from a tenant. | Below is the the instruction that describes the task:
### Input:
Removes a given single role for a user from a tenant.
### Response:
def remove_tenant_user_role(request, project=None, user=None, role=None,
group=None, domain=None):
"""Removes a given single role for a user from a te... |
def has_changed (filename):
"""Check if filename has changed since the last check. If this
is the first check, assume the file is changed."""
key = os.path.abspath(filename)
mtime = get_mtime(key)
if key not in _mtime_cache:
_mtime_cache[key] = mtime
return True
return mtime > _m... | Check if filename has changed since the last check. If this
is the first check, assume the file is changed. | Below is the the instruction that describes the task:
### Input:
Check if filename has changed since the last check. If this
is the first check, assume the file is changed.
### Response:
def has_changed (filename):
"""Check if filename has changed since the last check. If this
is the first check, assum... |
def showFileHeaderData(peInstance):
""" Prints IMAGE_FILE_HEADER fields. """
fileHeaderFields = peInstance.ntHeaders.fileHeader.getFields()
print "[+] IMAGE_FILE_HEADER values:\n"
for field in fileHeaderFields:
print "--> %s = 0x%08x" % (field, fileHeaderFields[field].value) | Prints IMAGE_FILE_HEADER fields. | Below is the the instruction that describes the task:
### Input:
Prints IMAGE_FILE_HEADER fields.
### Response:
def showFileHeaderData(peInstance):
""" Prints IMAGE_FILE_HEADER fields. """
fileHeaderFields = peInstance.ntHeaders.fileHeader.getFields()
print "[+] IMAGE_FILE_HEADER values:\n"
... |
def getAllChildNodes(self):
'''
getAllChildNodes - Gets all the children, and their children,
and their children, and so on, all the way to the end as a TagCollection.
Use .childNodes for a regular list
@return TagCollection<AdvancedTag> - ... | getAllChildNodes - Gets all the children, and their children,
and their children, and so on, all the way to the end as a TagCollection.
Use .childNodes for a regular list
@return TagCollection<AdvancedTag> - A TagCollection of all children (and their children ... | Below is the the instruction that describes the task:
### Input:
getAllChildNodes - Gets all the children, and their children,
and their children, and so on, all the way to the end as a TagCollection.
Use .childNodes for a regular list
@return TagCollectio... |
def get_temp_dir(keep=False):
"""Creates a temporary file, and returns its name.
:param keep: If False (default), the directory will be recursively
deleted when Scapy exits.
:return: A full path to a temporary directory.
"""
dname = tempfile.mkdtemp(prefix="scapy")
if not kee... | Creates a temporary file, and returns its name.
:param keep: If False (default), the directory will be recursively
deleted when Scapy exits.
:return: A full path to a temporary directory. | Below is the the instruction that describes the task:
### Input:
Creates a temporary file, and returns its name.
:param keep: If False (default), the directory will be recursively
deleted when Scapy exits.
:return: A full path to a temporary directory.
### Response:
def get_temp_dir(keep=... |
def _compute_prediction(self):
"""Compute the combined prediction and prediction weight for this
action set. The combined prediction is the weighted average of the
individual predictions of the classifiers. The combined prediction
weight is the sum of the individual prediction weights of... | Compute the combined prediction and prediction weight for this
action set. The combined prediction is the weighted average of the
individual predictions of the classifiers. The combined prediction
weight is the sum of the individual prediction weights of the
classifiers.
Usage:
... | Below is the the instruction that describes the task:
### Input:
Compute the combined prediction and prediction weight for this
action set. The combined prediction is the weighted average of the
individual predictions of the classifiers. The combined prediction
weight is the sum of the indiv... |
def _bfgs_direction(s, y, x, hessinv_estimate=None):
r"""Compute ``Hn^-1(x)`` for the L-BFGS method.
Parameters
----------
s : sequence of `LinearSpaceElement`
The ``s`` coefficients in the BFGS update, see Notes.
y : sequence of `LinearSpaceElement`
The ``y`` coefficients in the BF... | r"""Compute ``Hn^-1(x)`` for the L-BFGS method.
Parameters
----------
s : sequence of `LinearSpaceElement`
The ``s`` coefficients in the BFGS update, see Notes.
y : sequence of `LinearSpaceElement`
The ``y`` coefficients in the BFGS update, see Notes.
x : `LinearSpaceElement`
... | Below is the the instruction that describes the task:
### Input:
r"""Compute ``Hn^-1(x)`` for the L-BFGS method.
Parameters
----------
s : sequence of `LinearSpaceElement`
The ``s`` coefficients in the BFGS update, see Notes.
y : sequence of `LinearSpaceElement`
The ``y`` coefficien... |
def _load_region(self, acct_id, region_name, path):
"""load config from a single per-region subdirectory of an account"""
lim_path = os.path.join(path, 'limit_overrides.json')
thresh_path = os.path.join(path, 'threshold_overrides.json')
res = {'limit_overrides': {}, 'threshold_overrides'... | load config from a single per-region subdirectory of an account | Below is the the instruction that describes the task:
### Input:
load config from a single per-region subdirectory of an account
### Response:
def _load_region(self, acct_id, region_name, path):
"""load config from a single per-region subdirectory of an account"""
lim_path = os.path.join(path, 'lim... |
def run(self):
"""Run the main loop. Returns exit code."""
self.exit_code = 1
self.mainloop = GLib.MainLoop()
try:
future = ensure_future(self._start_async_tasks())
future.callbacks.append(self.set_exit_code)
self.mainloop.run()
return self... | Run the main loop. Returns exit code. | Below is the the instruction that describes the task:
### Input:
Run the main loop. Returns exit code.
### Response:
def run(self):
"""Run the main loop. Returns exit code."""
self.exit_code = 1
self.mainloop = GLib.MainLoop()
try:
future = ensure_future(self._start_asyn... |
def lookup_field(key, lookup_type=None, placeholder=None, html_class="div",
select_type="strapselect", mapping="uuid"):
"""Generates a lookup field for form definitions"""
if lookup_type is None:
lookup_type = key
if placeholder is None:
placeholder = "Select a " + lookup_... | Generates a lookup field for form definitions | Below is the the instruction that describes the task:
### Input:
Generates a lookup field for form definitions
### Response:
def lookup_field(key, lookup_type=None, placeholder=None, html_class="div",
select_type="strapselect", mapping="uuid"):
"""Generates a lookup field for form definitions"... |
def backend_widget(backend):
"""Creates a backend widget.
"""
config = backend.configuration().to_dict()
props = backend.properties().to_dict()
name = widgets.HTML(value="<h4>{name}</h4>".format(name=backend.name()),
layout=widgets.Layout())
n_qubits = config['n_qubits'... | Creates a backend widget. | Below is the the instruction that describes the task:
### Input:
Creates a backend widget.
### Response:
def backend_widget(backend):
"""Creates a backend widget.
"""
config = backend.configuration().to_dict()
props = backend.properties().to_dict()
name = widgets.HTML(value="<h4>{name}</h4>".f... |
def hexify(message):
'''Print out printable characters, but others in hex'''
import string
hexified = []
for char in message:
if (char in '\n\r \t') or (char not in string.printable):
hexified.append('\\x%02x' % ord(char))
else:
hexified.append(char)
return ''... | Print out printable characters, but others in hex | Below is the the instruction that describes the task:
### Input:
Print out printable characters, but others in hex
### Response:
def hexify(message):
'''Print out printable characters, but others in hex'''
import string
hexified = []
for char in message:
if (char in '\n\r \t') or (char not ... |
def _create_user_agent(self):
""" Create the user agent and return it as a string. """
user_agent = '{}/{} {}'.format(pyspacegdn.__title__,
pyspacegdn.__version__,
default_user_agent())
if self.client_name:
... | Create the user agent and return it as a string. | Below is the the instruction that describes the task:
### Input:
Create the user agent and return it as a string.
### Response:
def _create_user_agent(self):
""" Create the user agent and return it as a string. """
user_agent = '{}/{} {}'.format(pyspacegdn.__title__,
... |
def _filehandler(configurable):
"""Default logging file handler."""
filename = configurable.log_name.replace('.', sep)
path = join(configurable.log_path, '{0}.log'.format(filename))
return FileHandler(path, mode='a+') | Default logging file handler. | Below is the the instruction that describes the task:
### Input:
Default logging file handler.
### Response:
def _filehandler(configurable):
"""Default logging file handler."""
filename = configurable.log_name.replace('.', sep)
path = join(configurable.log_path, '{0}.log'.format(filename))
return... |
def reload_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
reload = ET.Element("reload")
config = reload
input = ET.SubElement(reload, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
rbridge_id.text = kwa... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def reload_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
reload = ET.Element("reload")
config = reload
input = ET.SubElemen... |
def _get_referenced_fields_and_fragment_names(
context, # ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
fragment, # type: InlineFragment
):
# type: (..... | Given a reference to a fragment, return the represented collection of fields as well as a list of
nested fragment names referenced via fragment spreads. | Below is the the instruction that describes the task:
### Input:
Given a reference to a fragment, return the represented collection of fields as well as a list of
nested fragment names referenced via fragment spreads.
### Response:
def _get_referenced_fields_and_fragment_names(
context, # ValidationContex... |
def lmx_relative():
"""Language model using relative attention."""
hparams = lmx_base()
hparams.self_attention_type = "dot_product_relative_v2"
hparams.activation_dtype = "float32"
hparams.weight_dtype = "float32"
return hparams | Language model using relative attention. | Below is the the instruction that describes the task:
### Input:
Language model using relative attention.
### Response:
def lmx_relative():
"""Language model using relative attention."""
hparams = lmx_base()
hparams.self_attention_type = "dot_product_relative_v2"
hparams.activation_dtype = "float32"
hpar... |
def _do_cross_validation(self, clf, data, task):
"""Run voxelwise cross validation based on correlation vectors.
clf: classification function
the classifier to be used in cross validation
data: 3D numpy array
If using sklearn.svm.SVC with precomputed kernel,
... | Run voxelwise cross validation based on correlation vectors.
clf: classification function
the classifier to be used in cross validation
data: 3D numpy array
If using sklearn.svm.SVC with precomputed kernel,
it is in shape [num_processed_voxels, num_epochs, num_epochs... | Below is the the instruction that describes the task:
### Input:
Run voxelwise cross validation based on correlation vectors.
clf: classification function
the classifier to be used in cross validation
data: 3D numpy array
If using sklearn.svm.SVC with precomputed kernel,
... |
def clean_draft_pages_from_space(confluence, space_key, count, date_now):
"""
Remove draft pages from space using datetime.now
:param confluence:
:param space_key:
:param count:
:param date_now:
:return: int counter
"""
pages = confluence.get_all_draft_pages_from_space(space=space_ke... | Remove draft pages from space using datetime.now
:param confluence:
:param space_key:
:param count:
:param date_now:
:return: int counter | Below is the the instruction that describes the task:
### Input:
Remove draft pages from space using datetime.now
:param confluence:
:param space_key:
:param count:
:param date_now:
:return: int counter
### Response:
def clean_draft_pages_from_space(confluence, space_key, count, date_now):
... |
def CheckMounts(filename):
"""Parses the currently mounted devices."""
with io.open(filename, "r") as fd:
for line in fd:
try:
device, mnt_point, fs_type, _ = line.split(" ", 3)
except ValueError:
continue
if fs_type in ACCEPTABLE_FILESYSTEMS:
if os.path.exists(device):... | Parses the currently mounted devices. | Below is the the instruction that describes the task:
### Input:
Parses the currently mounted devices.
### Response:
def CheckMounts(filename):
"""Parses the currently mounted devices."""
with io.open(filename, "r") as fd:
for line in fd:
try:
device, mnt_point, fs_type, _ = line.split(" ", 3... |
def generateFormatToExtension(format, fallbackFormat):
"""
+--------------+--------------------------------------------------------------------+
| mactype1 | Mac Type 1 font (generates suitcase and LWFN file) |
+--------------+-----------------------------------------... | +--------------+--------------------------------------------------------------------+
| mactype1 | Mac Type 1 font (generates suitcase and LWFN file) |
+--------------+--------------------------------------------------------------------+
| macttf | Mac TrueType font (ge... | Below is the the instruction that describes the task:
### Input:
+--------------+--------------------------------------------------------------------+
| mactype1 | Mac Type 1 font (generates suitcase and LWFN file) |
+--------------+-----------------------------------------------... |
def rotMatrix2AxisAndAngle(R):
"""
stackoverflow.com/questions/12463487/obtain-rotation-axis-from-rotation-matrix-and-translation-vector-in-opencv
R : 3x3 rotation matrix
returns axis, angle
"""
angle = np.arccos((R[0, 0] + R[1, 1] + R[2, 2] - 1)/ 2)
axis = np.array([
# x
(... | stackoverflow.com/questions/12463487/obtain-rotation-axis-from-rotation-matrix-and-translation-vector-in-opencv
R : 3x3 rotation matrix
returns axis, angle | Below is the the instruction that describes the task:
### Input:
stackoverflow.com/questions/12463487/obtain-rotation-axis-from-rotation-matrix-and-translation-vector-in-opencv
R : 3x3 rotation matrix
returns axis, angle
### Response:
def rotMatrix2AxisAndAngle(R):
"""
stackoverflow.com/questions/... |
def _resolve_path(path, manager_dict):
"""
Resolve a path based on a dictionary of manager prefixes.
Returns a triple of (prefix, manager, manager_relative_path).
"""
path = normalize_api_path(path)
parts = path.split('/')
# Try to find a sub-manager for the first subdirectory.
mgr = m... | Resolve a path based on a dictionary of manager prefixes.
Returns a triple of (prefix, manager, manager_relative_path). | Below is the the instruction that describes the task:
### Input:
Resolve a path based on a dictionary of manager prefixes.
Returns a triple of (prefix, manager, manager_relative_path).
### Response:
def _resolve_path(path, manager_dict):
"""
Resolve a path based on a dictionary of manager prefixes.
... |
def _unpack_bytes(bytes):
"""
Unpack a set of bytes into an integer. First pads to 4 bytes.
Little endian.
"""
if bytes == b'':
return 0
int_length = 4
len_diff = int_length - len(bytes)
bytes = bytes + len_diff * b'\x00'
return struct.unpack("<L", bytes)[0] | Unpack a set of bytes into an integer. First pads to 4 bytes.
Little endian. | Below is the the instruction that describes the task:
### Input:
Unpack a set of bytes into an integer. First pads to 4 bytes.
Little endian.
### Response:
def _unpack_bytes(bytes):
"""
Unpack a set of bytes into an integer. First pads to 4 bytes.
Little endian.
"""
if bytes == b'':
... |
def addCompletedJob(self, job, wallTime):
"""
Adds the shape of a completed job to the queue, allowing the scalar to use the last N
completed jobs in factoring how many nodes are required in the cluster.
:param toil.job.JobNode job: The memory, core and disk requirements of the completed... | Adds the shape of a completed job to the queue, allowing the scalar to use the last N
completed jobs in factoring how many nodes are required in the cluster.
:param toil.job.JobNode job: The memory, core and disk requirements of the completed job
:param int wallTime: The wall-time taken to compl... | Below is the the instruction that describes the task:
### Input:
Adds the shape of a completed job to the queue, allowing the scalar to use the last N
completed jobs in factoring how many nodes are required in the cluster.
:param toil.job.JobNode job: The memory, core and disk requirements of the co... |
def _set_queues_interface(self, v, load=False):
"""
Setter method for queues_interface, mapped from YANG variable /openflow_state/queues_interface (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_queues_interface is considered as a private
method. Backends... | Setter method for queues_interface, mapped from YANG variable /openflow_state/queues_interface (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_queues_interface is considered as a private
method. Backends looking to populate this variable should
do so via call... | Below is the the instruction that describes the task:
### Input:
Setter method for queues_interface, mapped from YANG variable /openflow_state/queues_interface (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_queues_interface is considered as a private
method.... |
def create_network(self, action, n_name, **kwargs):
"""
Creates a configured network.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param n_name: Network name.
:type n_name: unicode | str
:param kwargs: Additional keyword a... | Creates a configured network.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param n_name: Network name.
:type n_name: unicode | str
:param kwargs: Additional keyword arguments to complement or override the configuration-based values.
... | Below is the the instruction that describes the task:
### Input:
Creates a configured network.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param n_name: Network name.
:type n_name: unicode | str
:param kwargs: Additional keyword argu... |
def get_name(self, data):
""" For non-specific queries, this will return the actual name in the
result. """
if self.node.specific_attribute:
return self.node.name
name = data.get(self.predicate_var)
if str(RDF.type) in [self.node.name, name]:
return '$sche... | For non-specific queries, this will return the actual name in the
result. | Below is the the instruction that describes the task:
### Input:
For non-specific queries, this will return the actual name in the
result.
### Response:
def get_name(self, data):
""" For non-specific queries, this will return the actual name in the
result. """
if self.node.specific_... |
def handle(self, *args, **options):
"""
Run the specified Selenium test(s) the indicated number of times in
the specified browser.
"""
browser_name = options['browser_name']
count = options['count']
if len(args) > 0:
tests = list(args)
else:
... | Run the specified Selenium test(s) the indicated number of times in
the specified browser. | Below is the the instruction that describes the task:
### Input:
Run the specified Selenium test(s) the indicated number of times in
the specified browser.
### Response:
def handle(self, *args, **options):
"""
Run the specified Selenium test(s) the indicated number of times in
the s... |
def from_json_file(schema_file, validate=True):
# type: (TextIO, bool) -> Schema
""" Load a Schema object from a json file.
:param schema_file: A JSON file containing the schema.
:param validate: (default True) Raise an exception if the
schema does not conform to the master schema.
... | Load a Schema object from a json file.
:param schema_file: A JSON file containing the schema.
:param validate: (default True) Raise an exception if the
schema does not conform to the master schema.
:raises SchemaError: When the schema is invalid.
:return: the Schema | Below is the the instruction that describes the task:
### Input:
Load a Schema object from a json file.
:param schema_file: A JSON file containing the schema.
:param validate: (default True) Raise an exception if the
schema does not conform to the master schema.
:raises SchemaErr... |
def scan(self, module, onerror=None, ignore=None):
"""Scan the given module object for L{Method}s and register them."""
from venusian import Scanner
scanner = Scanner(registry=self)
kwargs = {"onerror": onerror, "categories": ["method"]}
if ignore is not None:
# Only ... | Scan the given module object for L{Method}s and register them. | Below is the the instruction that describes the task:
### Input:
Scan the given module object for L{Method}s and register them.
### Response:
def scan(self, module, onerror=None, ignore=None):
"""Scan the given module object for L{Method}s and register them."""
from venusian import Scanner
... |
def enabled(self):
"""
read or write the child sub-reaper flag of the current process
This property behaves in the following manner:
* If a read is attempted and a prior read or write has determined that
this feature is unavailable (status is equal to ``SR_UNSUPPORTED``)
... | read or write the child sub-reaper flag of the current process
This property behaves in the following manner:
* If a read is attempted and a prior read or write has determined that
this feature is unavailable (status is equal to ``SR_UNSUPPORTED``)
then no further attempts are made... | Below is the the instruction that describes the task:
### Input:
read or write the child sub-reaper flag of the current process
This property behaves in the following manner:
* If a read is attempted and a prior read or write has determined that
this feature is unavailable (status is equ... |
async def identity_of(client: Client, search: str) -> dict:
"""
GET Identity data written in the blockchain
:param client: Client to connect to the api
:param search: UID or public key
:return:
"""
return await client.get(MODULE + '/identity-of/%s' % search, schema=IDENTITY_OF_SCHEMA) | GET Identity data written in the blockchain
:param client: Client to connect to the api
:param search: UID or public key
:return: | Below is the the instruction that describes the task:
### Input:
GET Identity data written in the blockchain
:param client: Client to connect to the api
:param search: UID or public key
:return:
### Response:
async def identity_of(client: Client, search: str) -> dict:
"""
GET Identity data wri... |
def sig_handler(self, sig, _):
""" Handle the signal sent to the process
:param sig: Signal set to the process
:param _: Frame is not being used
"""
import tornado.ioloop
from tornado.process import task_id
tid = task_id()
pid = os.getpid()
if tid... | Handle the signal sent to the process
:param sig: Signal set to the process
:param _: Frame is not being used | Below is the the instruction that describes the task:
### Input:
Handle the signal sent to the process
:param sig: Signal set to the process
:param _: Frame is not being used
### Response:
def sig_handler(self, sig, _):
""" Handle the signal sent to the process
:param sig: Signal ... |
def generate(self):
"""
Generates a new token for this column based on its bit length. This method
will not ensure uniqueness in the model itself, that should be checked against
the model records in the database first.
:return: <str>
"""
try:
mode... | Generates a new token for this column based on its bit length. This method
will not ensure uniqueness in the model itself, that should be checked against
the model records in the database first.
:return: <str> | Below is the the instruction that describes the task:
### Input:
Generates a new token for this column based on its bit length. This method
will not ensure uniqueness in the model itself, that should be checked against
the model records in the database first.
:return: <str>
### Response... |
def on_trial_complete(self,
trial_id,
result=None,
error=False,
early_terminated=False):
"""Passes the result to BayesOpt unless early terminated or errored"""
if result:
self.optimizer.re... | Passes the result to BayesOpt unless early terminated or errored | Below is the the instruction that describes the task:
### Input:
Passes the result to BayesOpt unless early terminated or errored
### Response:
def on_trial_complete(self,
trial_id,
result=None,
error=False,
ear... |
def install_remote(self):
"""Download, extract and install NApp."""
package, pkg_folder = None, None
try:
package = self._download()
pkg_folder = self._extract(package)
napp_folder = self._get_local_folder(pkg_folder)
dst = self._installed / self.u... | Download, extract and install NApp. | Below is the the instruction that describes the task:
### Input:
Download, extract and install NApp.
### Response:
def install_remote(self):
"""Download, extract and install NApp."""
package, pkg_folder = None, None
try:
package = self._download()
pkg_folder = self._... |
def clear_choice(self, choice):
"""stub"""
if len(self.my_osid_object_form._my_map['choices']) == 0:
raise IllegalState('there are currently no choices defined for this question')
if (len(self.my_osid_object_form._my_map['choices']) == 1 and
choice in self.my_osid_obj... | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def clear_choice(self, choice):
"""stub"""
if len(self.my_osid_object_form._my_map['choices']) == 0:
raise IllegalState('there are currently no choices defined for this question')
if (len(self.my... |
def three_digit(number):
""" Add 0s to inputs that their length is less than 3.
:param number:
The number to convert
:type number:
int
:returns:
String
:example:
>>> three_digit(1)
'001'
"""
number = str(number)
if len(number) == 1:
retu... | Add 0s to inputs that their length is less than 3.
:param number:
The number to convert
:type number:
int
:returns:
String
:example:
>>> three_digit(1)
'001' | Below is the the instruction that describes the task:
### Input:
Add 0s to inputs that their length is less than 3.
:param number:
The number to convert
:type number:
int
:returns:
String
:example:
>>> three_digit(1)
'001'
### Response:
def three_digit(num... |
def _search_in_bases(type_):
"""Implementation detail."""
found = False
for base_type in type_.declaration.bases:
try:
found = internal_type_traits.get_by_name(
base_type.related_class, "element_type")
except runtime_errors.declaration_not_found_t:
pas... | Implementation detail. | Below is the the instruction that describes the task:
### Input:
Implementation detail.
### Response:
def _search_in_bases(type_):
"""Implementation detail."""
found = False
for base_type in type_.declaration.bases:
try:
found = internal_type_traits.get_by_name(
base... |
def _check_and_replace_parser_args(parser, section, option, rename_func, make_dirs=True):
""" Searches for parser settings that define filenames.
If such settings are found, they are renamed according to the wildcard
rules. Moreover, it is also tried to create the corresponding folders.
... | Searches for parser settings that define filenames.
If such settings are found, they are renamed according to the wildcard
rules. Moreover, it is also tried to create the corresponding folders.
:param parser: A config parser
:param section: A config section
:param option: The ... | Below is the the instruction that describes the task:
### Input:
Searches for parser settings that define filenames.
If such settings are found, they are renamed according to the wildcard
rules. Moreover, it is also tried to create the corresponding folders.
:param parser: A config parser... |
def help(obj, visualization=True, ansi=True, backend=None,
recursive=False, pattern=None):
"""
Extended version of the built-in help that supports parameterized
functions and objects. A pattern (regular expression) may be used to
filter the output and if recursive is set to True, documentation ... | Extended version of the built-in help that supports parameterized
functions and objects. A pattern (regular expression) may be used to
filter the output and if recursive is set to True, documentation for
the supplied object is shown. Note that the recursive option will
only work with an object instance ... | Below is the the instruction that describes the task:
### Input:
Extended version of the built-in help that supports parameterized
functions and objects. A pattern (regular expression) may be used to
filter the output and if recursive is set to True, documentation for
the supplied object is shown. Note ... |
def abs_path(rel_path):
"""Convert a path that is relative to the module from which this function is called,
to an absolute path.
Args:
rel_path: str
Path relative to the location of the module file from which this function is called.
Returns:
str : Absolute path to the location ... | Convert a path that is relative to the module from which this function is called,
to an absolute path.
Args:
rel_path: str
Path relative to the location of the module file from which this function is called.
Returns:
str : Absolute path to the location specified by ``rel_path``. | Below is the the instruction that describes the task:
### Input:
Convert a path that is relative to the module from which this function is called,
to an absolute path.
Args:
rel_path: str
Path relative to the location of the module file from which this function is called.
Returns:
... |
def get_closest_points(self, max_distance=None, origin_index=0, origin_raw=None):
"""
Get closest points to a given origin. Returns a list of 2 element tuples where first element is the destination and the second is the distance.
"""
if not self.dict_response['distance']['value']:
... | Get closest points to a given origin. Returns a list of 2 element tuples where first element is the destination and the second is the distance. | Below is the the instruction that describes the task:
### Input:
Get closest points to a given origin. Returns a list of 2 element tuples where first element is the destination and the second is the distance.
### Response:
def get_closest_points(self, max_distance=None, origin_index=0, origin_raw=None):
""... |
def set_connections_params(
self, harakiri=None, timeout_socket=None, retry_delay=None, retry_max=None, use_xclient=None):
"""Sets connection-related parameters.
:param int harakiri: Set gateway harakiri timeout (seconds).
:param int timeout_socket: Node socket timeout (seconds). ... | Sets connection-related parameters.
:param int harakiri: Set gateway harakiri timeout (seconds).
:param int timeout_socket: Node socket timeout (seconds). Default: 60.
:param int retry_delay: Retry connections to dead static nodes after the specified
amount of seconds. Default: 3... | Below is the the instruction that describes the task:
### Input:
Sets connection-related parameters.
:param int harakiri: Set gateway harakiri timeout (seconds).
:param int timeout_socket: Node socket timeout (seconds). Default: 60.
:param int retry_delay: Retry connections to dead stati... |
def knock_out(self):
"""Knockout gene by marking it as non-functional and setting all
associated reactions bounds to zero.
The change is reverted upon exit if executed within the model as
context.
"""
self.functional = False
for reaction in self.reactions:
... | Knockout gene by marking it as non-functional and setting all
associated reactions bounds to zero.
The change is reverted upon exit if executed within the model as
context. | Below is the the instruction that describes the task:
### Input:
Knockout gene by marking it as non-functional and setting all
associated reactions bounds to zero.
The change is reverted upon exit if executed within the model as
context.
### Response:
def knock_out(self):
"""Knocko... |
def add_dependency(self, depend):
"""Adds dependencies."""
try:
self._add_child(self.depends, self.depends_set, depend)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = s... | Adds dependencies. | Below is the the instruction that describes the task:
### Input:
Adds dependencies.
### Response:
def add_dependency(self, depend):
"""Adds dependencies."""
try:
self._add_child(self.depends, self.depends_set, depend)
except TypeError as e:
e = e.args[0]
... |
def figsize(x=8, y=7., aspect=1.):
""" manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar
"""
# update rcparams with adjusted figsize params
mpl.rcParams.update({'figure.figsize': (x*as... | manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar | Below is the the instruction that describes the task:
### Input:
manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar
### Response:
def figsize(x=8, y=7., aspect=1.):
""" manually set the defaul... |
def create_from_json(cls, json_data):
"""Deserialize msa json data into a Msa object
Args:
json_data (dict): The json data for this msa
Returns:
Msa object
"""
msa = Msa()
msa.msa = json_data["msa_info"]["msa"]
msa.meta = json_data["meta... | Deserialize msa json data into a Msa object
Args:
json_data (dict): The json data for this msa
Returns:
Msa object | Below is the the instruction that describes the task:
### Input:
Deserialize msa json data into a Msa object
Args:
json_data (dict): The json data for this msa
Returns:
Msa object
### Response:
def create_from_json(cls, json_data):
"""Deserialize msa json data into... |
def first(self) -> "QuerySet":
"""
Limit queryset to one object and return one object instead of list.
"""
queryset = self._clone()
queryset._limit = 1
queryset._single = True
return queryset | Limit queryset to one object and return one object instead of list. | Below is the the instruction that describes the task:
### Input:
Limit queryset to one object and return one object instead of list.
### Response:
def first(self) -> "QuerySet":
"""
Limit queryset to one object and return one object instead of list.
"""
queryset = self._clone()
... |
def get_online_version ():
"""Download update info and parse it."""
# prevent getting a cached answer
headers = {'Pragma': 'no-cache', 'Cache-Control': 'no-cache'}
content, info = get_content(UPDATE_URL, addheaders=headers)
if content is None:
return content, info
version, url = None, No... | Download update info and parse it. | Below is the the instruction that describes the task:
### Input:
Download update info and parse it.
### Response:
def get_online_version ():
"""Download update info and parse it."""
# prevent getting a cached answer
headers = {'Pragma': 'no-cache', 'Cache-Control': 'no-cache'}
content, info = get_c... |
def get_center_of_mass(self):
"""
Get a tuple (x,y) that is the center of mass. The center of mass is not
necessarily the same as the center of the bounding box. Imagine a black
square and a single dot wide outside of the square.
"""
xsum, ysum, counter = 0., 0., 0
... | Get a tuple (x,y) that is the center of mass. The center of mass is not
necessarily the same as the center of the bounding box. Imagine a black
square and a single dot wide outside of the square. | Below is the the instruction that describes the task:
### Input:
Get a tuple (x,y) that is the center of mass. The center of mass is not
necessarily the same as the center of the bounding box. Imagine a black
square and a single dot wide outside of the square.
### Response:
def get_center_of_mass(s... |
def get_fields(model):
"""
Returns a Model's knockout_fields,
or the default set of field names.
"""
try:
if hasattr(model, "knockout_fields"):
fields = model.knockout_fields()
else:
try:
fields = model_to_dict(model).keys()
except... | Returns a Model's knockout_fields,
or the default set of field names. | Below is the the instruction that describes the task:
### Input:
Returns a Model's knockout_fields,
or the default set of field names.
### Response:
def get_fields(model):
"""
Returns a Model's knockout_fields,
or the default set of field names.
"""
try:
if hasattr(model, "knockout... |
def setsweep(self, sweep=0, channel=0):
"""set the sweep and channel of an ABF. Both start at 0."""
try:
sweep=int(sweep)
except:
self.log.error("trying to set sweep to [%s]",sweep)
return
if sweep<0:
sweep=self.sweeps-1-sweep # if negative... | set the sweep and channel of an ABF. Both start at 0. | Below is the the instruction that describes the task:
### Input:
set the sweep and channel of an ABF. Both start at 0.
### Response:
def setsweep(self, sweep=0, channel=0):
"""set the sweep and channel of an ABF. Both start at 0."""
try:
sweep=int(sweep)
except:
self... |
def melt(self, plot=False):
"""
Find and merge groups of polygons in the surface that meet the
following criteria:
* Are coplanars.
* Are contiguous.
* The result is convex.
This method is very useful at reducing the num... | Find and merge groups of polygons in the surface that meet the
following criteria:
* Are coplanars.
* Are contiguous.
* The result is convex.
This method is very useful at reducing the number the items and,
therefore, the shadowi... | Below is the the instruction that describes the task:
### Input:
Find and merge groups of polygons in the surface that meet the
following criteria:
* Are coplanars.
* Are contiguous.
* The result is convex.
This method is very useful ... |
def check_for_missed_cleanup():
"""Check for TaskAttempts that were never cleaned up
"""
if get_setting('PRESERVE_ALL'):
return
from api.models.tasks import TaskAttempt
if get_setting('PRESERVE_ON_FAILURE'):
for task_attempt in TaskAttempt.objects.filter(
status_is_ru... | Check for TaskAttempts that were never cleaned up | Below is the the instruction that describes the task:
### Input:
Check for TaskAttempts that were never cleaned up
### Response:
def check_for_missed_cleanup():
"""Check for TaskAttempts that were never cleaned up
"""
if get_setting('PRESERVE_ALL'):
return
from api.models.tasks import TaskA... |
def vel_horizontal(HeightWaterCritical):
"""Return the horizontal velocity."""
#Checking input validity
ut.check_range([HeightWaterCritical, ">0", "Critical height of water"])
return np.sqrt(gravity.magnitude * HeightWaterCritical) | Return the horizontal velocity. | Below is the the instruction that describes the task:
### Input:
Return the horizontal velocity.
### Response:
def vel_horizontal(HeightWaterCritical):
"""Return the horizontal velocity."""
#Checking input validity
ut.check_range([HeightWaterCritical, ">0", "Critical height of water"])
return np.sq... |
def _dict_subset(keys, master_dict):
'''
Return a dictionary of only the subset of keys/values specified in keys
'''
return dict([(k, v) for k, v in six.iteritems(master_dict) if k in keys]) | Return a dictionary of only the subset of keys/values specified in keys | Below is the the instruction that describes the task:
### Input:
Return a dictionary of only the subset of keys/values specified in keys
### Response:
def _dict_subset(keys, master_dict):
'''
Return a dictionary of only the subset of keys/values specified in keys
'''
return dict([(k, v) for k, v in... |
def console_list_load_xp(
filename: str
) -> Optional[List[tcod.console.Console]]:
"""Return a list of consoles from a REXPaint `.xp` file."""
tcod_list = lib.TCOD_console_list_from_xp(filename.encode("utf-8"))
if tcod_list == ffi.NULL:
return None
try:
python_list = []
lib.T... | Return a list of consoles from a REXPaint `.xp` file. | Below is the the instruction that describes the task:
### Input:
Return a list of consoles from a REXPaint `.xp` file.
### Response:
def console_list_load_xp(
filename: str
) -> Optional[List[tcod.console.Console]]:
"""Return a list of consoles from a REXPaint `.xp` file."""
tcod_list = lib.TCOD_consol... |
def write(self, text: str):
"""
Prints text to the screen.
Supports colors by using the color constants.
To use colors, add the color before the text you want to print.
:param text: The text to print.
"""
# Default color is NORMAL.
last_color = (self._DAR... | Prints text to the screen.
Supports colors by using the color constants.
To use colors, add the color before the text you want to print.
:param text: The text to print. | Below is the the instruction that describes the task:
### Input:
Prints text to the screen.
Supports colors by using the color constants.
To use colors, add the color before the text you want to print.
:param text: The text to print.
### Response:
def write(self, text: str):
"""
... |
def query(self, expression, vm='python'):
"""Evaluate expression and then use it to extract rows from the table.
Parameters
----------
expression : string
Expression to evaluate.
vm : {'numexpr', 'python'}
Virtual machine to use.
Returns
... | Evaluate expression and then use it to extract rows from the table.
Parameters
----------
expression : string
Expression to evaluate.
vm : {'numexpr', 'python'}
Virtual machine to use.
Returns
-------
result : structured array | Below is the the instruction that describes the task:
### Input:
Evaluate expression and then use it to extract rows from the table.
Parameters
----------
expression : string
Expression to evaluate.
vm : {'numexpr', 'python'}
Virtual machine to use.
... |
def distance_to_edge(self, skydir):
"""Return the angular distance from the given direction and
the edge of the projection."""
xpix, ypix = skydir.to_pixel(self.wcs, origin=0)
deltax = np.array((xpix - self._pix_center[0]) * self._pix_size[0],
ndmin=1)
... | Return the angular distance from the given direction and
the edge of the projection. | Below is the the instruction that describes the task:
### Input:
Return the angular distance from the given direction and
the edge of the projection.
### Response:
def distance_to_edge(self, skydir):
"""Return the angular distance from the given direction and
the edge of the projection."""
... |
def setValues(self, values):
"""
Assign the values (string or float) to the parameter instances with the
specified indices, equivalent to the AMPL code:
.. code-block:: ampl
let {i in indices} par[i] := values[i];
Args:
values: list, dictionary or :clas... | Assign the values (string or float) to the parameter instances with the
specified indices, equivalent to the AMPL code:
.. code-block:: ampl
let {i in indices} par[i] := values[i];
Args:
values: list, dictionary or :class:`~amplpy.DataFrame` with the
indice... | Below is the the instruction that describes the task:
### Input:
Assign the values (string or float) to the parameter instances with the
specified indices, equivalent to the AMPL code:
.. code-block:: ampl
let {i in indices} par[i] := values[i];
Args:
values: list,... |
def update_all(self, *args, **kwargs):
"""Updates all objects with details given if they match a set of conditions supplied.
This method forwards filters and updates directly to the repository. It does not
instantiate entities and it does not trigger Entity callbacks or validations.
Up... | Updates all objects with details given if they match a set of conditions supplied.
This method forwards filters and updates directly to the repository. It does not
instantiate entities and it does not trigger Entity callbacks or validations.
Update values can be specified either as a dict, or ... | Below is the the instruction that describes the task:
### Input:
Updates all objects with details given if they match a set of conditions supplied.
This method forwards filters and updates directly to the repository. It does not
instantiate entities and it does not trigger Entity callbacks or valid... |
def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx):
"""Training function."""
hvd.broadcast_parameters(model.collect_params(), root_rank=0)
mlm_metric = nlp.metric.MaskedAccuracy()
nsp_metric = nlp.metric.MaskedAccuracy()
mlm_metric.reset()
nsp_metric.reset()
logging.debug('C... | Training function. | Below is the the instruction that describes the task:
### Input:
Training function.
### Response:
def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx):
"""Training function."""
hvd.broadcast_parameters(model.collect_params(), root_rank=0)
mlm_metric = nlp.metric.MaskedAccuracy()
nsp_m... |
def getmacbyip(ip, chainCC=0):
"""Return MAC address corresponding to a given IP address"""
if isinstance(ip, Net):
ip = next(iter(ip))
ip = inet_ntoa(inet_aton(ip or "0.0.0.0"))
tmp = [orb(e) for e in inet_aton(ip)]
if (tmp[0] & 0xf0) == 0xe0: # mcast @
return "01:00:5e:%.2x:%.2x:%... | Return MAC address corresponding to a given IP address | Below is the the instruction that describes the task:
### Input:
Return MAC address corresponding to a given IP address
### Response:
def getmacbyip(ip, chainCC=0):
"""Return MAC address corresponding to a given IP address"""
if isinstance(ip, Net):
ip = next(iter(ip))
ip = inet_ntoa(inet_aton(... |
def get_name_history(name, hostport=None, proxy=None, history_page=None):
"""
Get the full history of a name
Returns {'status': True, 'history': ...} on success, where history is grouped by block
Returns {'error': ...} on error
"""
assert hostport or proxy, 'Need hostport or proxy'
if proxy ... | Get the full history of a name
Returns {'status': True, 'history': ...} on success, where history is grouped by block
Returns {'error': ...} on error | Below is the the instruction that describes the task:
### Input:
Get the full history of a name
Returns {'status': True, 'history': ...} on success, where history is grouped by block
Returns {'error': ...} on error
### Response:
def get_name_history(name, hostport=None, proxy=None, history_page=None):
... |
def query(self, search_model: QueryModel):
"""Query elasticsearch for objects.
:param search_model: object of QueryModel.
:return: list of objects that match the query.
"""
query_parsed = query_parser(search_model.query)
self.logger.debug(f'elasticsearch::query::{query_pa... | Query elasticsearch for objects.
:param search_model: object of QueryModel.
:return: list of objects that match the query. | Below is the the instruction that describes the task:
### Input:
Query elasticsearch for objects.
:param search_model: object of QueryModel.
:return: list of objects that match the query.
### Response:
def query(self, search_model: QueryModel):
"""Query elasticsearch for objects.
:p... |
def supports_calendar_type(self, calendar_type):
"""Tests if the given calendar type is supported.
arg: calendar_type (osid.type.Type): a calendar Type
return: (boolean) - ``true`` if the type is supported, ``false``
otherwise
raise: IllegalState - syntax is not a ``... | Tests if the given calendar type is supported.
arg: calendar_type (osid.type.Type): a calendar Type
return: (boolean) - ``true`` if the type is supported, ``false``
otherwise
raise: IllegalState - syntax is not a ``DATETIME`` or
``DURATION``
raise: N... | Below is the the instruction that describes the task:
### Input:
Tests if the given calendar type is supported.
arg: calendar_type (osid.type.Type): a calendar Type
return: (boolean) - ``true`` if the type is supported, ``false``
otherwise
raise: IllegalState - syntax is... |
def processClubAttendance(f, clubs):
"""Process the attendance data of one club
If the club already exists in the list update its data.
If the club is new create a new Club object and add it to the dict
The next step is to iterate over all the lines and add a record for each line.
When reaching an empty... | Process the attendance data of one club
If the club already exists in the list update its data.
If the club is new create a new Club object and add it to the dict
The next step is to iterate over all the lines and add a record for each line.
When reaching an empty line it means there are no more records f... | Below is the the instruction that describes the task:
### Input:
Process the attendance data of one club
If the club already exists in the list update its data.
If the club is new create a new Club object and add it to the dict
The next step is to iterate over all the lines and add a record for each lin... |
def supports(cls, template_file=None):
"""
:return: Whether the engine can process given template file or not.
"""
if anytemplate.compat.IS_PYTHON_3:
cls._priority = 99
return False # Always as it's not ported to python 3.
return super(Engine, cls).suppo... | :return: Whether the engine can process given template file or not. | Below is the the instruction that describes the task:
### Input:
:return: Whether the engine can process given template file or not.
### Response:
def supports(cls, template_file=None):
"""
:return: Whether the engine can process given template file or not.
"""
if anytemplate.compat... |
def facetrecordtrees(table, key, start='start', stop='stop'):
"""
Construct faceted interval trees for the given table, where each node in
the tree is a record.
"""
import intervaltree
getstart = attrgetter(start)
getstop = attrgetter(stop)
getkey = attrgetter(key)
trees = dict()
... | Construct faceted interval trees for the given table, where each node in
the tree is a record. | Below is the the instruction that describes the task:
### Input:
Construct faceted interval trees for the given table, where each node in
the tree is a record.
### Response:
def facetrecordtrees(table, key, start='start', stop='stop'):
"""
Construct faceted interval trees for the given table, where ea... |
def halt(self):
"""
halt: None -> None
If this instance has a separate thread running, it will be
halted. This method will wait until the thread has cleaned
up before returning.
"""
if self._callback:
self._thread_continue = False
self._th... | halt: None -> None
If this instance has a separate thread running, it will be
halted. This method will wait until the thread has cleaned
up before returning. | Below is the the instruction that describes the task:
### Input:
halt: None -> None
If this instance has a separate thread running, it will be
halted. This method will wait until the thread has cleaned
up before returning.
### Response:
def halt(self):
"""
halt: None -> Non... |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AvailablePhoneNumberCountryContext for this AvailablePhoneNumberCountryInstance
:rtype: twilio.re... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AvailablePhoneNumberCountryContext for this AvailablePhoneNumberCountryInstance
:rtype: twilio.rest.api.v2010.account.available_phone_n... | Below is the the instruction that describes the task:
### Input:
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AvailablePhoneNumberCountryContext for this AvailablePhoneNumberCountryIns... |
def copy(self, remote_path_from, remote_path_to):
"""Copies resource from one place to another on WebDAV server.
More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_COPY
:param remote_path_from: the path to resource which will be copied,
:param remote_path_... | Copies resource from one place to another on WebDAV server.
More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_COPY
:param remote_path_from: the path to resource which will be copied,
:param remote_path_to: the path where resource will be copied. | Below is the the instruction that describes the task:
### Input:
Copies resource from one place to another on WebDAV server.
More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_COPY
:param remote_path_from: the path to resource which will be copied,
:param remo... |
def save(self):
""" Generate a random username before falling back to parent signup form """
while True:
username = sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
try:
get_user_model().objects.get(username__iexact=username)
except get_user_... | Generate a random username before falling back to parent signup form | Below is the the instruction that describes the task:
### Input:
Generate a random username before falling back to parent signup form
### Response:
def save(self):
""" Generate a random username before falling back to parent signup form """
while True:
username = sha1(str(random.random(... |
def get_and_update_setting(self, name, default=None):
'''Look for a setting in the environment (first priority) and then
the settings file (second). If something is found, the settings
file is updated. The order of operations works as follows:
1. The .sregistry settings file is used as a cache... | Look for a setting in the environment (first priority) and then
the settings file (second). If something is found, the settings
file is updated. The order of operations works as follows:
1. The .sregistry settings file is used as a cache for the variable
2. the environment variable always t... | Below is the the instruction that describes the task:
### Input:
Look for a setting in the environment (first priority) and then
the settings file (second). If something is found, the settings
file is updated. The order of operations works as follows:
1. The .sregistry settings file is used as... |
def zcount(self, key, min=float('-inf'), max=float('inf'),
*, exclude=None):
"""Count the members in a sorted set with scores
within the given values.
:raises TypeError: min or max is not float or int
:raises ValueError: if min greater than max
"""
if not ... | Count the members in a sorted set with scores
within the given values.
:raises TypeError: min or max is not float or int
:raises ValueError: if min greater than max | Below is the the instruction that describes the task:
### Input:
Count the members in a sorted set with scores
within the given values.
:raises TypeError: min or max is not float or int
:raises ValueError: if min greater than max
### Response:
def zcount(self, key, min=float('-inf'), max=f... |
def _model_to_dict(obj):
"""
Convert object model to dict.
Args:
obj: Object model.
Returns:
dict: Converted model.
"""
result = _properties_model_to_dict(obj.properties)
for attribute in ('metadata', 'snapshot'):
try:
... | Convert object model to dict.
Args:
obj: Object model.
Returns:
dict: Converted model. | Below is the the instruction that describes the task:
### Input:
Convert object model to dict.
Args:
obj: Object model.
Returns:
dict: Converted model.
### Response:
def _model_to_dict(obj):
"""
Convert object model to dict.
Args:
obj: ... |
def calc_humidity(temp, dewpoint):
'''
calculates the humidity via the formula from weatherwise.org
return the relative humidity
'''
t = fahrenheit_to_celsius(temp)
td = fahrenheit_to_celsius(dewpoint)
num = 112 - (0.1 * t) + td
denom = 112 + (0.9 * t)
rh = math.pow((num / denom),... | calculates the humidity via the formula from weatherwise.org
return the relative humidity | Below is the the instruction that describes the task:
### Input:
calculates the humidity via the formula from weatherwise.org
return the relative humidity
### Response:
def calc_humidity(temp, dewpoint):
'''
calculates the humidity via the formula from weatherwise.org
return the relative humidity
... |
def voigt_symmetrized(self):
"""
Returns a "voigt"-symmetrized tensor, i. e. a voigt-notation
tensor such that it is invariant wrt permutation of indices
"""
if not (self.rank % 2 == 0 and self.rank >= 2):
raise ValueError("V-symmetrization requires rank even and >= 2... | Returns a "voigt"-symmetrized tensor, i. e. a voigt-notation
tensor such that it is invariant wrt permutation of indices | Below is the the instruction that describes the task:
### Input:
Returns a "voigt"-symmetrized tensor, i. e. a voigt-notation
tensor such that it is invariant wrt permutation of indices
### Response:
def voigt_symmetrized(self):
"""
Returns a "voigt"-symmetrized tensor, i. e. a voigt-notati... |
def umask(self, new_mask):
"""Change the current umask.
Args:
new_mask: (int) The new umask value.
Returns:
The old umask.
Raises:
TypeError: if new_mask is of an invalid type.
"""
if not is_int_type(new_mask):
raise Type... | Change the current umask.
Args:
new_mask: (int) The new umask value.
Returns:
The old umask.
Raises:
TypeError: if new_mask is of an invalid type. | Below is the the instruction that describes the task:
### Input:
Change the current umask.
Args:
new_mask: (int) The new umask value.
Returns:
The old umask.
Raises:
TypeError: if new_mask is of an invalid type.
### Response:
def umask(self, new_mask):... |
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course = self.course_factory.get_course(courseid)
username = self.user_manager.session_username()
error = False
change = False
msg = ""
data = web.input()
if self.user_... | GET request | Below is the the instruction that describes the task:
### Input:
GET request
### Response:
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course = self.course_factory.get_course(courseid)
username = self.user_manager.session_username()
error ... |
def _learnOnNewSegments(connections, rng, newSegmentCells, growthCandidates,
initialPermanence, sampleSize, maxSynapsesPerSegment):
"""
Create new segments, and grow synapses on them.
@param connections (SparseMatrixConnections)
@param rng (Random)
@param newSegmentCells (... | Create new segments, and grow synapses on them.
@param connections (SparseMatrixConnections)
@param rng (Random)
@param newSegmentCells (numpy array)
@param growthCandidates (numpy array) | Below is the the instruction that describes the task:
### Input:
Create new segments, and grow synapses on them.
@param connections (SparseMatrixConnections)
@param rng (Random)
@param newSegmentCells (numpy array)
@param growthCandidates (numpy array)
### Response:
def _learnOnNewSegments(connect... |
def plot_color_map_bars(values, vmin=None, vmax=None, color_map=None,
axis=None, **kwargs):
'''
Plot bar for each value in `values`, colored based on values mapped onto
the specified color map.
Args
----
values (pandas.Series) : Numeric values to plot one bar per va... | Plot bar for each value in `values`, colored based on values mapped onto
the specified color map.
Args
----
values (pandas.Series) : Numeric values to plot one bar per value.
axis : A matplotlib axis. If `None`, an axis is created.
vmin : Minimum value to clip values at.
v... | Below is the the instruction that describes the task:
### Input:
Plot bar for each value in `values`, colored based on values mapped onto
the specified color map.
Args
----
values (pandas.Series) : Numeric values to plot one bar per value.
axis : A matplotlib axis. If `None`, an axis ... |
def disaggregate_temperature(data_daily,
method='sine_min_max',
min_max_time='fix',
mod_nighttime=False,
max_delta=None,
mean_course=None,
sun_tim... | The disaggregation function for temperature
Parameters
----
data_daily : daily data
method : method to disaggregate
min_max_time: "fix" - min/max temperature at fixed times 7h/14h,
"sun_loc" - min/max calculated by sunrise/sunnoon + 2h,
... | Below is the the instruction that describes the task:
### Input:
The disaggregation function for temperature
Parameters
----
data_daily : daily data
method : method to disaggregate
min_max_time: "fix" - min/max temperature at fixed times 7h/14h,
"sun_loc"... |
def purview(repertoire):
"""The purview of the repertoire.
Args:
repertoire (np.ndarray): A repertoire
Returns:
tuple[int]: The purview that the repertoire was computed over.
"""
if repertoire is None:
return None
return tuple(i for i, dim in enumerate(repertoire.shape... | The purview of the repertoire.
Args:
repertoire (np.ndarray): A repertoire
Returns:
tuple[int]: The purview that the repertoire was computed over. | Below is the the instruction that describes the task:
### Input:
The purview of the repertoire.
Args:
repertoire (np.ndarray): A repertoire
Returns:
tuple[int]: The purview that the repertoire was computed over.
### Response:
def purview(repertoire):
"""The purview of the repertoire.
... |
def get_preferred(self, addr_1, addr_2):
'''Return the preferred address.'''
if addr_1 > addr_2:
addr_1, addr_2 = addr_2, addr_1
return self._cache.get((addr_1, addr_2)) | Return the preferred address. | Below is the the instruction that describes the task:
### Input:
Return the preferred address.
### Response:
def get_preferred(self, addr_1, addr_2):
'''Return the preferred address.'''
if addr_1 > addr_2:
addr_1, addr_2 = addr_2, addr_1
return self._cache.get((addr_1, addr_2)) |
def _colorize(self, msg, color=None, encode=False):
"""
Colorize a string.
"""
# Valid colors
colors = {
'red': '31',
'green': '32',
'yellow': '33'
}
# No color specified or unsupported color
if not... | Colorize a string. | Below is the the instruction that describes the task:
### Input:
Colorize a string.
### Response:
def _colorize(self, msg, color=None, encode=False):
"""
Colorize a string.
"""
# Valid colors
colors = {
'red': '31',
'green': '32',
... |
def add(data_dic):
'''
Insert new record.
'''
uid = data_dic['uid']
TabLog.create(
uid=uid,
current_url=data_dic['url'],
refer_url=data_dic['refer'],
user_id=data_dic['user_id'],
time_create=data_dic['timein'],
... | Insert new record. | Below is the the instruction that describes the task:
### Input:
Insert new record.
### Response:
def add(data_dic):
'''
Insert new record.
'''
uid = data_dic['uid']
TabLog.create(
uid=uid,
current_url=data_dic['url'],
refer_url=data_dic['... |
def ensure_crops(self, *required_crops):
"""
Make sure a crop exists for each crop in required_crops.
Existing crops will not be changed.
If settings.ASSET_CELERY is specified then
the task will be run async
"""
if self._can_crop():
if settings.CELERY... | Make sure a crop exists for each crop in required_crops.
Existing crops will not be changed.
If settings.ASSET_CELERY is specified then
the task will be run async | Below is the the instruction that describes the task:
### Input:
Make sure a crop exists for each crop in required_crops.
Existing crops will not be changed.
If settings.ASSET_CELERY is specified then
the task will be run async
### Response:
def ensure_crops(self, *required_crops):
... |
def get_probability_grammar(self):
"""
A method that returns probability grammar
"""
# Creating valid word expression for probability, it is of the format
# wor1 | var2 , var3 or var1 var2 var3 or simply var
word_expr = Word(alphanums + '-' + '_') + Suppress(Optional("|")... | A method that returns probability grammar | Below is the the instruction that describes the task:
### Input:
A method that returns probability grammar
### Response:
def get_probability_grammar(self):
"""
A method that returns probability grammar
"""
# Creating valid word expression for probability, it is of the format
... |
def _compute_magnitude_term(self, C, dc1, mag):
"""
Computes the magnitude scaling term given by equation (2)
"""
base = C['theta1'] + (self.CONSTS['theta4'] * dc1)
dmag = self.CONSTS["C1"] + dc1
if mag > dmag:
f_mag = (self.CONSTS['theta5'] * (mag - dmag)) +\... | Computes the magnitude scaling term given by equation (2) | Below is the the instruction that describes the task:
### Input:
Computes the magnitude scaling term given by equation (2)
### Response:
def _compute_magnitude_term(self, C, dc1, mag):
"""
Computes the magnitude scaling term given by equation (2)
"""
base = C['theta1'] + (self.CONST... |
def compare_hives(fs0, fs1):
"""Compares all the windows registry hive files
returning those which differ.
"""
registries = []
for path in chain(registries_path(fs0.fsroot), user_registries(fs0, fs1)):
if fs0.checksum(path) != fs1.checksum(path):
registries.append(path)
re... | Compares all the windows registry hive files
returning those which differ. | Below is the the instruction that describes the task:
### Input:
Compares all the windows registry hive files
returning those which differ.
### Response:
def compare_hives(fs0, fs1):
"""Compares all the windows registry hive files
returning those which differ.
"""
registries = []
for path... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.