code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def handle_update(self, obj, internal_call=False):
"""Handle an incoming ``Data`` object update request.
:param obj: The Channels message object. Command object format:
.. code-block:: none
{
'command': 'update',
'data_id': [id of th... | Handle an incoming ``Data`` object update request.
:param obj: The Channels message object. Command object format:
.. code-block:: none
{
'command': 'update',
'data_id': [id of the :class:`~resolwe.flow.models.Data`
... | Below is the the instruction that describes the task:
### Input:
Handle an incoming ``Data`` object update request.
:param obj: The Channels message object. Command object format:
.. code-block:: none
{
'command': 'update',
'data_id': [i... |
def xsrf_token(self) -> bytes:
"""The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an '_xsrf' cookie
and include the same '_xsrf' value as an argument with all POST
requests. If the two do not match, we reject the form submission
... | The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an '_xsrf' cookie
and include the same '_xsrf' value as an argument with all POST
requests. If the two do not match, we reject the form submission
as a potential forgery.
See h... | Below is the the instruction that describes the task:
### Input:
The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an '_xsrf' cookie
and include the same '_xsrf' value as an argument with all POST
requests. If the two do not match, we reje... |
def get_X_slice(self, rmind):
'''get X with slicing'''
if self.forest.optimize_memory_use:
return self.forest.X[:, rmind][self.subsample]
else:
return self.X[:, rmind] | get X with slicing | Below is the the instruction that describes the task:
### Input:
get X with slicing
### Response:
def get_X_slice(self, rmind):
'''get X with slicing'''
if self.forest.optimize_memory_use:
return self.forest.X[:, rmind][self.subsample]
else:
return self.X[:, rmind] |
def pack_ip_addr(addr):
"""Given an IP address tuple like ('1.2.3.4', 47808) return the six-octet string
useful for a BACnet address."""
addr, port = addr
return socket.inet_aton(addr) + struct.pack('!H', port & _short_mask) | Given an IP address tuple like ('1.2.3.4', 47808) return the six-octet string
useful for a BACnet address. | Below is the the instruction that describes the task:
### Input:
Given an IP address tuple like ('1.2.3.4', 47808) return the six-octet string
useful for a BACnet address.
### Response:
def pack_ip_addr(addr):
"""Given an IP address tuple like ('1.2.3.4', 47808) return the six-octet string
useful for a... |
def getconfigvar_escaped(config: configparser.ConfigParser,
section: str,
key: str) -> Optional[str]:
"""
Returns a CGI-escaped version of the value read from an INI file using
:class:`ConfigParser`, or ``None``.
"""
value = config.get(section, key)
... | Returns a CGI-escaped version of the value read from an INI file using
:class:`ConfigParser`, or ``None``. | Below is the the instruction that describes the task:
### Input:
Returns a CGI-escaped version of the value read from an INI file using
:class:`ConfigParser`, or ``None``.
### Response:
def getconfigvar_escaped(config: configparser.ConfigParser,
section: str,
k... |
def LE16(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''16-bit field, Little endian encoded'''
return UInt16(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_LE, fuzzable=fuzzable, name=name, full_range=full_range) | 16-bit field, Little endian encoded | Below is the the instruction that describes the task:
### Input:
16-bit field, Little endian encoded
### Response:
def LE16(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''16-bit field, Little endian encoded'''
return UInt16(value, min_value=min_value, max_value=max_v... |
def _ReceiveFetchedFile(self, tracker):
"""Remove pathspec for this index and call the ReceiveFetchedFile method."""
index = tracker["index"]
_, request_data = self._RemoveCompletedPathspec(index)
# Report the request_data for this flow's caller.
self.ReceiveFetchedFile(
tracker["stat_entr... | Remove pathspec for this index and call the ReceiveFetchedFile method. | Below is the the instruction that describes the task:
### Input:
Remove pathspec for this index and call the ReceiveFetchedFile method.
### Response:
def _ReceiveFetchedFile(self, tracker):
"""Remove pathspec for this index and call the ReceiveFetchedFile method."""
index = tracker["index"]
_, request... |
def check_bbox(bbox):
"""Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums"""
for name, value in zip(['x_min', 'y_min', 'x_max', 'y_max'], bbox[:4]):
if not 0 <= value <= 1:
raise ValueError(
'Expected {name} for bbox {bbox} '
't... | Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums | Below is the the instruction that describes the task:
### Input:
Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums
### Response:
def check_bbox(bbox):
"""Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums"""
for name, value in zip(['x_min', 'y_mi... |
def __erase_primes(self):
"""Erase all prime markings"""
for i in range(self.n):
for j in range(self.n):
if self.marked[i][j] == 2:
self.marked[i][j] = 0 | Erase all prime markings | Below is the the instruction that describes the task:
### Input:
Erase all prime markings
### Response:
def __erase_primes(self):
"""Erase all prime markings"""
for i in range(self.n):
for j in range(self.n):
if self.marked[i][j] == 2:
self.marked[i][... |
def run_network_operation(self, task, wait_timeout=None,
close_timeout=None,
name='Network operation'):
'''Run the task and raise appropriate exceptions.
Coroutine.
'''
if wait_timeout is not None and close_timeout is not None:... | Run the task and raise appropriate exceptions.
Coroutine. | Below is the the instruction that describes the task:
### Input:
Run the task and raise appropriate exceptions.
Coroutine.
### Response:
def run_network_operation(self, task, wait_timeout=None,
close_timeout=None,
name='Network operation'):
... |
def matchstartorient(self,seq, factor=0.7):
"""
m.matchstartorient(,seq, factor=0.7) -- Returns list of (start,orientation) coordinate pairs of
matches to the motif in the supplied sequence. Factor
is multip... | m.matchstartorient(,seq, factor=0.7) -- Returns list of (start,orientation) coordinate pairs of
matches to the motif in the supplied sequence. Factor
is multiplied by m.maxscore to get a match threshold. | Below is the the instruction that describes the task:
### Input:
m.matchstartorient(,seq, factor=0.7) -- Returns list of (start,orientation) coordinate pairs of
matches to the motif in the supplied sequence. Factor
is m... |
def get_args():
"""
Supports the command-line arguments listed below.
"""
parser = argparse.ArgumentParser(
description="Provision multiple VM's through mist.io. You can get "
"information returned with the name of the virtual machine created "
"and its main mac and ip address i... | Supports the command-line arguments listed below. | Below is the the instruction that describes the task:
### Input:
Supports the command-line arguments listed below.
### Response:
def get_args():
"""
Supports the command-line arguments listed below.
"""
parser = argparse.ArgumentParser(
description="Provision multiple VM's through mist.io.... |
def set_ipcsem_params(self, ftok=None, persistent=None):
"""Sets ipcsem lock engine params.
:param str|unicode ftok: Set the ipcsem key via ftok() for avoiding duplicates.
:param bool persistent: Do not remove ipcsem's on shutdown.
"""
self._set('ftok', ftok)
self._set... | Sets ipcsem lock engine params.
:param str|unicode ftok: Set the ipcsem key via ftok() for avoiding duplicates.
:param bool persistent: Do not remove ipcsem's on shutdown. | Below is the the instruction that describes the task:
### Input:
Sets ipcsem lock engine params.
:param str|unicode ftok: Set the ipcsem key via ftok() for avoiding duplicates.
:param bool persistent: Do not remove ipcsem's on shutdown.
### Response:
def set_ipcsem_params(self, ftok=None, persist... |
def incrementName(nameList, name):
"""
return a name that is unique in a given nameList through
attaching a number to it
>>> l = []
now we will add 3xfoo 2xbar and one klaus to our list:
>>> l.append( incrementName(l,'foo') )
>>> l.append( incrementName(l,'bar') )
>>> l.append( increm... | return a name that is unique in a given nameList through
attaching a number to it
>>> l = []
now we will add 3xfoo 2xbar and one klaus to our list:
>>> l.append( incrementName(l,'foo') )
>>> l.append( incrementName(l,'bar') )
>>> l.append( incrementName(l,'foo') )
>>> l.append( incrementN... | Below is the the instruction that describes the task:
### Input:
return a name that is unique in a given nameList through
attaching a number to it
>>> l = []
now we will add 3xfoo 2xbar and one klaus to our list:
>>> l.append( incrementName(l,'foo') )
>>> l.append( incrementName(l,'bar') )
... |
def filter_segs(self, segs):
"""Given list of strings, return only those which are valid segments.
Args:
segs (list): list of unicode values
Returns:
list: values in `segs` that are valid segments (according to the
definititions of bases and diacritics... | Given list of strings, return only those which are valid segments.
Args:
segs (list): list of unicode values
Returns:
list: values in `segs` that are valid segments (according to the
definititions of bases and diacritics/modifiers known to the
... | Below is the the instruction that describes the task:
### Input:
Given list of strings, return only those which are valid segments.
Args:
segs (list): list of unicode values
Returns:
list: values in `segs` that are valid segments (according to the
definiti... |
def parser(self):
"""
This function returns a parser.
The grammar should be like most full text search engines (Google, Tsearch, Lucene).
Grammar:
- a query consists of alphanumeric words, with an optional '*' wildcard
at the end of a word
- a sequence ... | This function returns a parser.
The grammar should be like most full text search engines (Google, Tsearch, Lucene).
Grammar:
- a query consists of alphanumeric words, with an optional '*' wildcard
at the end of a word
- a sequence of words between quotes is a literal str... | Below is the the instruction that describes the task:
### Input:
This function returns a parser.
The grammar should be like most full text search engines (Google, Tsearch, Lucene).
Grammar:
- a query consists of alphanumeric words, with an optional '*' wildcard
at the end of ... |
def process_direct_map(self, root, state) -> List[Dict]:
"""Handles tags that are mapped directly from xml to IR with no
additional processing other than recursive translation of any child
nodes."""
val = {"tag": root.tag, "args": []}
for node in root:
val["args"] +=... | Handles tags that are mapped directly from xml to IR with no
additional processing other than recursive translation of any child
nodes. | Below is the the instruction that describes the task:
### Input:
Handles tags that are mapped directly from xml to IR with no
additional processing other than recursive translation of any child
nodes.
### Response:
def process_direct_map(self, root, state) -> List[Dict]:
"""Handles tags tha... |
def getdarkimg(self,chip):
"""
Return an array representing the dark image for the detector.
Returns
-------
dark : array
The dark array in the same shape as the image with **units of cps**.
"""
# Read the temperature dependeant dark file. The name... | Return an array representing the dark image for the detector.
Returns
-------
dark : array
The dark array in the same shape as the image with **units of cps**. | Below is the the instruction that describes the task:
### Input:
Return an array representing the dark image for the detector.
Returns
-------
dark : array
The dark array in the same shape as the image with **units of cps**.
### Response:
def getdarkimg(self,chip):
"""
... |
def blockquote(
self,
text):
"""*convert plain-text to MMD blockquote*
**Key Arguments:**
- ``text`` -- the text to convert to MMD blockquote
**Return:**
- ``blockquote`` -- the MMD blockquote
**Usage:**
To convert a text to... | *convert plain-text to MMD blockquote*
**Key Arguments:**
- ``text`` -- the text to convert to MMD blockquote
**Return:**
- ``blockquote`` -- the MMD blockquote
**Usage:**
To convert a text to a MMD blockquote:
.. code-block:: python
... | Below is the the instruction that describes the task:
### Input:
*convert plain-text to MMD blockquote*
**Key Arguments:**
- ``text`` -- the text to convert to MMD blockquote
**Return:**
- ``blockquote`` -- the MMD blockquote
**Usage:**
To convert a te... |
def to_markdown(self):
"""
Generate a summary in markdown format
"""
json = self.to_report_json()
# summary = json['summary']
s = "# Group: {group} - Dataset: {dataset}\n".format(group=json["group"], dataset=json["dataset"])
s += "\n## SUMMARY\n\n"
s += "... | Generate a summary in markdown format | Below is the the instruction that describes the task:
### Input:
Generate a summary in markdown format
### Response:
def to_markdown(self):
"""
Generate a summary in markdown format
"""
json = self.to_report_json()
# summary = json['summary']
s = "# Group: {group} -... |
def update_cnum(self):
"""Check if we shall add cnum in 035."""
if "ConferencePaper" not in self.collections:
cnums = record_get_field_values(self.record, '773', code="w")
for cnum in cnums:
cnum_subs = [
("9", "INSPIRE-CNUM"),
... | Check if we shall add cnum in 035. | Below is the the instruction that describes the task:
### Input:
Check if we shall add cnum in 035.
### Response:
def update_cnum(self):
"""Check if we shall add cnum in 035."""
if "ConferencePaper" not in self.collections:
cnums = record_get_field_values(self.record, '773', code="w")
... |
def dump(self, filename, encoding="utf8"):
"""
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8".
"""
with open(filename, mode='w', encoding=encoding) as text_file:
text... | Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8". | Below is the the instruction that describes the task:
### Input:
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8".
### Response:
def dump(self, filename, encoding="utf8"):
"""
Dumps the ascii... |
def assemble_transition_model_from_gradable_adjectives(self):
""" Add probability distribution functions constructed from gradable
adjective data to the edges of the analysis graph data structure.
Args:
adjective_data
res
"""
df = pd.read_sql_table("grad... | Add probability distribution functions constructed from gradable
adjective data to the edges of the analysis graph data structure.
Args:
adjective_data
res | Below is the the instruction that describes the task:
### Input:
Add probability distribution functions constructed from gradable
adjective data to the edges of the analysis graph data structure.
Args:
adjective_data
res
### Response:
def assemble_transition_model_from_grad... |
def delete_hosting_device_resources(self, context, tenant_id, mgmt_port,
**kwargs):
"""Deletes resources for a hosting device in a plugin specific way."""
if mgmt_port is not None:
try:
self._cleanup_hosting_port(context, mgmt_port['id... | Deletes resources for a hosting device in a plugin specific way. | Below is the the instruction that describes the task:
### Input:
Deletes resources for a hosting device in a plugin specific way.
### Response:
def delete_hosting_device_resources(self, context, tenant_id, mgmt_port,
**kwargs):
"""Deletes resources for a hosting devi... |
def account_groups_and_extra_data(account, resource,
refresh_timedelta=None):
"""Fetch account groups and extra data from resource if necessary."""
updated = datetime.utcnow()
modified_since = updated
if refresh_timedelta is not None:
modified_since += refresh_t... | Fetch account groups and extra data from resource if necessary. | Below is the the instruction that describes the task:
### Input:
Fetch account groups and extra data from resource if necessary.
### Response:
def account_groups_and_extra_data(account, resource,
refresh_timedelta=None):
"""Fetch account groups and extra data from resource if ... |
def backup(self):
"""
Saves the configuration information of the current running vent
instance to be used for restoring at a later time
"""
status = (True, None)
# initialize all needed variables (names for backup files, etc.)
backup_name = ('.vent-backup-' + '-'.... | Saves the configuration information of the current running vent
instance to be used for restoring at a later time | Below is the the instruction that describes the task:
### Input:
Saves the configuration information of the current running vent
instance to be used for restoring at a later time
### Response:
def backup(self):
"""
Saves the configuration information of the current running vent
inst... |
def time(self, target=None):
"""
Get server time.
Optional arguments:
* target=None - Target server.
"""
with self.lock:
if target:
self.send('TIME %s' % target)
else:
self.send('TIME')
time = ''
... | Get server time.
Optional arguments:
* target=None - Target server. | Below is the the instruction that describes the task:
### Input:
Get server time.
Optional arguments:
* target=None - Target server.
### Response:
def time(self, target=None):
"""
Get server time.
Optional arguments:
* target=None - Target server.
"""
... |
def _scale_fig_size(figsize, textsize, rows=1, cols=1):
"""Scale figure properties according to rows and cols.
Parameters
----------
figsize : float or None
Size of figure in inches
textsize : float or None
fontsize
rows : int
Number of rows
cols : int
Number... | Scale figure properties according to rows and cols.
Parameters
----------
figsize : float or None
Size of figure in inches
textsize : float or None
fontsize
rows : int
Number of rows
cols : int
Number of columns
Returns
-------
figsize : float or Non... | Below is the the instruction that describes the task:
### Input:
Scale figure properties according to rows and cols.
Parameters
----------
figsize : float or None
Size of figure in inches
textsize : float or None
fontsize
rows : int
Number of rows
cols : int
... |
async def _parse_message_text(self, message, parse_mode):
"""
Returns a (parsed message, entities) tuple depending on ``parse_mode``.
"""
if parse_mode is ():
parse_mode = self._parse_mode
else:
parse_mode = utils.sanitize_parse_mode(parse_mode)
i... | Returns a (parsed message, entities) tuple depending on ``parse_mode``. | Below is the the instruction that describes the task:
### Input:
Returns a (parsed message, entities) tuple depending on ``parse_mode``.
### Response:
async def _parse_message_text(self, message, parse_mode):
"""
Returns a (parsed message, entities) tuple depending on ``parse_mode``.
"""
... |
def periodic(seconds=0, minutes=0, hours=0, days=0, weeks=0, start_date=None,
end_date=None):
"""
Periodic task schedule: Use to schedule a task to run periodically,
starting from start_date (or None to be active immediately) until end_date
(or None to repeat forever).
The period start... | Periodic task schedule: Use to schedule a task to run periodically,
starting from start_date (or None to be active immediately) until end_date
(or None to repeat forever).
The period starts at the given start_date, or on Jan 1st 2000.
For more details, see README. | Below is the the instruction that describes the task:
### Input:
Periodic task schedule: Use to schedule a task to run periodically,
starting from start_date (or None to be active immediately) until end_date
(or None to repeat forever).
The period starts at the given start_date, or on Jan 1st 2000.
... |
def _mask(self, tensor, length, padding_value=0):
"""Set padding elements of a batch of sequences to a constant.
Useful for setting padding elements to zero before summing along the time
dimension, or for preventing infinite results in padding elements.
Args:
tensor: Tensor of sequences.
l... | Set padding elements of a batch of sequences to a constant.
Useful for setting padding elements to zero before summing along the time
dimension, or for preventing infinite results in padding elements.
Args:
tensor: Tensor of sequences.
length: Batch of sequence lengths.
padding_value: Va... | Below is the the instruction that describes the task:
### Input:
Set padding elements of a batch of sequences to a constant.
Useful for setting padding elements to zero before summing along the time
dimension, or for preventing infinite results in padding elements.
Args:
tensor: Tensor of sequen... |
def get_requested_aosp_permissions_details(self):
"""
Returns requested aosp permissions with details.
:rtype: dictionary
"""
l = {}
for i in self.permissions:
try:
l[i] = self.permission_module[i]
except KeyError:
... | Returns requested aosp permissions with details.
:rtype: dictionary | Below is the the instruction that describes the task:
### Input:
Returns requested aosp permissions with details.
:rtype: dictionary
### Response:
def get_requested_aosp_permissions_details(self):
"""
Returns requested aosp permissions with details.
:rtype: dictionary
"""
... |
def cli(conf):
""" OpenVPN status initdb method
"""
try:
config = init_config(conf)
debug = config.getboolean('DEFAULT', 'debug')
conn = get_conn(config.get('DEFAULT','statusdb'))
cur = conn.cursor()
sqlstr = '''create table client_status
(session_id text PRIM... | OpenVPN status initdb method | Below is the the instruction that describes the task:
### Input:
OpenVPN status initdb method
### Response:
def cli(conf):
""" OpenVPN status initdb method
"""
try:
config = init_config(conf)
debug = config.getboolean('DEFAULT', 'debug')
conn = get_conn(config.get('DEFAULT','sta... |
def load(filename, instruments = None):
"""
loads an script instance using pickle
Args:
filename: source filename
instruments:
optional - only needed if script requires instruments
dictionary of form
instruments = {
... | loads an script instance using pickle
Args:
filename: source filename
instruments:
optional - only needed if script requires instruments
dictionary of form
instruments = {
name_of_instrument_1 : instance_of_instrument_1,
... | Below is the the instruction that describes the task:
### Input:
loads an script instance using pickle
Args:
filename: source filename
instruments:
optional - only needed if script requires instruments
dictionary of form
instruments = ... |
def add_pfba(model, objective=None, fraction_of_optimum=1.0):
"""Add pFBA objective
Add objective to minimize the summed flux of all reactions to the
current objective.
See Also
-------
pfba
Parameters
----------
model : cobra.Model
The model to add the objective to
ob... | Add pFBA objective
Add objective to minimize the summed flux of all reactions to the
current objective.
See Also
-------
pfba
Parameters
----------
model : cobra.Model
The model to add the objective to
objective :
An objective to set in combination with the pFBA ob... | Below is the the instruction that describes the task:
### Input:
Add pFBA objective
Add objective to minimize the summed flux of all reactions to the
current objective.
See Also
-------
pfba
Parameters
----------
model : cobra.Model
The model to add the objective to
ob... |
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for ma... | Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user sta... | Below is the the instruction that describes the task:
### Input:
Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
th... |
def proppivot(self, prop):
'''
:foo:bar -> baz:faz
'''
pval = s_ast.RelPropValue(kids=(prop,))
self.ignore(whitespace)
self.nextmust('->')
self.ignore(whitespace)
if self.nextchar() == '*':
self.offs += 1
return s_ast.PropPivotO... | :foo:bar -> baz:faz | Below is the the instruction that describes the task:
### Input:
:foo:bar -> baz:faz
### Response:
def proppivot(self, prop):
'''
:foo:bar -> baz:faz
'''
pval = s_ast.RelPropValue(kids=(prop,))
self.ignore(whitespace)
self.nextmust('->')
self.ignore(whites... |
def get_property(self):
"""
Returns the property of the variable
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_property()
{'bowel-problem': ['position = (190, 69)'],
'dog-out': ['position = (155, 165)'],
'f... | Returns the property of the variable
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_property()
{'bowel-problem': ['position = (190, 69)'],
'dog-out': ['position = (155, 165)'],
'family-out': ['position = (112, 69)'],
... | Below is the the instruction that describes the task:
### Input:
Returns the property of the variable
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_property()
{'bowel-problem': ['position = (190, 69)'],
'dog-out': ['position = ... |
def input(self, *args, **kwargs):
"""
Adapt the input and check for errors.
Returns a tuple of adapted (args, kwargs) or raises
AnticipateErrors
"""
errors = []
if args and self.arg_names:
args = list(args)
# Replace args inline that have... | Adapt the input and check for errors.
Returns a tuple of adapted (args, kwargs) or raises
AnticipateErrors | Below is the the instruction that describes the task:
### Input:
Adapt the input and check for errors.
Returns a tuple of adapted (args, kwargs) or raises
AnticipateErrors
### Response:
def input(self, *args, **kwargs):
"""
Adapt the input and check for errors.
Returns a t... |
def flake(self, message):
"""Print an error message to stdout."""
self.stdout.write(str(message))
self.stdout.write('\n') | Print an error message to stdout. | Below is the the instruction that describes the task:
### Input:
Print an error message to stdout.
### Response:
def flake(self, message):
"""Print an error message to stdout."""
self.stdout.write(str(message))
self.stdout.write('\n') |
def _scaled_bqm(bqm, scalar, bias_range, quadratic_range,
ignored_variables, ignored_interactions,
ignore_offset):
"""Helper function of sample for scaling"""
bqm_copy = bqm.copy()
if scalar is None:
scalar = _calc_norm_coeff(bqm_copy.linear, bqm_copy.quadratic,
... | Helper function of sample for scaling | Below is the the instruction that describes the task:
### Input:
Helper function of sample for scaling
### Response:
def _scaled_bqm(bqm, scalar, bias_range, quadratic_range,
ignored_variables, ignored_interactions,
ignore_offset):
"""Helper function of sample for scaling"""
... |
def _get_files(path):
"""
Returns the list of files contained in path (recursively).
"""
ret_val = []
for root, _, files in os.walk(path):
for f in files:
ret_val.append(os.path.join(root, f))
return ret_val | Returns the list of files contained in path (recursively). | Below is the the instruction that describes the task:
### Input:
Returns the list of files contained in path (recursively).
### Response:
def _get_files(path):
"""
Returns the list of files contained in path (recursively).
"""
ret_val = []
for root, _, files in os.walk(path)... |
def _get_next_all_link_record(self):
"""Request next ALL-Link record."""
_LOGGER.debug("Starting: _get_next_all_link_record")
_LOGGER.debug("Requesting Next All-Link Record")
msg = GetNextAllLinkRecord()
self.send_msg(msg, wait_nak=True, wait_timeout=.5)
_LOGGER.debug("En... | Request next ALL-Link record. | Below is the the instruction that describes the task:
### Input:
Request next ALL-Link record.
### Response:
def _get_next_all_link_record(self):
"""Request next ALL-Link record."""
_LOGGER.debug("Starting: _get_next_all_link_record")
_LOGGER.debug("Requesting Next All-Link Record")
... |
def pretty_error(error, verbose=False):
"""Return an error message that is easier to read and more useful.
May require updating if the schemas change significantly.
"""
error_loc = ''
if error.path:
while len(error.path) > 0:
path_elem = error.path.popleft()
if type(... | Return an error message that is easier to read and more useful.
May require updating if the schemas change significantly. | Below is the the instruction that describes the task:
### Input:
Return an error message that is easier to read and more useful.
May require updating if the schemas change significantly.
### Response:
def pretty_error(error, verbose=False):
"""Return an error message that is easier to read and more useful.... |
def status_schedule(token):
"""
Returns the json string from the Hydrawise server after calling
statusschedule.php.
:param token: The users API token.
:type token: string
:returns: The response from the controller. If there was an error returns
None.
:rtype: string or None
... | Returns the json string from the Hydrawise server after calling
statusschedule.php.
:param token: The users API token.
:type token: string
:returns: The response from the controller. If there was an error returns
None.
:rtype: string or None | Below is the the instruction that describes the task:
### Input:
Returns the json string from the Hydrawise server after calling
statusschedule.php.
:param token: The users API token.
:type token: string
:returns: The response from the controller. If there was an error returns
None.
... |
def save_scatter_table(self, fn, description=""):
"""Save the scattering lookup tables.
Save the state of the scattering lookup tables to a file.
This can be loaded later with load_scatter_table.
Other variables will not be saved, but this does not matter because
the re... | Save the scattering lookup tables.
Save the state of the scattering lookup tables to a file.
This can be loaded later with load_scatter_table.
Other variables will not be saved, but this does not matter because
the results of the computations are based only on the contents
... | Below is the the instruction that describes the task:
### Input:
Save the scattering lookup tables.
Save the state of the scattering lookup tables to a file.
This can be loaded later with load_scatter_table.
Other variables will not be saved, but this does not matter because
... |
async def forward_messages(self, entity, messages, from_peer=None,
*, silent=None, as_album=None):
"""
Forwards the given message(s) to the specified entity.
Args:
entity (`entity`):
To which entity the message(s) will be forwarded.
... | Forwards the given message(s) to the specified entity.
Args:
entity (`entity`):
To which entity the message(s) will be forwarded.
messages (`list` | `int` | `Message <telethon.tl.custom.message.Message>`):
The message(s) to forward, or their integer IDs.... | Below is the the instruction that describes the task:
### Input:
Forwards the given message(s) to the specified entity.
Args:
entity (`entity`):
To which entity the message(s) will be forwarded.
messages (`list` | `int` | `Message <telethon.tl.custom.message.Message... |
def generation(self):
"""Get the current generation state if the group is stable.
Returns: the current generation or None if the group is unjoined/rebalancing
"""
with self._lock:
if self.state is not MemberState.STABLE:
return None
return self._g... | Get the current generation state if the group is stable.
Returns: the current generation or None if the group is unjoined/rebalancing | Below is the the instruction that describes the task:
### Input:
Get the current generation state if the group is stable.
Returns: the current generation or None if the group is unjoined/rebalancing
### Response:
def generation(self):
"""Get the current generation state if the group is stable.
... |
def match_term(self, value, required=True, new_group=False):
"""Add a fulltext search term to the query.
Warning:
Do not use this method with any other query-building helpers. This method
is only for building fulltext queries (in non-advanced mode). Using other
helpe... | Add a fulltext search term to the query.
Warning:
Do not use this method with any other query-building helpers. This method
is only for building fulltext queries (in non-advanced mode). Using other
helpers, such as ``match_field()``, will cause the query to run in advanced m... | Below is the the instruction that describes the task:
### Input:
Add a fulltext search term to the query.
Warning:
Do not use this method with any other query-building helpers. This method
is only for building fulltext queries (in non-advanced mode). Using other
helpers,... |
def plot_two_digit_freqs(f2):
"""
Plot two digits frequency counts using matplotlib.
"""
f2_copy = f2.copy()
f2_copy.shape = (10,10)
ax = plt.matshow(f2_copy)
plt.colorbar()
for i in range(10):
for j in range(10):
plt.text(i-0.2, j+0.2, str(j)+str(i))
plt.ylabel('... | Plot two digits frequency counts using matplotlib. | Below is the the instruction that describes the task:
### Input:
Plot two digits frequency counts using matplotlib.
### Response:
def plot_two_digit_freqs(f2):
"""
Plot two digits frequency counts using matplotlib.
"""
f2_copy = f2.copy()
f2_copy.shape = (10,10)
ax = plt.matshow(f2_copy)
... |
def _main(self):
"""module "main" method. Only used by external modules.
:return: None
"""
self.set_proctitle(self.name)
self.set_signal_handler()
logger.info("process for module %s is now running (pid=%d)", self.name, os.getpid())
# Will block here!
tr... | module "main" method. Only used by external modules.
:return: None | Below is the the instruction that describes the task:
### Input:
module "main" method. Only used by external modules.
:return: None
### Response:
def _main(self):
"""module "main" method. Only used by external modules.
:return: None
"""
self.set_proctitle(self.name)
... |
def get_local_environnement(self):
"""
Mix the environment and the environment variables into a new local
environment dictionary
Note: We cannot just update the global os.environ because this
would effect all other checks.
:return: local environment variables
:r... | Mix the environment and the environment variables into a new local
environment dictionary
Note: We cannot just update the global os.environ because this
would effect all other checks.
:return: local environment variables
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Mix the environment and the environment variables into a new local
environment dictionary
Note: We cannot just update the global os.environ because this
would effect all other checks.
:return: local environment variab... |
def timer(logger=None, level=logging.INFO,
fmt="function %(function_name)s execution time: %(execution_time).3f",
*func_or_func_args, **timer_kwargs):
""" Function decorator displaying the function execution time
All kwargs are the arguments taken by the Timer class constructor.
"""
... | Function decorator displaying the function execution time
All kwargs are the arguments taken by the Timer class constructor. | Below is the the instruction that describes the task:
### Input:
Function decorator displaying the function execution time
All kwargs are the arguments taken by the Timer class constructor.
### Response:
def timer(logger=None, level=logging.INFO,
fmt="function %(function_name)s execution time: %(exe... |
def load_json(filename, to='auto'):
'''
load_json(filename) yields the object represented by the json file or stream object filename.
The optional argument to may be set to None to indicate that the JSON data should be returned
verbatim rather than parsed by neuropythy's denormalize system.
'''... | load_json(filename) yields the object represented by the json file or stream object filename.
The optional argument to may be set to None to indicate that the JSON data should be returned
verbatim rather than parsed by neuropythy's denormalize system. | Below is the the instruction that describes the task:
### Input:
load_json(filename) yields the object represented by the json file or stream object filename.
The optional argument to may be set to None to indicate that the JSON data should be returned
verbatim rather than parsed by neuropythy's denorm... |
def _expected_condition_value_in_element_attribute(self, element_attribute_value):
"""Tries to find the element and checks that it contains the requested attribute with the expected value,
but does not thrown an exception if the element is not found
:param element_attribute_value: Tuple with... | Tries to find the element and checks that it contains the requested attribute with the expected value,
but does not thrown an exception if the element is not found
:param element_attribute_value: Tuple with 3 items where:
[0] element: PageElement or element locator as a tuple (locator_ty... | Below is the the instruction that describes the task:
### Input:
Tries to find the element and checks that it contains the requested attribute with the expected value,
but does not thrown an exception if the element is not found
:param element_attribute_value: Tuple with 3 items where:
... |
def get_user():
"""
Get your user object.
Users may only get their own info, not others'.
---
responses:
'200':
description: user response
schema:
$ref: '#/definitions/User'
default:
description: unexpected error
schema:
$ref: '#/defin... | Get your user object.
Users may only get their own info, not others'.
---
responses:
'200':
description: user response
schema:
$ref: '#/definitions/User'
default:
description: unexpected error
schema:
$ref: '#/definitions/errorModel'
descr... | Below is the the instruction that describes the task:
### Input:
Get your user object.
Users may only get their own info, not others'.
---
responses:
'200':
description: user response
schema:
$ref: '#/definitions/User'
default:
description: unexpected error... |
def my_profile_view(request):
''' The view of the profile page. '''
page_name = "Profile Page"
if request.user.username == ANONYMOUS_USERNAME:
return red_home(request, MESSAGES['SPINELESS'])
userProfile = UserProfile.objects.get(user=request.user)
change_password_form = PasswordChangeForm(
... | The view of the profile page. | Below is the the instruction that describes the task:
### Input:
The view of the profile page.
### Response:
def my_profile_view(request):
''' The view of the profile page. '''
page_name = "Profile Page"
if request.user.username == ANONYMOUS_USERNAME:
return red_home(request, MESSAGES['SPINELES... |
def selection_paste_data_gen(self, selection, data, freq=None):
"""Generator that yields data for selection paste"""
(bb_top, bb_left), (bb_bottom, bb_right) = \
selection.get_grid_bbox(self.grid.code_array.shape)
bbox_height = bb_bottom - bb_top + 1
bbox_width = bb_right - ... | Generator that yields data for selection paste | Below is the the instruction that describes the task:
### Input:
Generator that yields data for selection paste
### Response:
def selection_paste_data_gen(self, selection, data, freq=None):
"""Generator that yields data for selection paste"""
(bb_top, bb_left), (bb_bottom, bb_right) = \
... |
def revoke_all_tokens(self):
"""
Implementation of :meth:`twitcher.api.ITokenManager.revoke_all_tokens`.
"""
try:
self.store.clear_tokens()
except Exception:
LOGGER.exception('Failed to remove tokens.')
return False
else:
re... | Implementation of :meth:`twitcher.api.ITokenManager.revoke_all_tokens`. | Below is the the instruction that describes the task:
### Input:
Implementation of :meth:`twitcher.api.ITokenManager.revoke_all_tokens`.
### Response:
def revoke_all_tokens(self):
"""
Implementation of :meth:`twitcher.api.ITokenManager.revoke_all_tokens`.
"""
try:
self.s... |
def conduit_lengths(network, throats=None, mode='pore'):
r"""
Return the respective lengths of the conduit components defined by the throat
conns P1 T P2
mode = 'pore' - uses pore coordinates
mode = 'centroid' uses pore and throat centroids
"""
if throats is None:
throats = network.t... | r"""
Return the respective lengths of the conduit components defined by the throat
conns P1 T P2
mode = 'pore' - uses pore coordinates
mode = 'centroid' uses pore and throat centroids | Below is the the instruction that describes the task:
### Input:
r"""
Return the respective lengths of the conduit components defined by the throat
conns P1 T P2
mode = 'pore' - uses pore coordinates
mode = 'centroid' uses pore and throat centroids
### Response:
def conduit_lengths(network, throats... |
def sqldelete(table, where):
"""Generates SQL delete from ... where ...
>>> sqldelete('t', {'id': 5})
('delete from t where id=%s', [5])
"""
validate_name(table)
(whereclause, wherevalues) = sqlwhere(where)
sql = "delete from {}".format(table)
if whereclause:
sql += " where " + ... | Generates SQL delete from ... where ...
>>> sqldelete('t', {'id': 5})
('delete from t where id=%s', [5]) | Below is the the instruction that describes the task:
### Input:
Generates SQL delete from ... where ...
>>> sqldelete('t', {'id': 5})
('delete from t where id=%s', [5])
### Response:
def sqldelete(table, where):
"""Generates SQL delete from ... where ...
>>> sqldelete('t', {'id': 5})
('delet... |
def image_export(cls, source_path, dest_url, **kwargs):
"""Export the specific image to remote host or local file system """
dest_path = urlparse.urlparse(dest_url).path
if kwargs['remote_host']:
target_path = ':'.join([kwargs['remote_host'], dest_path])
command = ' '.joi... | Export the specific image to remote host or local file system | Below is the the instruction that describes the task:
### Input:
Export the specific image to remote host or local file system
### Response:
def image_export(cls, source_path, dest_url, **kwargs):
"""Export the specific image to remote host or local file system """
dest_path = urlparse.urlparse(des... |
def iptag_get(self, iptag, x, y):
"""Get the value of an IPTag.
Parameters
----------
iptag : int
Index of the IPTag to get
Returns
-------
:py:class:`.IPTag`
The IPTag returned from SpiNNaker.
"""
ack = self._send_scp(x, ... | Get the value of an IPTag.
Parameters
----------
iptag : int
Index of the IPTag to get
Returns
-------
:py:class:`.IPTag`
The IPTag returned from SpiNNaker. | Below is the the instruction that describes the task:
### Input:
Get the value of an IPTag.
Parameters
----------
iptag : int
Index of the IPTag to get
Returns
-------
:py:class:`.IPTag`
The IPTag returned from SpiNNaker.
### Response:
def i... |
def load_parameter(input_filename, only_header=False):
"""Load HTK parameter/feature file.
:param input_filename:
:param only_header: only load the metadata
:return: a named tuple representing the HTK parmeter file
"""
with open(input_filename, 'rb') as f:
meta = _parse_parameter_meta(... | Load HTK parameter/feature file.
:param input_filename:
:param only_header: only load the metadata
:return: a named tuple representing the HTK parmeter file | Below is the the instruction that describes the task:
### Input:
Load HTK parameter/feature file.
:param input_filename:
:param only_header: only load the metadata
:return: a named tuple representing the HTK parmeter file
### Response:
def load_parameter(input_filename, only_header=False):
"""Load... |
def error(msg, details=None, *args, **kwargs):
'''Display an error message with optionnal details'''
msg = '{0} {1}'.format(red(KO), white(msg))
if details:
msg = '\n'.join((msg, safe_unicode(details)))
echo(format_multiline(msg), *args, **kwargs) | Display an error message with optionnal details | Below is the the instruction that describes the task:
### Input:
Display an error message with optionnal details
### Response:
def error(msg, details=None, *args, **kwargs):
'''Display an error message with optionnal details'''
msg = '{0} {1}'.format(red(KO), white(msg))
if details:
msg = '\n'.... |
def get_available_modes(self):
"""Return a list of available mode objects for an Arlo user."""
resource = "modes"
resource_event = self.publish_and_get_event(resource)
if resource_event:
properties = resource_event.get("properties")
return properties.get("modes")
... | Return a list of available mode objects for an Arlo user. | Below is the the instruction that describes the task:
### Input:
Return a list of available mode objects for an Arlo user.
### Response:
def get_available_modes(self):
"""Return a list of available mode objects for an Arlo user."""
resource = "modes"
resource_event = self.publish_and_get_ev... |
def invalidate_m2m_cache(sender, instance, model, **kwargs):
"""
Signal receiver for models to invalidate model cache for many-to-many relationship.
Parameters
~~~~~~~~~~
sender
The model class
instance
The instance whose many-to-many relation is updated.
model
The c... | Signal receiver for models to invalidate model cache for many-to-many relationship.
Parameters
~~~~~~~~~~
sender
The model class
instance
The instance whose many-to-many relation is updated.
model
The class of the objects that are added to, removed from or cleared from the r... | Below is the the instruction that describes the task:
### Input:
Signal receiver for models to invalidate model cache for many-to-many relationship.
Parameters
~~~~~~~~~~
sender
The model class
instance
The instance whose many-to-many relation is updated.
model
The class... |
def gen_and(src1, src2, dst):
"""Return an AND instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.AND, src1, src2, dst) | Return an AND instruction. | Below is the the instruction that describes the task:
### Input:
Return an AND instruction.
### Response:
def gen_and(src1, src2, dst):
"""Return an AND instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.AND, src1, src2, dst) |
def checkrc(rc, *args):
"""Check if ``rc`` (return code) meets requirements.
Check if ``rc`` is 0 or is in ``args`` list that contains
acceptable return codes.
Last argument of ``args`` can optionally be error message that
is printed if ``rc`` doesn't meet requirements.
Output is JSON of the f... | Check if ``rc`` (return code) meets requirements.
Check if ``rc`` is 0 or is in ``args`` list that contains
acceptable return codes.
Last argument of ``args`` can optionally be error message that
is printed if ``rc`` doesn't meet requirements.
Output is JSON of the form:
{"proc.rc": <rc>,... | Below is the the instruction that describes the task:
### Input:
Check if ``rc`` (return code) meets requirements.
Check if ``rc`` is 0 or is in ``args`` list that contains
acceptable return codes.
Last argument of ``args`` can optionally be error message that
is printed if ``rc`` doesn't meet requ... |
def sort_candidate_pairs(pairs, ice_controlling):
"""
Sort a list of candidate pairs.
"""
def pair_priority(pair):
return -candidate_pair_priority(pair.local_candidate,
pair.remote_candidate,
ice_controlling)
pa... | Sort a list of candidate pairs. | Below is the the instruction that describes the task:
### Input:
Sort a list of candidate pairs.
### Response:
def sort_candidate_pairs(pairs, ice_controlling):
"""
Sort a list of candidate pairs.
"""
def pair_priority(pair):
return -candidate_pair_priority(pair.local_candidate,
... |
def run(self):
"""
Sets up live server, and then loops over handling http requests.
"""
try:
# Go through the list of possible ports, hoping we can find
# one that is free to use for the WSGI server.
for index, port in enumerate(self.possible_ports):
... | Sets up live server, and then loops over handling http requests. | Below is the the instruction that describes the task:
### Input:
Sets up live server, and then loops over handling http requests.
### Response:
def run(self):
"""
Sets up live server, and then loops over handling http requests.
"""
try:
# Go through the list of possible ... |
def icosahedron():
"""
Create an icosahedron, a 20 faced polyhedron.
Returns
-------------
ico : trimesh.Trimesh
Icosahederon centered at the origin.
"""
t = (1.0 + 5.0**.5) / 2.0
vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t,
0, -1, -t, 0, ... | Create an icosahedron, a 20 faced polyhedron.
Returns
-------------
ico : trimesh.Trimesh
Icosahederon centered at the origin. | Below is the the instruction that describes the task:
### Input:
Create an icosahedron, a 20 faced polyhedron.
Returns
-------------
ico : trimesh.Trimesh
Icosahederon centered at the origin.
### Response:
def icosahedron():
"""
Create an icosahedron, a 20 faced polyhedron.
Returns
... |
def _run_cnvkit_single(data, background=None):
"""Process a single input file with BAM or uniform background.
"""
if not background:
background = []
ckouts = _run_cnvkit_shared([data], background)
if not ckouts:
return [data]
else:
assert len(ckouts) == 1
return _... | Process a single input file with BAM or uniform background. | Below is the the instruction that describes the task:
### Input:
Process a single input file with BAM or uniform background.
### Response:
def _run_cnvkit_single(data, background=None):
"""Process a single input file with BAM or uniform background.
"""
if not background:
background = []
cko... |
def RFC3156_canonicalize(text):
"""
Canonicalizes plain text (MIME-encoded usually) according to RFC3156.
This function works as follows (in that order):
1. Convert all line endings to \\\\r\\\\n (DOS line endings).
2. Encode all occurrences of "From " at the beginning of a line
to "From=20... | Canonicalizes plain text (MIME-encoded usually) according to RFC3156.
This function works as follows (in that order):
1. Convert all line endings to \\\\r\\\\n (DOS line endings).
2. Encode all occurrences of "From " at the beginning of a line
to "From=20" in order to prevent other mail programs to... | Below is the the instruction that describes the task:
### Input:
Canonicalizes plain text (MIME-encoded usually) according to RFC3156.
This function works as follows (in that order):
1. Convert all line endings to \\\\r\\\\n (DOS line endings).
2. Encode all occurrences of "From " at the beginning of ... |
def from_file(f, origin = None, rdclass = dns.rdataclass.IN,
relativize = True, zone_factory=Zone, filename=None,
allow_include=True, check_origin=True):
"""Read a master file and build a zone object.
@param f: file or string. If I{f} is a string, it is treated
as the name of a... | Read a master file and build a zone object.
@param f: file or string. If I{f} is a string, it is treated
as the name of a file to open.
@param origin: The origin of the zone; if not specified, the first
$ORIGIN statement in the master file will determine the origin of the
zone.
@type origin: d... | Below is the the instruction that describes the task:
### Input:
Read a master file and build a zone object.
@param f: file or string. If I{f} is a string, it is treated
as the name of a file to open.
@param origin: The origin of the zone; if not specified, the first
$ORIGIN statement in the maste... |
def add_step(self, step):
"""
Adds a new step to the waterfall.
:param step: Step to add
:return: Waterfall dialog for fluent calls to `add_step()`.
"""
if not step:
raise TypeError('WaterfallDialog.add_step(): step cannot be None.')
self.... | Adds a new step to the waterfall.
:param step: Step to add
:return: Waterfall dialog for fluent calls to `add_step()`. | Below is the the instruction that describes the task:
### Input:
Adds a new step to the waterfall.
:param step: Step to add
:return: Waterfall dialog for fluent calls to `add_step()`.
### Response:
def add_step(self, step):
"""
Adds a new step to the waterfall.
:... |
def user_absent(name, htpasswd_file=None, runas=None):
'''
Make sure the user is not in the specified htpasswd file
name
User name
htpasswd_file
Path to the htpasswd file
runas
The system user to run htpasswd command with
'''
ret = {'name': name,
'chang... | Make sure the user is not in the specified htpasswd file
name
User name
htpasswd_file
Path to the htpasswd file
runas
The system user to run htpasswd command with | Below is the the instruction that describes the task:
### Input:
Make sure the user is not in the specified htpasswd file
name
User name
htpasswd_file
Path to the htpasswd file
runas
The system user to run htpasswd command with
### Response:
def user_absent(name, htpasswd_fil... |
def bind_all(morc, builtin_only=False, stoplist=None, verbose=None):
"""Recursively apply constant binding to functions in a module or class.
Use as the last line of the module (after everything is defined, but
before test code). In modules that need modifiable globals, set
builtin_only to True.
:... | Recursively apply constant binding to functions in a module or class.
Use as the last line of the module (after everything is defined, but
before test code). In modules that need modifiable globals, set
builtin_only to True.
:param morc: module or class to transform.
:param bool builtin_only: only... | Below is the the instruction that describes the task:
### Input:
Recursively apply constant binding to functions in a module or class.
Use as the last line of the module (after everything is defined, but
before test code). In modules that need modifiable globals, set
builtin_only to True.
:param m... |
def no_constraints(cls, with_subclasses=False):
"""
Runs a callback with constraints disabled on the relation.
"""
cls._constraints = False
if with_subclasses:
for klass in cls.__subclasses__():
klass._constraints = False
try:
yie... | Runs a callback with constraints disabled on the relation. | Below is the the instruction that describes the task:
### Input:
Runs a callback with constraints disabled on the relation.
### Response:
def no_constraints(cls, with_subclasses=False):
"""
Runs a callback with constraints disabled on the relation.
"""
cls._constraints = False
... |
def start(self):
"""Starts the event dispatcher.
Initiates executor and start polling events.
Raises:
IllegalStateError: Can't start a dispatcher again when it's already
running.
"""
if not self.started:
self.started = True
se... | Starts the event dispatcher.
Initiates executor and start polling events.
Raises:
IllegalStateError: Can't start a dispatcher again when it's already
running. | Below is the the instruction that describes the task:
### Input:
Starts the event dispatcher.
Initiates executor and start polling events.
Raises:
IllegalStateError: Can't start a dispatcher again when it's already
running.
### Response:
def start(self):
"""Sta... |
def _hugoniot_p(self, v):
"""
calculate static pressure at 300 K.
:param v: unit-cell volume in A^3
:return: static pressure at t_ref (=300 K) in GPa
"""
rho = self._get_rho(v)
params = self._set_params(self.params_hugoniot)
if self.nonlinear:
... | calculate static pressure at 300 K.
:param v: unit-cell volume in A^3
:return: static pressure at t_ref (=300 K) in GPa | Below is the the instruction that describes the task:
### Input:
calculate static pressure at 300 K.
:param v: unit-cell volume in A^3
:return: static pressure at t_ref (=300 K) in GPa
### Response:
def _hugoniot_p(self, v):
"""
calculate static pressure at 300 K.
:param v... |
def _generate_route_method_decl(
self, namespace, route, arg_data_type, request_binary_body,
method_name_suffix='', extra_args=None):
"""Generates the method prototype for a route."""
args = ['self']
if extra_args:
args += extra_args
if request_binary_... | Generates the method prototype for a route. | Below is the the instruction that describes the task:
### Input:
Generates the method prototype for a route.
### Response:
def _generate_route_method_decl(
self, namespace, route, arg_data_type, request_binary_body,
method_name_suffix='', extra_args=None):
"""Generates the method pr... |
def fromfd(cls, fd):
"""
Create a new epoll object from a given file descriptor
:param fd:
A pre-made file descriptor obtained from ``epoll_create(2)`` or
``epoll_create1(2)``
:raises ValueError:
If fd is not a valid file descriptor
:returns:
... | Create a new epoll object from a given file descriptor
:param fd:
A pre-made file descriptor obtained from ``epoll_create(2)`` or
``epoll_create1(2)``
:raises ValueError:
If fd is not a valid file descriptor
:returns:
A new epoll object
.... | Below is the the instruction that describes the task:
### Input:
Create a new epoll object from a given file descriptor
:param fd:
A pre-made file descriptor obtained from ``epoll_create(2)`` or
``epoll_create1(2)``
:raises ValueError:
If fd is not a valid file d... |
def build(self, pre=None, shortest=False):
"""Build the ``Join`` field instance.
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
... | Build the ``Join`` field instance.
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. | Below is the the instruction that describes the task:
### Input:
Build the ``Join`` field instance.
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
### Response:
def build(sel... |
def app_broadcast(self, *args) -> None:
'''Send a broadcast.'''
_, error = self._execute('-s', self.device_sn, 'shell',
'am', 'broadcast', *args)
if error:
raise ApplicationsException(error.split(':', 1)[-1].strip()) | Send a broadcast. | Below is the the instruction that describes the task:
### Input:
Send a broadcast.
### Response:
def app_broadcast(self, *args) -> None:
'''Send a broadcast.'''
_, error = self._execute('-s', self.device_sn, 'shell',
'am', 'broadcast', *args)
if error:
... |
def nx_edges_between(graph, nodes1, nodes2=None, assume_disjoint=False,
assume_sparse=True):
r"""
Get edges between two components or within a single component
Args:
graph (nx.Graph): the graph
nodes1 (set): list of nodes
nodes2 (set): (default=None) if None it ... | r"""
Get edges between two components or within a single component
Args:
graph (nx.Graph): the graph
nodes1 (set): list of nodes
nodes2 (set): (default=None) if None it is equivlanet to nodes2=nodes1
assume_disjoint (bool): skips expensive check to ensure edges arnt
... | Below is the the instruction that describes the task:
### Input:
r"""
Get edges between two components or within a single component
Args:
graph (nx.Graph): the graph
nodes1 (set): list of nodes
nodes2 (set): (default=None) if None it is equivlanet to nodes2=nodes1
assume_dis... |
def plot_trunc_gr_model(
aval, bval, min_mag, max_mag, dmag,
catalogue=None, completeness=None, filename=None,
figure_size=(8, 6), filetype='png', dpi=300, ax=None):
"""
Plots a Gutenberg-Richter model
"""
input_model = TruncatedGRMFD(min_mag, max_mag, dmag, aval, bval)
if no... | Plots a Gutenberg-Richter model | Below is the the instruction that describes the task:
### Input:
Plots a Gutenberg-Richter model
### Response:
def plot_trunc_gr_model(
aval, bval, min_mag, max_mag, dmag,
catalogue=None, completeness=None, filename=None,
figure_size=(8, 6), filetype='png', dpi=300, ax=None):
"""
Pl... |
def list_node(self, **kwargs):
"""
list or watch objects of kind Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_node(async_req=True)
>>> result = thread.get()
:p... | list or watch objects of kind Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_node(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str pretty: If '... | Below is the the instruction that describes the task:
### Input:
list or watch objects of kind Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_node(async_req=True)
>>> result = thread... |
def diversity(layer):
"""Encourage diversity between each batch element.
A neural net feature often responds to multiple things, but naive feature
visualization often only shows us one. If you optimize a batch of images,
this objective will encourage them all to be different.
In particular, it caculuates th... | Encourage diversity between each batch element.
A neural net feature often responds to multiple things, but naive feature
visualization often only shows us one. If you optimize a batch of images,
this objective will encourage them all to be different.
In particular, it caculuates the correlation matrix of act... | Below is the the instruction that describes the task:
### Input:
Encourage diversity between each batch element.
A neural net feature often responds to multiple things, but naive feature
visualization often only shows us one. If you optimize a batch of images,
this objective will encourage them all to be dif... |
def build_simple_fault_geometry(fault_source):
"""
Returns the simple fault source geometry as a Node
:param fault_source:
Simple fault source model as an instance of the :class:
`openquake.hazardlib.source.simple_fault.SimpleFaultSource`
:returns:
Instance of :class:`openquake.... | Returns the simple fault source geometry as a Node
:param fault_source:
Simple fault source model as an instance of the :class:
`openquake.hazardlib.source.simple_fault.SimpleFaultSource`
:returns:
Instance of :class:`openquake.baselib.node.Node` | Below is the the instruction that describes the task:
### Input:
Returns the simple fault source geometry as a Node
:param fault_source:
Simple fault source model as an instance of the :class:
`openquake.hazardlib.source.simple_fault.SimpleFaultSource`
:returns:
Instance of :class:`... |
def get_encoding_from_headers(headers):
"""Returns encodings from given HTTP Header Dict.
:param headers: dictionary to extract encoding from.
"""
content_type = headers.get('content-type')
if not content_type:
return None
content_type, params = cgi.parse_header(content_type)
if... | Returns encodings from given HTTP Header Dict.
:param headers: dictionary to extract encoding from. | Below is the the instruction that describes the task:
### Input:
Returns encodings from given HTTP Header Dict.
:param headers: dictionary to extract encoding from.
### Response:
def get_encoding_from_headers(headers):
"""Returns encodings from given HTTP Header Dict.
:param headers: dictionary to ex... |
def check_existing_results(self, benchmark):
"""
Check and abort if the target directory for the benchmark results
already exists in order to avoid overwriting results.
"""
if os.path.exists(benchmark.log_folder):
sys.exit('Output directory {0} already exists, will no... | Check and abort if the target directory for the benchmark results
already exists in order to avoid overwriting results. | Below is the the instruction that describes the task:
### Input:
Check and abort if the target directory for the benchmark results
already exists in order to avoid overwriting results.
### Response:
def check_existing_results(self, benchmark):
"""
Check and abort if the target directory for... |
def search_dimensions(self, *args, **kwargs):
"""
Args:
query (string): elasticsearch string query
order_by (optional[string]): property by which to order results
offset (optional[int]): number of results to skip for pagination
(default=0)
... | Args:
query (string): elasticsearch string query
order_by (optional[string]): property by which to order results
offset (optional[int]): number of results to skip for pagination
(default=0)
limit (optional[int]): how many results to return (default=50)
... | Below is the the instruction that describes the task:
### Input:
Args:
query (string): elasticsearch string query
order_by (optional[string]): property by which to order results
offset (optional[int]): number of results to skip for pagination
(default=0)
... |
def index(self, value):
"""
Return the smallest index of the row(s) with this column
equal to value.
"""
for i in xrange(len(self.parentNode)):
if getattr(self.parentNode[i], self.Name) == value:
return i
raise ValueError(value) | Return the smallest index of the row(s) with this column
equal to value. | Below is the the instruction that describes the task:
### Input:
Return the smallest index of the row(s) with this column
equal to value.
### Response:
def index(self, value):
"""
Return the smallest index of the row(s) with this column
equal to value.
"""
for i in xrange(len(self.parentNode)):
if g... |
def amountdiv(number, minnum, maxnum):
"""
Get the amount of numbers divisable by a number.
:type number: number
:param number: The number to use.
:type minnum: integer
:param minnum: The minimum number to check.
:type maxnum: integer
:param maxnum: The maximum number to check.
>... | Get the amount of numbers divisable by a number.
:type number: number
:param number: The number to use.
:type minnum: integer
:param minnum: The minimum number to check.
:type maxnum: integer
:param maxnum: The maximum number to check.
>>> amountdiv(20, 1, 15)
5 | Below is the the instruction that describes the task:
### Input:
Get the amount of numbers divisable by a number.
:type number: number
:param number: The number to use.
:type minnum: integer
:param minnum: The minimum number to check.
:type maxnum: integer
:param maxnum: The maximum numbe... |
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locat... | Return a dict of all available VM locations on the cloud provider with
relevant data | Below is the the instruction that describes the task:
### Input:
Return a dict of all available VM locations on the cloud provider with
relevant data
### Response:
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if... |
def writequery(
log,
sqlQuery,
dbConn,
Force=False,
manyValueList=False
):
"""*Execute a MySQL write command given a sql query*
**Key Arguments:**
- ``sqlQuery`` -- the MySQL command to execute
- ``dbConn`` -- the db connection
- ``Force`` -- do not exit code if erro... | *Execute a MySQL write command given a sql query*
**Key Arguments:**
- ``sqlQuery`` -- the MySQL command to execute
- ``dbConn`` -- the db connection
- ``Force`` -- do not exit code if error occurs, move onto the next command
- ``manyValueList`` -- a list of value tuples if executin... | Below is the the instruction that describes the task:
### Input:
*Execute a MySQL write command given a sql query*
**Key Arguments:**
- ``sqlQuery`` -- the MySQL command to execute
- ``dbConn`` -- the db connection
- ``Force`` -- do not exit code if error occurs, move onto the next comm... |
def tpt(msmobj, A, B):
r""" A->B reactive flux from transition path theory (TPT)
The returned :class:`ReactiveFlux <pyemma.msm.models.ReactiveFlux>` object
can be used to extract various quantities of the flux, as well as to
compute A -> B transition pathways, their weights, and to coarse-grain
the... | r""" A->B reactive flux from transition path theory (TPT)
The returned :class:`ReactiveFlux <pyemma.msm.models.ReactiveFlux>` object
can be used to extract various quantities of the flux, as well as to
compute A -> B transition pathways, their weights, and to coarse-grain
the flux onto sets of states.
... | Below is the the instruction that describes the task:
### Input:
r""" A->B reactive flux from transition path theory (TPT)
The returned :class:`ReactiveFlux <pyemma.msm.models.ReactiveFlux>` object
can be used to extract various quantities of the flux, as well as to
compute A -> B transition pathways, ... |
def add_usr_local_bin_to_path(log=False):
""" adds /usr/local/bin to $PATH """
if log:
bookshelf2.logging_helpers.log_green('inserts /usr/local/bin into PATH')
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
capture=True):
try:
sudo('echo "export... | adds /usr/local/bin to $PATH | Below is the the instruction that describes the task:
### Input:
adds /usr/local/bin to $PATH
### Response:
def add_usr_local_bin_to_path(log=False):
""" adds /usr/local/bin to $PATH """
if log:
bookshelf2.logging_helpers.log_green('inserts /usr/local/bin into PATH')
with settings(hide('warnin... |
def from_dict(vpc_config, do_sanitize=False):
"""
Extracts subnets and security group ids as lists from a VpcConfig dict
Args:
vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds'
do_sanitize (bool): whether to sanitize the VpcConfig dict before extracting values
... | Extracts subnets and security group ids as lists from a VpcConfig dict
Args:
vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds'
do_sanitize (bool): whether to sanitize the VpcConfig dict before extracting values
Returns:
Tuple of lists as (subnets, security... | Below is the the instruction that describes the task:
### Input:
Extracts subnets and security group ids as lists from a VpcConfig dict
Args:
vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds'
do_sanitize (bool): whether to sanitize the VpcConfig dict before extract... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.