code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def uninitialize_ui(self):
"""
Uninitializes the Component ui.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Uninitializing '{0}' Component ui.".format(self.__class__.__name__))
self.__remove_actions()
# Signals / Slots.
self.Port_s... | Uninitializes the Component ui.
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Uninitializes the Component ui.
:return: Method success.
:rtype: bool
### Response:
def uninitialize_ui(self):
"""
Uninitializes the Component ui.
:return: Method success.
:rtype: bool
"""
... |
def compiled_quil(self):
"""
If the Quil program associated with the Job was compiled (e.g., to translate it to the
QPU's natural gateset) return this compiled program.
:rtype: Optional[Program]
"""
prog = self._raw.get("program", {}).get("compiled-quil", None)
i... | If the Quil program associated with the Job was compiled (e.g., to translate it to the
QPU's natural gateset) return this compiled program.
:rtype: Optional[Program] | Below is the the instruction that describes the task:
### Input:
If the Quil program associated with the Job was compiled (e.g., to translate it to the
QPU's natural gateset) return this compiled program.
:rtype: Optional[Program]
### Response:
def compiled_quil(self):
"""
If the Q... |
def list_to_str(list, separator=','):
"""
>>> list = [0, 0, 7]
>>> list_to_str(list)
'0,0,7'
"""
list = [str(x) for x in list]
return separator.join(list) | >>> list = [0, 0, 7]
>>> list_to_str(list)
'0,0,7' | Below is the the instruction that describes the task:
### Input:
>>> list = [0, 0, 7]
>>> list_to_str(list)
'0,0,7'
### Response:
def list_to_str(list, separator=','):
"""
>>> list = [0, 0, 7]
>>> list_to_str(list)
'0,0,7'
"""
list = [str(x) for x in list]
return separator.join(... |
def get_context_data(self, **kwargs):
"""
Add query in context.
"""
context = super(BaseEntryChannel, self).get_context_data(**kwargs)
context.update({'query': self.query})
return context | Add query in context. | Below is the the instruction that describes the task:
### Input:
Add query in context.
### Response:
def get_context_data(self, **kwargs):
"""
Add query in context.
"""
context = super(BaseEntryChannel, self).get_context_data(**kwargs)
context.update({'query': self.query})
... |
def gradient_plots(self, analytes=None, win=15, samples=None, ranges=False,
focus=None, outdir=None,
figsize=[10, 4], subset='All_Analyses'):
"""
Plot analyte gradients as a function of time.
Parameters
----------
analytes : optional... | Plot analyte gradients as a function of time.
Parameters
----------
analytes : optional, array_like or str
The analyte(s) to plot. Defaults to all analytes.
samples: optional, array_like or str
The sample(s) to plot. Defaults to all samples.
ranges : bool... | Below is the the instruction that describes the task:
### Input:
Plot analyte gradients as a function of time.
Parameters
----------
analytes : optional, array_like or str
The analyte(s) to plot. Defaults to all analytes.
samples: optional, array_like or str
... |
def _train_multi_device(symbol, ctx, arg_names, param_names, aux_names,
arg_params, aux_params,
begin_epoch, end_epoch, epoch_size, optimizer,
kvstore, update_on_kvstore,
train_data, eval_data=None, eval_metric=None,
... | Internal training function on multiple devices.
This function will also work for single device as well.
Parameters
----------
symbol : Symbol
The network configuration.
ctx : list of Context
The training devices.
arg_names: list of str
Name of all arguments of the networ... | Below is the the instruction that describes the task:
### Input:
Internal training function on multiple devices.
This function will also work for single device as well.
Parameters
----------
symbol : Symbol
The network configuration.
ctx : list of Context
The training devices.
... |
def getDocPath(fn, root=None):
'''
Helper for getting a documentation data file paths.
Args:
fn (str): Name of the file to retrieve the full path for.
root (str): Optional root path to look for a docdata in.
Notes:
Defaults to looking for the ``docdata`` directory in the curren... | Helper for getting a documentation data file paths.
Args:
fn (str): Name of the file to retrieve the full path for.
root (str): Optional root path to look for a docdata in.
Notes:
Defaults to looking for the ``docdata`` directory in the current
working directory. This behavior ... | Below is the the instruction that describes the task:
### Input:
Helper for getting a documentation data file paths.
Args:
fn (str): Name of the file to retrieve the full path for.
root (str): Optional root path to look for a docdata in.
Notes:
Defaults to looking for the ``docdata... |
def uav_status_send(self, target, latitude, longitude, altitude, speed, course, force_mavlink1=False):
'''
Transmits the actual status values UAV in flight
target : The ID system reporting the action (uint8_t)
latitude ... | Transmits the actual status values UAV in flight
target : The ID system reporting the action (uint8_t)
latitude : Latitude UAV (float)
longitude : Longitude UAV (float)
altitude : Altitu... | Below is the the instruction that describes the task:
### Input:
Transmits the actual status values UAV in flight
target : The ID system reporting the action (uint8_t)
latitude : Latitude UAV (float)
longitude : Lon... |
async def copy_to_table(self, table_name, *, source,
columns=None, schema_name=None, timeout=None,
format=None, oids=None, freeze=None,
delimiter=None, null=None, header=None,
quote=None, escape=None, force_q... | Copy data to the specified table.
:param str table_name:
The name of the table to copy data to.
:param source:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <python:file-like object>`, or
an :term:`asynchronous iterab... | Below is the the instruction that describes the task:
### Input:
Copy data to the specified table.
:param str table_name:
The name of the table to copy data to.
:param source:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <py... |
def tryDynMod(name):
'''
Dynamically import a python module or exception.
'''
try:
return importlib.import_module(name)
except ModuleNotFoundError:
raise s_exc.NoSuchDyn(name=name) | Dynamically import a python module or exception. | Below is the the instruction that describes the task:
### Input:
Dynamically import a python module or exception.
### Response:
def tryDynMod(name):
'''
Dynamically import a python module or exception.
'''
try:
return importlib.import_module(name)
except ModuleNotFoundError:
rai... |
def add_rerandomize(self, rerandomize):
"""stub"""
if not self.my_osid_object_form._is_valid_string(
rerandomize, self.get_rerandomize_metadata()):
raise InvalidArgument('rerandomize')
self.my_osid_object_form._my_map['rerandomize'] = rerandomize | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def add_rerandomize(self, rerandomize):
"""stub"""
if not self.my_osid_object_form._is_valid_string(
rerandomize, self.get_rerandomize_metadata()):
raise InvalidArgument('rerandomize')
... |
def flightmode_colour(self, flightmode):
'''return colour to be used for rendering a flight mode background'''
if flightmode not in self.flightmode_colourmap:
self.flightmode_colourmap[flightmode] = self.next_flightmode_colour()
return self.flightmode_colourmap[flightmode] | return colour to be used for rendering a flight mode background | Below is the the instruction that describes the task:
### Input:
return colour to be used for rendering a flight mode background
### Response:
def flightmode_colour(self, flightmode):
'''return colour to be used for rendering a flight mode background'''
if flightmode not in self.flightmode_colourma... |
def save(self):
"""
Saves the snapshot based on the current region.
"""
# close down the snapshot widget
if self.hideWindow():
self.hideWindow().hide()
self.hide()
QApplication.processEvents()
time.sleep(1)
... | Saves the snapshot based on the current region. | Below is the the instruction that describes the task:
### Input:
Saves the snapshot based on the current region.
### Response:
def save(self):
"""
Saves the snapshot based on the current region.
"""
# close down the snapshot widget
if self.hideWindow():
sel... |
def _reflex_rule_process(self, wf_action):
"""This function does all the reflex rule process.
:param wf_action: is a string containing the workflow action triggered
"""
# Check out if the analysis has any reflex rule bound to it.
# First we have get the analysis' method because t... | This function does all the reflex rule process.
:param wf_action: is a string containing the workflow action triggered | Below is the the instruction that describes the task:
### Input:
This function does all the reflex rule process.
:param wf_action: is a string containing the workflow action triggered
### Response:
def _reflex_rule_process(self, wf_action):
"""This function does all the reflex rule process.
... |
def post_events_service(request):
"""Respond to inbound webhook JSON HTTP POST from Webex Teams."""
# Get the POST data sent from Webex Teams
json_data = request.json
log.info("\n")
log.info("WEBHOOK POST RECEIVED:")
log.info(json_data)
log.info("\n")
# Create a Webhook object from the... | Respond to inbound webhook JSON HTTP POST from Webex Teams. | Below is the the instruction that describes the task:
### Input:
Respond to inbound webhook JSON HTTP POST from Webex Teams.
### Response:
def post_events_service(request):
"""Respond to inbound webhook JSON HTTP POST from Webex Teams."""
# Get the POST data sent from Webex Teams
json_data = request.j... |
def HEAD(self, rest_path_list, **kwargs):
"""Send a HEAD request. See requests.sessions.request for optional parameters.
:returns: Response object
"""
kwargs.setdefault("allow_redirects", False)
return self._request("HEAD", rest_path_list, **kwargs) | Send a HEAD request. See requests.sessions.request for optional parameters.
:returns: Response object | Below is the the instruction that describes the task:
### Input:
Send a HEAD request. See requests.sessions.request for optional parameters.
:returns: Response object
### Response:
def HEAD(self, rest_path_list, **kwargs):
"""Send a HEAD request. See requests.sessions.request for optional paramete... |
def _init_colors(self):
"""Init the Curses color layout."""
# Set curses options
try:
if hasattr(curses, 'start_color'):
curses.start_color()
if hasattr(curses, 'use_default_colors'):
curses.use_default_colors()
except Exception as... | Init the Curses color layout. | Below is the the instruction that describes the task:
### Input:
Init the Curses color layout.
### Response:
def _init_colors(self):
"""Init the Curses color layout."""
# Set curses options
try:
if hasattr(curses, 'start_color'):
curses.start_color()
... |
def get_default_section(self, file_name):
"""Returns first non-DEFAULT section; falls back to DEFAULT."""
if not os.path.isfile(file_name):
return 'DEFAULT'
parser = self.make_parser()
with open(file_name) as fp:
parser.read_file(fp)
sections = parser.sect... | Returns first non-DEFAULT section; falls back to DEFAULT. | Below is the the instruction that describes the task:
### Input:
Returns first non-DEFAULT section; falls back to DEFAULT.
### Response:
def get_default_section(self, file_name):
"""Returns first non-DEFAULT section; falls back to DEFAULT."""
if not os.path.isfile(file_name):
return 'DE... |
def str_from_text(text):
"""
Return content of a free form text block as a string.
"""
REGEX = re.compile('<text>((.|\n)+)</text>', re.UNICODE)
match = REGEX.match(text)
if match:
return match.group(1)
else:
return None | Return content of a free form text block as a string. | Below is the the instruction that describes the task:
### Input:
Return content of a free form text block as a string.
### Response:
def str_from_text(text):
"""
Return content of a free form text block as a string.
"""
REGEX = re.compile('<text>((.|\n)+)</text>', re.UNICODE)
match = REGEX.matc... |
def sync(remote='origin', branch='master'):
"""git pull and push commit"""
pull(branch, remote)
push(branch, remote)
print(cyan("Git Synced!")) | git pull and push commit | Below is the the instruction that describes the task:
### Input:
git pull and push commit
### Response:
def sync(remote='origin', branch='master'):
"""git pull and push commit"""
pull(branch, remote)
push(branch, remote)
print(cyan("Git Synced!")) |
def parse_resource_type(self, response):
'''
parse resource type from self.http_request()
Note: uses isinstance() as plugins may extend these base LDP resource type.
Args:
response (requests.models.Response): response object
Returns:
[NonRDFSource, BasicContainer, DirectContainer, IndirectContainer]... | parse resource type from self.http_request()
Note: uses isinstance() as plugins may extend these base LDP resource type.
Args:
response (requests.models.Response): response object
Returns:
[NonRDFSource, BasicContainer, DirectContainer, IndirectContainer] | Below is the the instruction that describes the task:
### Input:
parse resource type from self.http_request()
Note: uses isinstance() as plugins may extend these base LDP resource type.
Args:
response (requests.models.Response): response object
Returns:
[NonRDFSource, BasicContainer, DirectContainer,... |
def delay_for(
self,
wait: typing.Union[int, float],
identifier: typing.Any,
) -> bool:
"""Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
the number ... | Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
the number of seconds that must pass before the callback
becomes available for execution. All given values must be
pos... | Below is the the instruction that describes the task:
### Input:
Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
the number of seconds that must pass before the callback
becomes ... |
def activate(self, timeout=None, **options):
"""Activate DEP communication as a target."""
if timeout is None:
timeout = 1.0
gbt = options.get('gbt', '')[0:47]
lrt = min(max(0, options.get('lrt', 3)), 3)
rwt = min(max(0, options.get('rwt', 8)), 14)
pp = (lrt... | Activate DEP communication as a target. | Below is the the instruction that describes the task:
### Input:
Activate DEP communication as a target.
### Response:
def activate(self, timeout=None, **options):
"""Activate DEP communication as a target."""
if timeout is None:
timeout = 1.0
gbt = options.get('gbt', '')[0:47]... |
def set_remote_addr(self, dst_mac, dst_ip):
"""
Configure remote ethernet and IP addresses.
"""
self.dst_mac = dst_mac
self.dst_ip = dst_ip
if not (dst_mac == "FF:FF:FF:FF:FF:FF" or dst_ip == "255.255.255.255"):
self._remote_addr_config = True
LOG.in... | Configure remote ethernet and IP addresses. | Below is the the instruction that describes the task:
### Input:
Configure remote ethernet and IP addresses.
### Response:
def set_remote_addr(self, dst_mac, dst_ip):
"""
Configure remote ethernet and IP addresses.
"""
self.dst_mac = dst_mac
self.dst_ip = dst_ip
if ... |
def default_value(fieldname, datatype):
"""
Return the default value for a column.
If the column name (e.g. *i-wf*) is defined to have an idiosyncratic
value, that value is returned. Otherwise the default value for the
column's datatype is returned.
Args:
fieldname: the column name (e.... | Return the default value for a column.
If the column name (e.g. *i-wf*) is defined to have an idiosyncratic
value, that value is returned. Otherwise the default value for the
column's datatype is returned.
Args:
fieldname: the column name (e.g. `i-wf`)
datatype: the datatype of the col... | Below is the the instruction that describes the task:
### Input:
Return the default value for a column.
If the column name (e.g. *i-wf*) is defined to have an idiosyncratic
value, that value is returned. Otherwise the default value for the
column's datatype is returned.
Args:
fieldname: th... |
def end_of_line(event):
" Move to the end of the line. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_end_of_line_position() | Move to the end of the line. | Below is the the instruction that describes the task:
### Input:
Move to the end of the line.
### Response:
def end_of_line(event):
" Move to the end of the line. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_end_of_line_position() |
def nvrtcGetErrorString(self, code):
"""
Returns a text identifier for the given NVRTC status code.
"""
code_int = c_int(code)
res = self._lib.nvrtcGetErrorString(code_int)
return res.decode('utf-8') | Returns a text identifier for the given NVRTC status code. | Below is the the instruction that describes the task:
### Input:
Returns a text identifier for the given NVRTC status code.
### Response:
def nvrtcGetErrorString(self, code):
"""
Returns a text identifier for the given NVRTC status code.
"""
code_int = c_int(code)
res = self... |
def _ParsePerformanceOptions(self, options):
"""Parses the performance options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
self._buffer_size = getattr(options, 'buffer_size', 0)
if self._buffer_size:
# ... | Parses the performance options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid. | Below is the the instruction that describes the task:
### Input:
Parses the performance options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
### Response:
def _ParsePerformanceOptions(self, options):
"""Parses the perfor... |
def parse_metadata(self):
"""Parse the INDEX_JSON file and reorganize it as a dictionary of lists."""
all_models = defaultdict(list)
with open(self.metadata_index_json) as f:
loaded = json.load(f)
for m in loaded['index']:
all_models[m['uniprot_ac']].append(m)
... | Parse the INDEX_JSON file and reorganize it as a dictionary of lists. | Below is the the instruction that describes the task:
### Input:
Parse the INDEX_JSON file and reorganize it as a dictionary of lists.
### Response:
def parse_metadata(self):
"""Parse the INDEX_JSON file and reorganize it as a dictionary of lists."""
all_models = defaultdict(list)
with op... |
def roberts(image, mask=None):
'''Find edges using the Roberts algorithm
image - the image to process
mask - mask of relevant points
The algorithm returns the magnitude of the output of the two Roberts
convolution kernels.
The following is the canonical citation for the algorithm:
L. Rob... | Find edges using the Roberts algorithm
image - the image to process
mask - mask of relevant points
The algorithm returns the magnitude of the output of the two Roberts
convolution kernels.
The following is the canonical citation for the algorithm:
L. Roberts Machine Perception of 3-D Solids,... | Below is the the instruction that describes the task:
### Input:
Find edges using the Roberts algorithm
image - the image to process
mask - mask of relevant points
The algorithm returns the magnitude of the output of the two Roberts
convolution kernels.
The following is the canonical citatio... |
def GetCookies(self):
"""
Grabs the cookies form your Office Sharepoint site
and uses it as Authentication for the rest of the calls
"""
sectoken = self.GetSecurityToken(self.Username, self.Password)
url = self.share_point_site+ '/_forms/default.aspx?wa=wsignin1.0'
... | Grabs the cookies form your Office Sharepoint site
and uses it as Authentication for the rest of the calls | Below is the the instruction that describes the task:
### Input:
Grabs the cookies form your Office Sharepoint site
and uses it as Authentication for the rest of the calls
### Response:
def GetCookies(self):
"""
Grabs the cookies form your Office Sharepoint site
and uses it as Authe... |
def fit(self):
"""
Fits the model with random restarts.
:return:
"""
self.model.optimize_restarts(num_restarts=self.num_restarts, verbose=False) | Fits the model with random restarts.
:return: | Below is the the instruction that describes the task:
### Input:
Fits the model with random restarts.
:return:
### Response:
def fit(self):
"""
Fits the model with random restarts.
:return:
"""
self.model.optimize_restarts(num_restarts=self.num_restarts, verbose=Fals... |
def getCall(self, n): #pylint: disable=invalid-name
"""
Args:
n: integer (index of function call)
Return:
SpyCall object (or None if the index is not valid)
"""
call_list = super(SinonSpy, self)._get_wrapper().call_list
if n >= 0 and n < len(call_l... | Args:
n: integer (index of function call)
Return:
SpyCall object (or None if the index is not valid) | Below is the the instruction that describes the task:
### Input:
Args:
n: integer (index of function call)
Return:
SpyCall object (or None if the index is not valid)
### Response:
def getCall(self, n): #pylint: disable=invalid-name
"""
Args:
n: integer (i... |
def adjusted_rand_score(self, reference_clusters):
"""
Calculates the adjusted rand score w.r.t. the reference clusters (explicit evaluation)
:param reference_clusters: Clusters that are to be used as reference
:return: returns the value of the adjusted rand score
"""
re... | Calculates the adjusted rand score w.r.t. the reference clusters (explicit evaluation)
:param reference_clusters: Clusters that are to be used as reference
:return: returns the value of the adjusted rand score | Below is the the instruction that describes the task:
### Input:
Calculates the adjusted rand score w.r.t. the reference clusters (explicit evaluation)
:param reference_clusters: Clusters that are to be used as reference
:return: returns the value of the adjusted rand score
### Response:
def adjus... |
def get_all_elbs(region=None, key=None, keyid=None, profile=None):
'''
Return all load balancers associated with an account
CLI example:
.. code-block:: bash
salt myminion boto_elb.get_all_elbs region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)... | Return all load balancers associated with an account
CLI example:
.. code-block:: bash
salt myminion boto_elb.get_all_elbs region=us-east-1 | Below is the the instruction that describes the task:
### Input:
Return all load balancers associated with an account
CLI example:
.. code-block:: bash
salt myminion boto_elb.get_all_elbs region=us-east-1
### Response:
def get_all_elbs(region=None, key=None, keyid=None, profile=None):
'''
... |
def vectorize_inhibit(audio: np.ndarray) -> np.ndarray:
"""
Returns an array of inputs generated from the
wake word audio that shouldn't cause an activation
"""
def samp(x):
return int(pr.sample_rate * x)
inputs = []
for offset in range(samp(inhibit_t), samp(inhibit_dist_t), samp(i... | Returns an array of inputs generated from the
wake word audio that shouldn't cause an activation | Below is the the instruction that describes the task:
### Input:
Returns an array of inputs generated from the
wake word audio that shouldn't cause an activation
### Response:
def vectorize_inhibit(audio: np.ndarray) -> np.ndarray:
"""
Returns an array of inputs generated from the
wake word audio t... |
def fix(self):
"""Runs fix_file on each modified file.
- Prints progress and diff depending on options.
- Returns True if there were any changes
"""
from pep8radius.diff import print_diff, udiff_lines_fixed
n = len(self.filenames_diff)
_maybe_print('Applying au... | Runs fix_file on each modified file.
- Prints progress and diff depending on options.
- Returns True if there were any changes | Below is the the instruction that describes the task:
### Input:
Runs fix_file on each modified file.
- Prints progress and diff depending on options.
- Returns True if there were any changes
### Response:
def fix(self):
"""Runs fix_file on each modified file.
- Prints progress an... |
def reshape(self, data_shapes, label_shapes=None):
"""Reshapes both modules for new input shapes.
Parameters
----------
data_shapes : list of (str, tuple)
Typically is ``data_iter.provide_data``.
label_shapes : list of (str, tuple)
Typically is ``data_ite... | Reshapes both modules for new input shapes.
Parameters
----------
data_shapes : list of (str, tuple)
Typically is ``data_iter.provide_data``.
label_shapes : list of (str, tuple)
Typically is ``data_iter.provide_label``. | Below is the the instruction that describes the task:
### Input:
Reshapes both modules for new input shapes.
Parameters
----------
data_shapes : list of (str, tuple)
Typically is ``data_iter.provide_data``.
label_shapes : list of (str, tuple)
Typically is ``d... |
def clean_len(self, line):
''' Calculate wisible length of string '''
if isinstance(line, basestring):
return len(self.screen.markup.clean_markup(line))
elif isinstance(line, tuple) or isinstance(line, list):
markups = self.screen.markup.get_markup_vars()
le... | Calculate wisible length of string | Below is the the instruction that describes the task:
### Input:
Calculate wisible length of string
### Response:
def clean_len(self, line):
''' Calculate wisible length of string '''
if isinstance(line, basestring):
return len(self.screen.markup.clean_markup(line))
elif isins... |
def trace(self, data, callback=None):
"""Queue data for tracing
Args:
data (bytearray, string): Unstructured data to trace to any
connected client.
callback (callable): An optional callback that will be called with
a bool value of True when this d... | Queue data for tracing
Args:
data (bytearray, string): Unstructured data to trace to any
connected client.
callback (callable): An optional callback that will be called with
a bool value of True when this data actually gets traced.
If the ... | Below is the the instruction that describes the task:
### Input:
Queue data for tracing
Args:
data (bytearray, string): Unstructured data to trace to any
connected client.
callback (callable): An optional callback that will be called with
a bool value... |
def get_entity_by_regid(self, regid):
"""
Returns a restclients.Entity object for the given regid. If the
regid isn't found, or if there is an error communicating with the PWS,
a DataFailureException will be thrown.
"""
if not self.valid_uwregid(regid):
raise... | Returns a restclients.Entity object for the given regid. If the
regid isn't found, or if there is an error communicating with the PWS,
a DataFailureException will be thrown. | Below is the the instruction that describes the task:
### Input:
Returns a restclients.Entity object for the given regid. If the
regid isn't found, or if there is an error communicating with the PWS,
a DataFailureException will be thrown.
### Response:
def get_entity_by_regid(self, regid):
... |
def encrypt_report(self, device_id, root, data, **kwargs):
"""Encrypt a buffer of report data on behalf of a device.
Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
data (... | Encrypt a buffer of report data on behalf of a device.
Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
data (bytearray): The data that we should encrypt.
**kwargs: The... | Below is the the instruction that describes the task:
### Input:
Encrypt a buffer of report data on behalf of a device.
Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
data (b... |
def permitted_actions(self, user, obj=None):
"""Determine list of permitted actions for an object or object
pattern.
:param user: The user to test.
:type user: ``User``
:param obj: A function mapping from action names to object
paths to test.
:type ob... | Determine list of permitted actions for an object or object
pattern.
:param user: The user to test.
:type user: ``User``
:param obj: A function mapping from action names to object
paths to test.
:type obj: callable
:returns: ``list(tutelary.engine.Act... | Below is the the instruction that describes the task:
### Input:
Determine list of permitted actions for an object or object
pattern.
:param user: The user to test.
:type user: ``User``
:param obj: A function mapping from action names to object
paths to test.
... |
def magspec(frames, NFFT):
"""Compute the magnitude spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1).
:param frames: the array of frames. Each row is a frame.
:param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded.
:returns: If frame... | Compute the magnitude spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1).
:param frames: the array of frames. Each row is a frame.
:param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded.
:returns: If frames is an NxD matrix, output will be... | Below is the the instruction that describes the task:
### Input:
Compute the magnitude spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1).
:param frames: the array of frames. Each row is a frame.
:param NFFT: the FFT length to use. If NFFT > frame_len, the frames are ... |
def incomplete_bell_poly(n, k, x):
r"""Recursive evaluation of the incomplete Bell polynomial :math:`B_{n, k}(x)`.
Evaluates the incomplete Bell polynomial :math:`B_{n, k}(x_1, x_2, \dots, x_{n-k+1})`,
also known as the partial Bell polynomial or the Bell polynomial of the
second kind. This polynom... | r"""Recursive evaluation of the incomplete Bell polynomial :math:`B_{n, k}(x)`.
Evaluates the incomplete Bell polynomial :math:`B_{n, k}(x_1, x_2, \dots, x_{n-k+1})`,
also known as the partial Bell polynomial or the Bell polynomial of the
second kind. This polynomial is useful in the evaluation of (the... | Below is the the instruction that describes the task:
### Input:
r"""Recursive evaluation of the incomplete Bell polynomial :math:`B_{n, k}(x)`.
Evaluates the incomplete Bell polynomial :math:`B_{n, k}(x_1, x_2, \dots, x_{n-k+1})`,
also known as the partial Bell polynomial or the Bell polynomial of the... |
def basicConfig(level=logging.WARNING, transient_level=logging.NOTSET):
"""Shortcut for setting up transient logging
I am a replica of ``logging.basicConfig`` which installs a
transient logging handler to stderr.
"""
fmt = "%(asctime)s [%(levelname)s] [%(name)s:%(lineno)d] %(message)s"
logging.... | Shortcut for setting up transient logging
I am a replica of ``logging.basicConfig`` which installs a
transient logging handler to stderr. | Below is the the instruction that describes the task:
### Input:
Shortcut for setting up transient logging
I am a replica of ``logging.basicConfig`` which installs a
transient logging handler to stderr.
### Response:
def basicConfig(level=logging.WARNING, transient_level=logging.NOTSET):
"""Shortcut f... |
def deflections_from_grid(self, grid):
"""Compute the summed (y,x) deflection angles of the galaxy's mass profiles using a grid of Cartesian (y,x) \
coordinates.
If the galaxy has no mass profiles, two grid of zeros are returned.
See *profiles.mass_profiles* module for details of how t... | Compute the summed (y,x) deflection angles of the galaxy's mass profiles using a grid of Cartesian (y,x) \
coordinates.
If the galaxy has no mass profiles, two grid of zeros are returned.
See *profiles.mass_profiles* module for details of how this is performed.
Parameters
----... | Below is the the instruction that describes the task:
### Input:
Compute the summed (y,x) deflection angles of the galaxy's mass profiles using a grid of Cartesian (y,x) \
coordinates.
If the galaxy has no mass profiles, two grid of zeros are returned.
See *profiles.mass_profiles* module f... |
def bench_report(results):
"""Print a report for given benchmark results to the console."""
table = Table(names=['function', 'nest', 'nside', 'size',
'time_healpy', 'time_self', 'ratio'],
dtype=['S20', bool, int, int, float, float, float], masked=True)
for row in ... | Print a report for given benchmark results to the console. | Below is the the instruction that describes the task:
### Input:
Print a report for given benchmark results to the console.
### Response:
def bench_report(results):
"""Print a report for given benchmark results to the console."""
table = Table(names=['function', 'nest', 'nside', 'size',
... |
def folderitem(self, obj, item, index):
"""Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by... | Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by
the template
:index: current i... | Below is the the instruction that describes the task:
### Input:
Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the ob... |
def _step(self, row, position, passed):
"""Walk through the knitting pattern by expanding an row."""
if row in passed or not self._row_should_be_placed(row, position):
return
self._place_row(row, position)
passed = [row] + passed
# print("{}{} at\t{} {}".format(" " *... | Walk through the knitting pattern by expanding an row. | Below is the the instruction that describes the task:
### Input:
Walk through the knitting pattern by expanding an row.
### Response:
def _step(self, row, position, passed):
"""Walk through the knitting pattern by expanding an row."""
if row in passed or not self._row_should_be_placed(row, position... |
def run_step(self):
"""Do the file in-out rewrite."""
rewriter = StreamRewriter(self.context.iter_formatted_strings)
super().run_step(rewriter) | Do the file in-out rewrite. | Below is the the instruction that describes the task:
### Input:
Do the file in-out rewrite.
### Response:
def run_step(self):
"""Do the file in-out rewrite."""
rewriter = StreamRewriter(self.context.iter_formatted_strings)
super().run_step(rewriter) |
def delete(self):
"""Remove myself from my :class:`Character`.
For symmetry with :class:`Thing` and :class`Place`.
"""
branch, turn, tick = self.engine._nbtt()
self.engine._edges_cache.store(
self.character.name,
self.origin.name,
self.destin... | Remove myself from my :class:`Character`.
For symmetry with :class:`Thing` and :class`Place`. | Below is the the instruction that describes the task:
### Input:
Remove myself from my :class:`Character`.
For symmetry with :class:`Thing` and :class`Place`.
### Response:
def delete(self):
"""Remove myself from my :class:`Character`.
For symmetry with :class:`Thing` and :class`Place`.
... |
def get_current_value(self):
"""Return current annealing value
# Returns
Value to use in annealing
"""
if self.agent.training:
# Linear annealed: f(x) = ax + b.
a = -float(self.value_max - self.value_min) / float(self.nb_steps)
b = float(s... | Return current annealing value
# Returns
Value to use in annealing | Below is the the instruction that describes the task:
### Input:
Return current annealing value
# Returns
Value to use in annealing
### Response:
def get_current_value(self):
"""Return current annealing value
# Returns
Value to use in annealing
"""
... |
async def get_available_abilities(self, units: Union[List[Unit], Units], ignore_resource_requirements=False) -> List[List[AbilityId]]:
""" Returns available abilities of one or more units. """
# right know only checks cooldown, energy cost, and whether the ability has been researched
return awai... | Returns available abilities of one or more units. | Below is the the instruction that describes the task:
### Input:
Returns available abilities of one or more units.
### Response:
async def get_available_abilities(self, units: Union[List[Unit], Units], ignore_resource_requirements=False) -> List[List[AbilityId]]:
""" Returns available abilities of one or m... |
def expand_by_device(original_parallelism, device_parallelism, data):
"""Opposite of reduce_by_device().
Args:
original_parallelism: a expert_utils.Parallelism object.
device_parallelism: a expert_utils.Parallelism object.
data: a list of tensors with length device_parallelism.n
Returns:
a list ... | Opposite of reduce_by_device().
Args:
original_parallelism: a expert_utils.Parallelism object.
device_parallelism: a expert_utils.Parallelism object.
data: a list of tensors with length device_parallelism.n
Returns:
a list of Tensors with length original_parallelism.n | Below is the the instruction that describes the task:
### Input:
Opposite of reduce_by_device().
Args:
original_parallelism: a expert_utils.Parallelism object.
device_parallelism: a expert_utils.Parallelism object.
data: a list of tensors with length device_parallelism.n
Returns:
a list of Ten... |
def get_code_version_numbers(cp):
"""Will extract the version information from the executables listed in
the executable section of the supplied ConfigParser object.
Returns
--------
dict
A dictionary keyed by the executable name with values giving the
version string for each executa... | Will extract the version information from the executables listed in
the executable section of the supplied ConfigParser object.
Returns
--------
dict
A dictionary keyed by the executable name with values giving the
version string for each executable. | Below is the the instruction that describes the task:
### Input:
Will extract the version information from the executables listed in
the executable section of the supplied ConfigParser object.
Returns
--------
dict
A dictionary keyed by the executable name with values giving the
ver... |
def recipe_compile(backend, kitchen, recipe, variation):
"""
Apply variables to a Recipe
"""
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
if use_kitchen is None:
raise click.ClickException(err_str)
if recipe is None:
recipe = DKRecipeDisk.find_recipe_name()
... | Apply variables to a Recipe | Below is the the instruction that describes the task:
### Input:
Apply variables to a Recipe
### Response:
def recipe_compile(backend, kitchen, recipe, variation):
"""
Apply variables to a Recipe
"""
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
if use_kitchen is None:
r... |
def get_authorization(self, request):
"""
This function extracts the authorization JWT string. It first
looks for specified key in header and then looks
for the same in body part.
Parameters
----------
request: HttpRequest
This is the raw request that... | This function extracts the authorization JWT string. It first
looks for specified key in header and then looks
for the same in body part.
Parameters
----------
request: HttpRequest
This is the raw request that user has sent.
Returns
-------
a... | Below is the the instruction that describes the task:
### Input:
This function extracts the authorization JWT string. It first
looks for specified key in header and then looks
for the same in body part.
Parameters
----------
request: HttpRequest
This is the raw r... |
def movies_upcoming(self, **kwargs):
"""Gets the upcoming movies from the API.
Args:
page_limit (optional): number of movies to show per page, default=16
page (optional): results page number, default=1
country (optional): localized data for selected country, default="us"
... | Gets the upcoming movies from the API.
Args:
page_limit (optional): number of movies to show per page, default=16
page (optional): results page number, default=1
country (optional): localized data for selected country, default="us"
Returns:
A dict respresentatio... | Below is the the instruction that describes the task:
### Input:
Gets the upcoming movies from the API.
Args:
page_limit (optional): number of movies to show per page, default=16
page (optional): results page number, default=1
country (optional): localized data for selected co... |
def set_measurements(test):
"""Test phase that sets a measurement."""
test.measurements.level_none = 0
time.sleep(1)
test.measurements.level_some = 8
time.sleep(1)
test.measurements.level_all = 9
time.sleep(1)
level_all = test.get_measurement('level_all')
assert level_all.value == 9 | Test phase that sets a measurement. | Below is the the instruction that describes the task:
### Input:
Test phase that sets a measurement.
### Response:
def set_measurements(test):
"""Test phase that sets a measurement."""
test.measurements.level_none = 0
time.sleep(1)
test.measurements.level_some = 8
time.sleep(1)
test.measurements.level_... |
def policy_map_class_police_eir(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
po_name_key = ET.SubElement(policy_map, "po-name")
po_name_key.text = k... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def policy_map_class_police_eir(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:b... |
def showAnns(self, anns):
"""
Display the specified annotations.
:param anns (array of object): annotations to display
:return: None
"""
if len(anns) == 0:
return 0
if 'segmentation' in anns[0] or 'keypoints' in anns[0]:
datasetType = 'inst... | Display the specified annotations.
:param anns (array of object): annotations to display
:return: None | Below is the the instruction that describes the task:
### Input:
Display the specified annotations.
:param anns (array of object): annotations to display
:return: None
### Response:
def showAnns(self, anns):
"""
Display the specified annotations.
:param anns (array of object... |
def _clearQuantities(self):
""" Computes the cleared quantities for each offer/bid according
to the dispatched output from the OPF solution.
"""
generators = [g for g in self.case.generators if not g.is_load]
vLoads = [g for g in self.case.generators if g.is_load]
for g ... | Computes the cleared quantities for each offer/bid according
to the dispatched output from the OPF solution. | Below is the the instruction that describes the task:
### Input:
Computes the cleared quantities for each offer/bid according
to the dispatched output from the OPF solution.
### Response:
def _clearQuantities(self):
""" Computes the cleared quantities for each offer/bid according
to the dis... |
def bdp(tickers, flds, **kwargs):
"""
Bloomberg reference data
Args:
tickers: tickers
flds: fields to query
**kwargs: bbg overrides
Returns:
pd.DataFrame
Examples:
>>> bdp('IQ US Equity', 'Crncy', raw=True)
ticker field value
0 IQ... | Bloomberg reference data
Args:
tickers: tickers
flds: fields to query
**kwargs: bbg overrides
Returns:
pd.DataFrame
Examples:
>>> bdp('IQ US Equity', 'Crncy', raw=True)
ticker field value
0 IQ US Equity Crncy USD
>>> bdp('IQ US... | Below is the the instruction that describes the task:
### Input:
Bloomberg reference data
Args:
tickers: tickers
flds: fields to query
**kwargs: bbg overrides
Returns:
pd.DataFrame
Examples:
>>> bdp('IQ US Equity', 'Crncy', raw=True)
ticker fi... |
def factory(arg1, arg2, version=-1, forceviewserveruse=False, windowId=None, uiAutomatorHelper=None):
'''
View factory
@type arg1: ClassType or dict
@type arg2: View instance or AdbClient
'''
if DEBUG_VIEW_FACTORY:
print >> sys.stderr, "View.factory(%s, %s, ... | View factory
@type arg1: ClassType or dict
@type arg2: View instance or AdbClient | Below is the the instruction that describes the task:
### Input:
View factory
@type arg1: ClassType or dict
@type arg2: View instance or AdbClient
### Response:
def factory(arg1, arg2, version=-1, forceviewserveruse=False, windowId=None, uiAutomatorHelper=None):
'''
View factory
... |
def func(self, name: str):
"""return the first func defined named name"""
for f in self.body:
if (hasattr(f, '_ctype')
and isinstance(f._ctype, FuncType)
and f._name == name):
return f | return the first func defined named name | Below is the the instruction that describes the task:
### Input:
return the first func defined named name
### Response:
def func(self, name: str):
"""return the first func defined named name"""
for f in self.body:
if (hasattr(f, '_ctype')
and isinstance(f._ctype, Fun... |
def _from_dict(cls, _dict):
"""Initialize a TrainingQuery object from a json dictionary."""
args = {}
if 'query_id' in _dict:
args['query_id'] = _dict.get('query_id')
if 'natural_language_query' in _dict:
args['natural_language_query'] = _dict.get('natural_languag... | Initialize a TrainingQuery object from a json dictionary. | Below is the the instruction that describes the task:
### Input:
Initialize a TrainingQuery object from a json dictionary.
### Response:
def _from_dict(cls, _dict):
"""Initialize a TrainingQuery object from a json dictionary."""
args = {}
if 'query_id' in _dict:
args['query_id']... |
def add_edge_by_index(self, source_index: int, target_index: int,
weight: float, save_to_cache: bool = True) -> None:
"""
Adds an edge between the nodes with the specified indices to the graph.
Arguments:
source_index (int): The index of the source no... | Adds an edge between the nodes with the specified indices to the graph.
Arguments:
source_index (int): The index of the source node of the edge to add.
target_index (int): The index of the target node of the edge to add.
weight (float): The weight of the edge.
... | Below is the the instruction that describes the task:
### Input:
Adds an edge between the nodes with the specified indices to the graph.
Arguments:
source_index (int): The index of the source node of the edge to add.
target_index (int): The index of the target node of the edge t... |
def get_element_dos(self):
"""
Get element projected Dos.
Returns:
dict of {Element: Dos}
"""
el_dos = {}
for site, atom_dos in self.pdos.items():
el = site.specie
if el not in el_dos:
el_dos[el] = np.array(atom_dos)
... | Get element projected Dos.
Returns:
dict of {Element: Dos} | Below is the the instruction that describes the task:
### Input:
Get element projected Dos.
Returns:
dict of {Element: Dos}
### Response:
def get_element_dos(self):
"""
Get element projected Dos.
Returns:
dict of {Element: Dos}
"""
el_dos =... |
def inspect(package):
"""
Inspect package details
"""
team, owner, pkg = parse_package(package)
store, pkgroot = PackageStore.find_package(team, owner, pkg)
if pkgroot is None:
raise CommandException("Package {package} not found.".format(package=package))
def _print_children(childr... | Inspect package details | Below is the the instruction that describes the task:
### Input:
Inspect package details
### Response:
def inspect(package):
"""
Inspect package details
"""
team, owner, pkg = parse_package(package)
store, pkgroot = PackageStore.find_package(team, owner, pkg)
if pkgroot is None:
ra... |
def run_backup(filename, root_dir, ignore=[], ignore_ext=[], ignore_pattern=[]):
"""The backup utility method.
:param root_dir: the directory you want to backup
:param ignore: file or directory defined in this list will be ignored.
:param ignore_ext: file with extensions defined in this list will be ig... | The backup utility method.
:param root_dir: the directory you want to backup
:param ignore: file or directory defined in this list will be ignored.
:param ignore_ext: file with extensions defined in this list will be ignored.
:param ignore_pattern: any file or directory that contains this pattern
... | Below is the the instruction that describes the task:
### Input:
The backup utility method.
:param root_dir: the directory you want to backup
:param ignore: file or directory defined in this list will be ignored.
:param ignore_ext: file with extensions defined in this list will be ignored.
:param i... |
def list_bucket_analytics_configurations(client=None, **kwargs):
"""
Bucket='string'
"""
result = client.list_bucket_analytics_configurations(**kwargs)
if not result.get("AnalyticsConfigurationList"):
result.update({"AnalyticsConfigurationList": []})
return result | Bucket='string' | Below is the the instruction that describes the task:
### Input:
Bucket='string'
### Response:
def list_bucket_analytics_configurations(client=None, **kwargs):
"""
Bucket='string'
"""
result = client.list_bucket_analytics_configurations(**kwargs)
if not result.get("AnalyticsConfigurationList"):... |
def _validate_resource_dict(cls, logical_id, resource_dict):
"""Validates that the provided resource dict contains the correct Type string, and the required Properties dict.
:param dict resource_dict: the resource dict to validate
:returns: True if the resource dict has the expected format
... | Validates that the provided resource dict contains the correct Type string, and the required Properties dict.
:param dict resource_dict: the resource dict to validate
:returns: True if the resource dict has the expected format
:rtype: bool
:raises InvalidResourceException: if the resour... | Below is the the instruction that describes the task:
### Input:
Validates that the provided resource dict contains the correct Type string, and the required Properties dict.
:param dict resource_dict: the resource dict to validate
:returns: True if the resource dict has the expected format
... |
def destroy_by_name(name, driver):
"""Destroy all nodes matching specified name"""
matches = [node for node in list_nodes(driver) if node.name == name]
if len(matches) == 0:
logger.warn('no node named %s' % name)
return False
else:
return all([node.destroy() for node in matches... | Destroy all nodes matching specified name | Below is the the instruction that describes the task:
### Input:
Destroy all nodes matching specified name
### Response:
def destroy_by_name(name, driver):
"""Destroy all nodes matching specified name"""
matches = [node for node in list_nodes(driver) if node.name == name]
if len(matches) == 0:
... |
def setupitems(self):
"""Lookup available setup items
:returns: catalog brains
"""
query = {
"path": {
"query": api.get_path(self.setup),
"depth": 1,
},
}
items = api.search(query, "portal_catalog")
# filter... | Lookup available setup items
:returns: catalog brains | Below is the the instruction that describes the task:
### Input:
Lookup available setup items
:returns: catalog brains
### Response:
def setupitems(self):
"""Lookup available setup items
:returns: catalog brains
"""
query = {
"path": {
"query": ... |
def get_swagger(self, request):
"""
Generate this document.
"""
api_base = self.parent
paths, definitions = self.parse_operations()
codecs = getattr(self.cenancestor, 'registered_codecs', CODECS) # type: dict
return dict_filter({
'swagger': '2.0',
... | Generate this document. | Below is the the instruction that describes the task:
### Input:
Generate this document.
### Response:
def get_swagger(self, request):
"""
Generate this document.
"""
api_base = self.parent
paths, definitions = self.parse_operations()
codecs = getattr(self.cenancesto... |
def extrude_triangulation(vertices,
faces,
height,
**kwargs):
"""
Turn a 2D triangulation into a watertight Trimesh.
Parameters
----------
vertices : (n, 2) float
2D vertices
faces : (m, 3) int
Triangle in... | Turn a 2D triangulation into a watertight Trimesh.
Parameters
----------
vertices : (n, 2) float
2D vertices
faces : (m, 3) int
Triangle indexes of vertices
height : float
Distance to extrude triangulation
**kwargs:
passed to Trimesh
Returns
---------
mesh... | Below is the the instruction that describes the task:
### Input:
Turn a 2D triangulation into a watertight Trimesh.
Parameters
----------
vertices : (n, 2) float
2D vertices
faces : (m, 3) int
Triangle indexes of vertices
height : float
Distance to extrude triangulation
**... |
def recv(self, maxsize=None):
'''
Receive data from the terminal as a (``stdout``, ``stderr``) tuple. If
any of those is ``None`` we can no longer communicate with the
terminal's child process.
'''
if maxsize is None:
maxsize = 1024
elif maxsize < 1:
... | Receive data from the terminal as a (``stdout``, ``stderr``) tuple. If
any of those is ``None`` we can no longer communicate with the
terminal's child process. | Below is the the instruction that describes the task:
### Input:
Receive data from the terminal as a (``stdout``, ``stderr``) tuple. If
any of those is ``None`` we can no longer communicate with the
terminal's child process.
### Response:
def recv(self, maxsize=None):
'''
Receive da... |
def work_in(dirname=None):
"""
Context manager version of os.chdir. When exited, returns to the working
directory prior to entering.
"""
curdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
requests_cache.configure(expire_after=60 * 10 * 10)
ch... | Context manager version of os.chdir. When exited, returns to the working
directory prior to entering. | Below is the the instruction that describes the task:
### Input:
Context manager version of os.chdir. When exited, returns to the working
directory prior to entering.
### Response:
def work_in(dirname=None):
"""
Context manager version of os.chdir. When exited, returns to the working
directory prio... |
def get_suffix(name):
"""Check if file name have valid suffix for formatting.
if have suffix return it else return False.
"""
a = name.count(".")
if a:
ext = name.split(".")[-1]
if ext in LANGS.keys():
return ext
return False
else:
return False | Check if file name have valid suffix for formatting.
if have suffix return it else return False. | Below is the the instruction that describes the task:
### Input:
Check if file name have valid suffix for formatting.
if have suffix return it else return False.
### Response:
def get_suffix(name):
"""Check if file name have valid suffix for formatting.
if have suffix return it else return False.... |
def _apply_source_provider_dim_updates(cube, source_providers, budget_dims):
"""
Given a list of source_providers, apply the list of
suggested dimension updates given in provider.updated_dimensions()
to the supplied hypercube.
Dimension global_sizes are always updated with the supplied sizes and
... | Given a list of source_providers, apply the list of
suggested dimension updates given in provider.updated_dimensions()
to the supplied hypercube.
Dimension global_sizes are always updated with the supplied sizes and
lower_extent is always set to 0. upper_extent is set to any reductions
(current upp... | Below is the the instruction that describes the task:
### Input:
Given a list of source_providers, apply the list of
suggested dimension updates given in provider.updated_dimensions()
to the supplied hypercube.
Dimension global_sizes are always updated with the supplied sizes and
lower_extent is al... |
def setup_keras_trainer(
trainer, get_model,
input_signature, target_signature,
input, optimizer, loss, metrics):
"""
Args:
trainer (SingleCostTrainer):
get_model (input1, input2, ... -> tf.keras.Model):
A function which takes tensors, builds and returns a Ker... | Args:
trainer (SingleCostTrainer):
get_model (input1, input2, ... -> tf.keras.Model):
A function which takes tensors, builds and returns a Keras model.
It will be part of the tower function.
input (InputSource):
optimizer (tf.train.Optimizer):
loss, metric... | Below is the the instruction that describes the task:
### Input:
Args:
trainer (SingleCostTrainer):
get_model (input1, input2, ... -> tf.keras.Model):
A function which takes tensors, builds and returns a Keras model.
It will be part of the tower function.
input (Input... |
def is_indexed(self, identifier):
""" Returns True if identifier is already indexed. Otherwise returns False. """
query = text("""
SELECT identifier
FROM identifier_index
WHERE identifier = :identifier;
""")
result = self.execute(query, identifier=iden... | Returns True if identifier is already indexed. Otherwise returns False. | Below is the the instruction that describes the task:
### Input:
Returns True if identifier is already indexed. Otherwise returns False.
### Response:
def is_indexed(self, identifier):
""" Returns True if identifier is already indexed. Otherwise returns False. """
query = text("""
SELEC... |
def delete_one(self, query):
"""
Deletes one document from the collection
:param query: dictionary representing the mongo query
:return: DeleteResult
"""
item = self.find_one(query)
result = self.table.remove(where(u'_id') == item[u'_id'])
return DeleteR... | Deletes one document from the collection
:param query: dictionary representing the mongo query
:return: DeleteResult | Below is the the instruction that describes the task:
### Input:
Deletes one document from the collection
:param query: dictionary representing the mongo query
:return: DeleteResult
### Response:
def delete_one(self, query):
"""
Deletes one document from the collection
:pa... |
def project(original_image, perturbed_images, alphas, shape, constraint):
""" Projection onto given l2 / linf balls in a batch. """
alphas_shape = [len(alphas)] + [1] * len(shape)
alphas = alphas.reshape(alphas_shape)
if constraint == 'l2':
projected = (1-alphas) * original_image + alphas * perturbed_images... | Projection onto given l2 / linf balls in a batch. | Below is the the instruction that describes the task:
### Input:
Projection onto given l2 / linf balls in a batch.
### Response:
def project(original_image, perturbed_images, alphas, shape, constraint):
""" Projection onto given l2 / linf balls in a batch. """
alphas_shape = [len(alphas)] + [1] * len(shape)
... |
def dump_uvarint_b_into(n, buffer, offset=0):
"""
Serializes n as variable size integer to the provided buffer.
Buffer has to ha
:param n:
:param buffer:
:param offset:
:return:
"""
shifted = True
while shifted:
shifted = n >> 7
buffer[offset] = (n & 0x7F) | (0x80... | Serializes n as variable size integer to the provided buffer.
Buffer has to ha
:param n:
:param buffer:
:param offset:
:return: | Below is the the instruction that describes the task:
### Input:
Serializes n as variable size integer to the provided buffer.
Buffer has to ha
:param n:
:param buffer:
:param offset:
:return:
### Response:
def dump_uvarint_b_into(n, buffer, offset=0):
"""
Serializes n as variable size ... |
def setPixmapSize(self, size):
"""
Sets the pixmap size for this label.
:param size | <QSize>
"""
self._pixmapSize = size
self.setPixmap(self.action().icon().pixmap(size))
max_size = self.parent().maximumPixmapSize()
... | Sets the pixmap size for this label.
:param size | <QSize> | Below is the the instruction that describes the task:
### Input:
Sets the pixmap size for this label.
:param size | <QSize>
### Response:
def setPixmapSize(self, size):
"""
Sets the pixmap size for this label.
:param size | <QSize>
"""
... |
def make_model(corpus, lemmatize=False, rm_stops=False, size=100, window=10, min_count=5, workers=4, sg=1,
save_path=None):
"""Train W2V model."""
# Simple training, with one large list
t0 = time.time()
sentences_stream = gen_docs(corpus, lemmatize=lemmatize, rm_stops=rm_stops)
# se... | Train W2V model. | Below is the the instruction that describes the task:
### Input:
Train W2V model.
### Response:
def make_model(corpus, lemmatize=False, rm_stops=False, size=100, window=10, min_count=5, workers=4, sg=1,
save_path=None):
"""Train W2V model."""
# Simple training, with one large list
t0 = ... |
def as_raw(self):
"""
Return a representation of this object that can be used with mongoengine Document.objects(__raw__=x)
Example:
>>> stream_id = StreamId(name='test', meta_data=((u'house', u'1'), (u'resident', u'1')))
>>> stream_id.as_raw()
{'stream_id.meta_data': [(u... | Return a representation of this object that can be used with mongoengine Document.objects(__raw__=x)
Example:
>>> stream_id = StreamId(name='test', meta_data=((u'house', u'1'), (u'resident', u'1')))
>>> stream_id.as_raw()
{'stream_id.meta_data': [(u'house', u'1'), (u'resident', u'1')], ... | Below is the the instruction that describes the task:
### Input:
Return a representation of this object that can be used with mongoengine Document.objects(__raw__=x)
Example:
>>> stream_id = StreamId(name='test', meta_data=((u'house', u'1'), (u'resident', u'1')))
>>> stream_id.as_raw()
... |
def stop(self):
"""Return the last day of the period as an Instant instance.
>>> period('year', 2014).stop
Instant((2014, 12, 31))
>>> period('month', 2014).stop
Instant((2014, 12, 31))
>>> period('day', 2014).stop
Instant((2014, 12, 31))
>>> period('yea... | Return the last day of the period as an Instant instance.
>>> period('year', 2014).stop
Instant((2014, 12, 31))
>>> period('month', 2014).stop
Instant((2014, 12, 31))
>>> period('day', 2014).stop
Instant((2014, 12, 31))
>>> period('year', '2012-2-29').stop
... | Below is the the instruction that describes the task:
### Input:
Return the last day of the period as an Instant instance.
>>> period('year', 2014).stop
Instant((2014, 12, 31))
>>> period('month', 2014).stop
Instant((2014, 12, 31))
>>> period('day', 2014).stop
Instan... |
def decrypt(self, pkt, verify=True):
"""
Decrypt (and decapsulate) an IP(v6) packet containing ESP or AH.
@param pkt: the packet to decrypt
@param verify: if False, do not perform the integrity check
@return: the decrypted/decapsulated packet
@raise IPSecIntegrityE... | Decrypt (and decapsulate) an IP(v6) packet containing ESP or AH.
@param pkt: the packet to decrypt
@param verify: if False, do not perform the integrity check
@return: the decrypted/decapsulated packet
@raise IPSecIntegrityError: if the integrity check fails | Below is the the instruction that describes the task:
### Input:
Decrypt (and decapsulate) an IP(v6) packet containing ESP or AH.
@param pkt: the packet to decrypt
@param verify: if False, do not perform the integrity check
@return: the decrypted/decapsulated packet
@raise IPS... |
def _join_date_and_time(dates, times, joiner):
"""Returns a tuple of all date and time format strings joined together by
:joiner:.
:dates: an enumerable of date format strings
:times: an enumerable of time format strings
:joiner: a string to join a date and time format together
"""
return tuple("{}{}{}".... | Returns a tuple of all date and time format strings joined together by
:joiner:.
:dates: an enumerable of date format strings
:times: an enumerable of time format strings
:joiner: a string to join a date and time format together | Below is the the instruction that describes the task:
### Input:
Returns a tuple of all date and time format strings joined together by
:joiner:.
:dates: an enumerable of date format strings
:times: an enumerable of time format strings
:joiner: a string to join a date and time format together
### Response:... |
def start(self):
"""
Starts this VMware VM.
"""
if self.status == "started":
return
if (yield from self.is_running()):
raise VMwareError("The VM is already running in VMware")
ubridge_path = self.ubridge_path
if not ubridge_path or not o... | Starts this VMware VM. | Below is the the instruction that describes the task:
### Input:
Starts this VMware VM.
### Response:
def start(self):
"""
Starts this VMware VM.
"""
if self.status == "started":
return
if (yield from self.is_running()):
raise VMwareError("The VM is... |
def send(self, cmd="", timeout=300, wait_for_string=None, password=False):
"""Send the command to the device and return the output.
Args:
cmd (str): Command string for execution. Defaults to empty string.
timeout (int): Timeout in seconds. Defaults to 300 sec (5 min)
... | Send the command to the device and return the output.
Args:
cmd (str): Command string for execution. Defaults to empty string.
timeout (int): Timeout in seconds. Defaults to 300 sec (5 min)
wait_for_string (str): This is optional string that driver
waits for afte... | Below is the the instruction that describes the task:
### Input:
Send the command to the device and return the output.
Args:
cmd (str): Command string for execution. Defaults to empty string.
timeout (int): Timeout in seconds. Defaults to 300 sec (5 min)
wait_for_string ... |
def migrate_non_shared(vm_, target, ssh=False):
'''
Attempt to execute non-shared storage "all" migration
:param vm_: domain name
:param target: target libvirt host name
:param ssh: True to connect over ssh
CLI Example:
.. code-block:: bash
salt '*' virt.migrate_non_shared <vm na... | Attempt to execute non-shared storage "all" migration
:param vm_: domain name
:param target: target libvirt host name
:param ssh: True to connect over ssh
CLI Example:
.. code-block:: bash
salt '*' virt.migrate_non_shared <vm name> <target hypervisor>
A tunnel data migration can be ... | Below is the the instruction that describes the task:
### Input:
Attempt to execute non-shared storage "all" migration
:param vm_: domain name
:param target: target libvirt host name
:param ssh: True to connect over ssh
CLI Example:
.. code-block:: bash
salt '*' virt.migrate_non_shar... |
def fetch_interfaces(self, interface, way):
"""Get the list of charms that provides or requires this interface.
@param interface The interface for the charm relation.
@param way The type of relation, either "provides" or "requires".
@return List of charms
"""
if not inte... | Get the list of charms that provides or requires this interface.
@param interface The interface for the charm relation.
@param way The type of relation, either "provides" or "requires".
@return List of charms | Below is the the instruction that describes the task:
### Input:
Get the list of charms that provides or requires this interface.
@param interface The interface for the charm relation.
@param way The type of relation, either "provides" or "requires".
@return List of charms
### Response:
de... |
def execute(self, operation, params=()):
""" Execute the query
:param operation: SQL statement
:type operation: str
"""
conn = self._assert_open()
conn._try_activate_cursor(self)
self._execute(operation, params)
# for compatibility with pyodbc
ret... | Execute the query
:param operation: SQL statement
:type operation: str | Below is the the instruction that describes the task:
### Input:
Execute the query
:param operation: SQL statement
:type operation: str
### Response:
def execute(self, operation, params=()):
""" Execute the query
:param operation: SQL statement
:type operation: str
... |
def ip(ip_addr, return_tuple=True):
"""
Function to check if a address is good
Args:
ip_addr: IP address in the following format 192.168.1.1
return_tuple: Set to True it returns a IP, set to False returns True or False
Returns: see return_tuple for return options
"""
regex_ip =... | Function to check if a address is good
Args:
ip_addr: IP address in the following format 192.168.1.1
return_tuple: Set to True it returns a IP, set to False returns True or False
Returns: see return_tuple for return options | Below is the the instruction that describes the task:
### Input:
Function to check if a address is good
Args:
ip_addr: IP address in the following format 192.168.1.1
return_tuple: Set to True it returns a IP, set to False returns True or False
Returns: see return_tuple for return options
##... |
def setup_gage_obs(gage_file,ins_file=None,start_datetime=None,times=None):
"""writes an instruction file for a mt3d-usgs sft output file
Parameters
----------
gage_file : str
the gage output file (ASCII)
ins_file : str
the name of the instruction file to create. If... | writes an instruction file for a mt3d-usgs sft output file
Parameters
----------
gage_file : str
the gage output file (ASCII)
ins_file : str
the name of the instruction file to create. If None, the name
is <gage_file>.processed.ins. Default is None
... | Below is the the instruction that describes the task:
### Input:
writes an instruction file for a mt3d-usgs sft output file
Parameters
----------
gage_file : str
the gage output file (ASCII)
ins_file : str
the name of the instruction file to create. If None, the nam... |
def cut(self):
""" Copy the currently selected text to the clipboard and delete it
if it's inside the input buffer.
"""
self.copy()
if self.can_cut():
self._control.textCursor().removeSelectedText() | Copy the currently selected text to the clipboard and delete it
if it's inside the input buffer. | Below is the the instruction that describes the task:
### Input:
Copy the currently selected text to the clipboard and delete it
if it's inside the input buffer.
### Response:
def cut(self):
""" Copy the currently selected text to the clipboard and delete it
if it's inside the input... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.